这是我的代码: 由于某种原因,我的屏幕上不会出现任何内容,但我不知道为什么,我相信我正在正确初始化它并添加它。帮助?
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class main implements MouseListener{
final int WIDTH = 800, HEIGHT = 500, BOARD_WIDTH = 10, BOARD_HEIGHT = 10;
private JButton [][]buttons = new JButton[BOARD_WIDTH][BOARD_HEIGHT];
public static void main(String[] args) {
// TODO Auto-generated method stub
new main();
}
public main()
{
Start();
}
private void Start()
{
JFrame mainFrame = new JFrame("MineSweeper");
mainFrame.setVisible(true);
mainFrame.setSize(WIDTH,HEIGHT);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setLocationRelativeTo(null);
mainFrame.setResizable(false);
mainFrame.setLayout(new BorderLayout());
JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(BOARD_WIDTH, BOARD_HEIGHT));
for(int x = 0; x < BOARD_WIDTH; x++)
for(int y = 0; y < BOARD_HEIGHT; y++)
{
buttons[x][y] = new JButton("01");
buttons[x][y].addMouseListener(this);
p1.add(buttons[x][y]);
}
mainFrame.add(p1, BorderLayout.CENTER);
}
@Override
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
}
感谢您的帮助! 也很抱歉造成任何困惑,因为我的按钮不会出现在屏幕上,而不是框架不会出现。
最佳答案
最后调用mainFrame.setVisible(true);
private void Start()
{
JFrame mainFrame = new JFrame("MineSweeper");
// Move this...
//mainFrame.setVisible(true);
//...
mainFrame.add(p1, BorderLayout.CENTER);
// To here
mainFrame.setVisible(true);
}
您还应该在 EDT 上下文中启动应用程序。看看Initial Threads了解更多详情
您还应该避免在按钮上使用 MouseListener
,它们有一个 ActionListener
API,其中包括用户单击按钮或“Activity ”键(通常是 Enter 或 Space)时的通知
关于java - 我正在尝试将添加到面板的 JButton 数组添加到 JFrame 上,但没有显示任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20060923/