Reputation: 677
I am working on a java program that solves sudoku puzzles. So far all I have coded is a class that draws the board with swing, and another class that calls the gui class.
When I try and run the program nothing happens. No error messages are shown, but the gui doesn't show either. It immediately terminates.
Here is my code so far:
Gui class:
package sudoku;
import java.awt.*;
import javax.swing.*;
public class Gui {
Gui gui;
JPanel board;
JPanel subBoard[][];
GridLayout layout;
JLabel square[][];
public void load() {
gui = new Gui();
gui.setUp();
gui.buildBoard();
}
private void setUp() {
layout = new GridLayout(3, 3);
board = new JPanel(layout);
subBoard = new JPanel[3][3];
square = new JLabel[9][9];
}
private void buildBoard() {
// set up board
board.setSize(800, 600);
board.setVisible(true);
int mod = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
// add subBoards to board
subBoard[i][j] = new JPanel();
board.add(subBoard[i][j]);
subBoard[i][j].setLayout(layout);
subBoard[i][j].setVisible(true);
// add textfields to each subBoard
square[i + mod][j + mod] = new JLabel();
subBoard[i][j].add(square[i + mod][j + mod]);
square[i + mod][j + mod].setVisible(true);
}
mod += 3;
}
}
}
main class:
package sudoku;
public class SudokuSolver {
public static void main(String[] args) {
Gui gui = new Gui();
gui.load();
}
}
I tried running it in both eclipse and netbeans but got the same result both times. Why does this not work?
Upvotes: 0
Views: 9938
Reputation: 160
You can not show directly Jpanel. for show gui you must use JFrame or any other Window class(JDialog, JWindow...) and after that set visible property true.
setVisible(true);
public class Gui extends JFrame {
Gui(){
...
setVisible(true);
setSize(300,400);
}
...
}
Upvotes: 0
Reputation: 159754
There is no displayable window such as a JFrame
being used in the application.
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame("New GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Gui gui = new Gui();
gui.load();
frame.add(gui.getBoard()); // add getBoard getter
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
Remove the class member variable gui
within Gui
. This is shadowing variables in the outer class Gui
so use the latter instead. Also override getPreferredSize
to give the board
a size when frame.pack()
is invoked.
Upvotes: 5
Reputation: 2242
Make GUI
extend JFrame
firstly. Then in your main method call gui.setVisible(true);
.
public class Gui extends JFrame { }
Then in main.
Gui gui = new Gui();
gui.load();
gui.setVisible(true);
Upvotes: 2