简体   繁体   中英

I am trying to add a JButton array that I added to a panel onto my JFrame, yet nothing is showing up

Here is my code: For some reason nothing will appear on my screen, yet I don't know why, I believe I am initializing it correctly and adding it. Help?

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

}

}

Thanks for any help! Also sorry for any confusion it is that my buttons wont appear on the screen not that the frame will no appear.

Call mainFrame.setVisible(true); last

private void Start()
{

    JFrame mainFrame = new JFrame("MineSweeper");
    // Move this...
    //mainFrame.setVisible(true);
    //...
    mainFrame.add(p1, BorderLayout.CENTER); 
    // To here
    mainFrame.setVisible(true);
}

You should also launch you application with the context of the EDT. Take a look at Initial Threads for more details

You should also avoid using a MouseListener on buttons, they have a ActionListener API which includes notification when the use clicks the button or "active" key (usually Enter or Space )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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