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);
lastYou 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 aActionListener
API which includes notification when the use clicks the button or "active" key (usually Enter or Space)