/* This is a box layout using horizontal method * */ import javax.swing.*; import java.awt.event.*; import java.awt.*; // Needed for box layout public class BoxHorizontal extends JFrame { JPanel panel; JButton yellow; JButton red; JButton blue; public BoxHorizontal() { // Set the title of the window setTitle("Box Layout"); // Sets the size of the window setSize(300, 100); // Sets the action when the window is close setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Sets the start location of the window setLocationRelativeTo(null); // Creates a horizontal box Box box = Box.createHorizontalBox(); // Create three buttons yellow = new JButton("Yellow"); red = new JButton("Red"); blue = new JButton("Blue"); // Add the buttons to the horizontal box box.add(yellow); box.add(red); box.add(blue); // Create action listener for the buttons yellow.addActionListener(new ButtonListener()); red.addActionListener(new ButtonListener()); blue.addActionListener(new ButtonListener()); // Create a panel panel = new JPanel(); // Add box layout to the panel panel.add(box); // Add the panel to the content pane add(panel); // Sets the visibility of the window setVisible(true); } /* The buttons click event are handle here * */ public class ButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { if(e.getSource()==yellow) { JOptionPane.showMessageDialog(null, "You've clicked a yellow button"); } if(e.getSource()==red) { JOptionPane.showMessageDialog(null, "You've clicked a red button"); } if(e.getSource()==blue) { JOptionPane.showMessageDialog(null, "You've clicked a blue button"); } } } public static void main(String[] args) { new BoxHorizontal(); } }