问题描述
我想在 JPanel 中添加 52 个按钮。全部带有 ActionListeners。当我达到一定数量 (13) 并运行程序时,并非所有按钮都显示出来。例如,我添加了 15 个按钮,但只显示了 9 或 12 个。有时是全部,但不是每次都如此。
以下是两个 JButton 的代码:
JButton button_one=new JButton();
button_one.setPreferredSize(new Dimension(100,150));
mainpanel.add(button_one);
button_one.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent button_1_picked){
amount_of_cards_picked=amount_of_cards_picked+1;
cardamountcheck();
if(twocardspicked==true){
userpick2=0;
System.out.println(setoutcards[userpick2]);
pairdetermination();
}
else if(twocardspicked==false){
userpick1=0;
System.out.println(setoutcards[userpick1]);
}
}
});
JButton button_two = new JButton();
button_two.setPreferredSize(new Dimension(100,150));
mainpanel.add(button_two);
button_two.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent button_2_picked){
amount_of_cards_picked=amount_of_cards_picked+1;
cardamountcheck();
if(twocardspicked==true){
userpick2=1;
System.out.println(setoutcards[userpick2]);
pairdetermination();
}
else if(twocardspicked==false){
userpick1=1;
System.out.println(setoutcards[userpick1]);
}
}
});
基本上,当单击这些按钮之一时,我的代码中的变量会发生变化。 这些按钮运行良好,完全按照我的要求工作,但是当它们超过 13 个时它们不会全部出现,而我需要 52 个。
解决方法
我想在 JPanel 中添加 52 个按钮。全部使用 ActionListeners。
完成。我创建了一个显示 52 JButtons
的 GUI。我把它们做成了 OP 大小的一半,所以 GUI 会更适合答案。
在 GridLayout
上使用 JPanel
相当简单。
这是完整的可运行代码。一个最小的可重现示例。
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class FiftyTwoJButtonGUI implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new FiftyTwoJButtonGUI());
}
@Override
public void run() {
JFrame frame = new JFrame("52 JButton GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createMainPanel(),BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createMainPanel() {
JPanel panel = new JPanel(new GridLayout(0,13,5,5));
panel.setBorder(BorderFactory.createEmptyBorder(5,5));
CardListener listener = new CardListener();
for (int i = 0; i < 52; i++) {
JButton button = new JButton("" + (i + 1));
button.addActionListener(listener);
button.setPreferredSize(new Dimension(50,75));
panel.add(button);
}
return panel;
}
public class CardListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent event) {
JButton button = (JButton) event.getSource();
int cardNumber = Integer.valueOf(button.getText());
System.out.println(cardNumber);
}
}
}