Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add controls vertically instead of horizontally using flow layout

I am adding checkboxes on JPanel in FlowLayout the checkboxes are being added horizontally.

I want to add checkboxes vertically on the Panel. What is the possible solution?

like image 500
adesh Avatar asked Nov 22 '12 10:11

adesh


People also ask

How do I change alignment in flow layout?

If the container is wider than necessary for a row of components, the row is, by default, centered horizontally within the container. To specify that the row is to aligned either to the left or right, use a FlowLayout constructor that takes an alignment argument.

Which method is used to set the element in flow layout?

The layout is set by the method setLayout();

What is setLayout in Java?

The setLayout(...) method allows you to set the layout of the container, often a JPanel, to say FlowLayout, BorderLayout, GridLayout, null layout, or whatever layout desired. The layout manager helps lay out the components held by this container.


2 Answers

I hope what you are trying to achieve is like this. For this please use Box layout.

package com.kcing.kailas.sample.client;  import javax.swing.BoxLayout; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.WindowConstants;  public class Testing extends JFrame {      private JPanel jContentPane = null;      public Testing() {         super();         initialize();     }      private void initialize() {         this.setSize(300, 200);         this.setContentPane(getJContentPane());         this.setTitle("JFrame");     }      private JPanel getJContentPane() {         if (jContentPane == null) {             jContentPane = new JPanel();             jContentPane.setLayout(null);              JPanel panel = new JPanel();              panel.setBounds(61, 11, 81, 140);             panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));             jContentPane.add(panel);              JCheckBox c1 = new JCheckBox("Check1");             panel.add(c1);             c1 = new JCheckBox("Check2");             panel.add(c1);             c1 = new JCheckBox("Check3");             panel.add(c1);             c1 = new JCheckBox("Check4");             panel.add(c1);         }         return jContentPane;     }      public static void main(String[] args) throws Exception {         Testing frame = new Testing();         frame.setVisible(true);         frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);     } } 
like image 71
Sunil luitel Avatar answered Sep 19 '22 15:09

Sunil luitel


I used a BoxLayout and set its second parameter as BoxLayout.Y_AXIS and it worked for me:

panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); 
like image 44
Nakul Sudhakar Avatar answered Sep 17 '22 15:09

Nakul Sudhakar