首页 > 解决方案 > 在 JPanel 中并排创建两个按钮

问题描述

我正在尝试JPanel并排制作两个按钮。到目前为止,我有以下代码:

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);

当我运行代码时,下面是我看到的输出。我不确定为什么第二个按钮没有正确显示。这可能是什么原因?

标签: javaswingjframejpaneljbutton

解决方案


你写作的地方,button.setText("Sort Shapes");就是button2.setText("Sort Shapes");

它正在更改之前已设置文本的第一个按钮的文本


推荐阅读