我正在尝试添加一些按钮,但它只显示button3,我不知道为什么 我没有发现任何与其他问题重复的内容
如何使这些按钮中的每一个都在标签上显示(当有人单击它们时)变量的值? 如果有人可以帮忙请帮忙
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class gui extends JFrame {
public gui() {
initUI();
}
private void initUI() {
JButton quitButton = new JButton("Quit");
JButton button1 = new JButton("button1");
JButton button2 = new JButton("button2");
JButton button3 = new JButton("button3");
quitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
button1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
createLayout(quitButton);
createLayout(button1);
createLayout(button2);
createLayout(button3);
setTitle("example");
setSize(500, 300);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private void createLayout(JComponent... arg) {
Container pane = getContentPane();
GroupLayout gl = new GroupLayout(pane);
pane.setLayout(gl);
gl.setAutoCreateContainerGaps(true);
gl.setHorizontalGroup(gl.createSequentialGroup()
.addComponent(arg[0])
);
gl.setVerticalGroup(gl.createSequentialGroup()
.addComponent(arg[0])
);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
gui ex = new gui();
ex.setVisible(true);
}
});
}
最佳答案
如果您不知道并且只想查看所有按钮,您可以尝试如下:
- 删除你的createLayout()
将 initUI() 方法替换为:
private void initUI() { JButton quitButton = new JButton("Quit"); JButton button1 = new JButton("button1"); JButton button2 = new JButton("button2"); JButton button3 = new JButton("button3"); JPanel panel = new JPanel(); quitButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { System.exit(0); } }); button1.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { System.exit(0); } }); getContentPane().add(panel); panel.add(quitButton); panel.add(button1); panel.add(button2); panel.add(button3); setTitle("example"); setSize(500, 300); setLocationRelativeTo(null); setDefaultCloseOperation(EXIT_ON_CLOSE); }
我强烈建议您首先阅读有关 swing 布局的文档: A Visual Guide to Layout Managers
关于java - swing java 多个按钮 gui,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36561618/