I am trying to add some buttons but it only shows button3 , I don't know why I didn't found any duplicate with other question
How I can make each one of these buttons to show(when someone clicked them) on a label the value of a variable? Please if anyone can help
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);
}
});
}
答案 0 :(得分:1)
如果您不知道并且只是想看到所有按钮,您可以尝试这样做:
将您的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