Java 按钮未出现在 JPanel 中

标签 java swing jbutton

只有当我将鼠标移到“不可见按钮”上时,这些按钮才不会出现在我的 JPanel 中...

那不是我的代码。所以,我的代码看起来没问题,但没有出现在我的 JPanel 中...我只是尝试重新验证并重新绘制 JPanel,但什么也没发生...

for (int i; i < 5; i++) {
  JButton button = new JButton();
  button.setText("" + i);
  button.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent ae) { 

       System.out.print("\n Test: " + ae.getActionCommand());

     } 
  });
  button.setSize(60,20);
  button.setLocation(100, 140);
  button.setVisible(true);
  this.add(button);
  this.revalidate();
  this.repaint();
}

最佳答案

如果有人遇到这个问题...

只需输入: 按钮.requestFocusInWindow();//在方法的最后一行...

像这样:

for (int i; i < 5; i++) {
JButton button = new JButton();
button.setText("" + i);
button.addActionListener(new ActionListener() {
 public void actionPerformed(ActionEvent ae) { 

   System.out.print("\n Test: " + ae.getActionCommand());

 } 
});
button.setSize(60,20);
button.setLocation(100, 140);
button.setVisible(true);
this.add(button);
this.revalidate();
this.repaint();
button.requestFocusInWindow(); 

}

关于Java 按钮未出现在 JPanel 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18838621/

相关文章:

java - 通知大图标看起来很小

从 native pthread 调用时不调用 Java 方法

Java Spring Controller 拒绝除 GET 之外的所有请求

Java 复选框操作

java - 将按钮放置在图像顶部

java - 如何让Java服务器发送ison响应

java - 不同的回车和鼠标点击事件

java - 在java中打印jframe

java - Java 中 JButton 的击键/热键

java - 如何在窗口内移动 3 个按钮