I am writing a program to solve Sudoku puzzles. I create the user interface using AWT/Swing.
One panel of the main window (JFrame object) contains a Graphics2D component only (a grid for the sudoku puzzle). The problem is that this panel is too small for its contents when it is created. I have tried many things to make it bigger (like the setSize method of the panel), but to no avail. Who can tell me how I can make the panel with a single Graphics2D object larger?
Below is the code for the main window, which is a JFrame object. I set its size to 400 x 400 to have ample room for all panels. I then create two panels: a sudoku panel that contains the sudoku grid and a button panel that contains two buttons. The button panel has a flow layout.
I then create the main panel. This has a vertical BoxLayout. Finally I add the sudoku panel and the button panel to the main panel and the main panel to the frame.
public class ViewController_Graphics extends JFrame { JButton solveButton = new JButton("Solve"); JButton nakedSinglesButton = new JButton("Naked Singles"); public ViewController_Graphics(SudokuModel model) { super("Sudoku"); setSize(400,400); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLookAndFeel(); // create sudoku panel SudokuPanel sudokuPanel = new SudokuPanel(); // create button panel JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new FlowLayout(FlowLayout.LEFT)); buttonPanel.add(solveButton); buttonPanel.add(nakedSinglesButton); //create main panel JPanel mainPanel = new JPanel(); mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS)); mainPanel.add(sudokuPanel); mainPanel.add(buttonPanel); // show frame add(new JScrollPane(mainPanel)); setVisible(true); } }
Below is the code for the SudokuPanel class.
class SudokuPanel extends JPanel { final int X_OFFSET = 10; final int Y_OFFSET = 10; final int WIDTH = 30; final int HEIGHT = 30; final float LIGHTSTROKE = 1.0f; final float BOLDSTROKE = 2.0f; public void paintComponent(Graphics comp) { Graphics2D comp2D = (Graphics2D)comp; comp2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); comp2D.setColor(Color.black); for (int x = 0; x < 9; x++) { for (int y = 0; y < 9; y++) { int xPos = X_OFFSET + (x * WIDTH); int yPos = Y_OFFSET + (y * HEIGHT); comp2D.setStroke(new BasicStroke(LIGHTSTROKE, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_MITER)); comp2D.draw(new Rectangle2D.Double(xPos, yPos, WIDTH, HEIGHT)); if (((x % 3) == 0) && ((y % 3) == 0)) { comp2D.setStroke(new BasicStroke(BOLDSTROKE, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_MITER)); comp2D.draw(new Rectangle2D.Double(xPos, yPos, WIDTH * 3, HEIGHT * 3)); } } } } }
When I run the program, the following Window shows up:
As you can see, the button panel is exactly in the middle (and it remains in the middle, no matter how I resize the window). And there is not enough room for the sudoku panel.
How can I make enough room for the sudoku panel when the window is created?