Home > OS >  Creating two buttons in JPanel side by side
Creating two buttons in JPanel side by side

Time:10-17

I am trying to make two buttons in JPanel side by side. I have the following code as of now:

JFrame frame = new JFrame("Display Shapes");
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
JButton button = new JButton();
button.setBounds(50,100,80,30);

button.setText("Load Shapes");
panel.add(button);
JButton button2 = new JButton();
button2.setBounds(100,100,80,30);

button.setText("Sort Shapes");
panel.add(button2);

frame.add(panel);
frame.setSize(600, 600);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);

When I run the code, below is the output I see. I am not sure why the second button is not appearing correctly. What could be the reason for this?

CodePudding user response:

The place where you are writing button.setText("Sort Shapes");, it will be button2.setText("Sort Shapes");

It is changing the text of the first button whose text had been set earlier

  • Related