繁体   English   中英

为什么我的按钮不显示?

[英]Why do my buttons wont show up?

我想构建一个包含以下源代码的Bingo,该源代码应创建一个JFrame,其中将25个按钮放置在5x5矩阵中。 但是我的按钮没有任何形式被绘制在窗口上。

我已经创建了一个Jpanel,在其上放置了按钮,这些位置并没有具体说明,稍后会进行微调,第一件事就是将它们绘制在窗口上。

Bingo Buttons是一个扩展JFrame的类,它仅添加了两种方法,一种将其状态从true切换为false,另一种方法是用于检查按钮当前为true还是false的方法(isSet)。

bingoField是一个字符串数组,除了按钮应获取的数据外,不保存其他任何内容。

我不明白为什么它什么都不做,请帮帮我。 任何帮助都将受到高度赞赏!

public class BingoFrame extends JFrame {

public static final int BINGOSIZE=25;
public static final int BUTTON_X=50;
public static final int BUTTON_Y=50;

public BingoFrame() {
    setResizable(false);
    String[] bingoField = null;
    BingoButton[] buttons=new BingoButton[25];

try {
  bingoField = Utils.getRandomBingoField("Test");
} catch (FileNotFoundException e) {
  e.printStackTrace();
} catch (IOException e) {
  e.printStackTrace();
}

this.setTitle("BS Bingo");
this.setResizable(false);
this.setLocation(50, 50);
this.setSize(600, 800);
this.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(null);

JPanel buttonPanel = new JPanel();
buttonPanel.setBounds(0, 0, 594, 772);
getContentPane().add(buttonPanel);
buttonPanel.setLayout(null);

for(int i=0;i<BINGOSIZE;i++) {
  buttons[i] = new BingoButton("Text");
}

//decorate buttons and add an action listener
for(int i=0;i<BINGOSIZE;i++) {
  final BingoButton temp = buttons[i];
  temp.setText(bingoField[i]);
  temp.setBackground(Color.white);
  temp.setForeground(Color.blue);
  temp.setPreferredSize(new Dimension(BUTTON_X,BUTTON_Y));

  temp.addActionListener(new ActionListener() {
    boolean toggle = false;
    @Override
    public void actionPerformed(ActionEvent e) {
      if (!temp.isSet()) {
        temp.setBackground(Color.blue);
        temp.setForeground(Color.white);
      } else {
        temp.setBackground(Color.white);
        temp.setForeground(Color.blue);
      }
      temp.toggle();
    }
  });

  buttons[i]=temp;
} 

//set Location for the buttons
for(int i=0;i<5;i++) {
    buttons[i].setLocation(100,(50*i)+10*(i+1));
}    
for(int i=5;i<10;i++) {
    buttons[i].setLocation(160,(50*i)+10*(i+1));
}
for(int i=10;i<15;i++) {
    buttons[i].setLocation(220,(50*i)+10*(i+1));
}
for(int i=15;i<20;i++) {
    buttons[i].setLocation(280,(50*i)+10*(i+1));
}
for(int i=20;i<25;i++) {
    buttons[i].setLocation(340,(50*i)+10*(i+1));
}

//add buttons to the panel
for(int i=0;i<BINGOSIZE;i++) {
  buttonPanel.add(buttons[i]);
}    

this.setVisible(true);   

我得到了答案。

我已经将面板的布局更改为网格布局。 这将使按钮恰好位于5x5矩阵中应有的位置,以及它们之间的期望间距。 这也使定位代码完全过时了。

通过简单地将Layout更改为GridLayout,我所有的问题都消失了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM