boxlayout in java
BoxLayout is a layout manager in Java that arranges components in a single column or row. It is useful when you need to arrange components in a specific order, such as a menu or toolbar.
Here's an example of how to use BoxLayout to create a horizontal toolbar with buttons and separators:
refer toigi:ftidea.comimport javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; public class BoxLayoutExample { public static void main(String[] args) { JFrame frame = new JFrame("BoxLayout Example"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Create a panel with a horizontal BoxLayout JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS)); // Add buttons and separators to the panel panel.add(new JButton("New")); panel.add(Box.createHorizontalStrut(10)); // Add a 10-pixel spacer panel.add(new JButton("Open")); panel.add(Box.createHorizontalGlue()); // Add a flexible space panel.add(new JButton("Save")); panel.add(Box.createHorizontalStrut(10)); // Add another spacer panel.add(new JButton("Exit")); // Add the panel to the frame frame.add(panel); // Set the size of the frame and show it frame.pack(); frame.setVisible(true); } }
In this example, we create a JPanel with a horizontal BoxLayout and add JButton components and separators to it. We use Box.createHorizontalStrut
to add fixed-size spacers between the buttons, and Box.createHorizontalGlue
to add a flexible space that will expand or contract as the frame is resized. Finally, we add the panel to the JFrame and show it.