I'm using a grid layout for one of my programs and when i try to add JTextFields to the grid It doesn't show at all. If i try adding JButtons instead of JTextFields in the same method it works perfectly.
package suDUKO;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Toolkit;
import javax.swing.JTextField;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
public class Gui_Class {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension blocksize;
private final int screenW=(int) (screenSize.getWidth()/2);
private final int screenH=(int) (screenSize.getHeight()/2);
JFrame frame;
JPanel panel;
public Gui_Class() {
frame=new JFrame("Suduko");
frame.setBounds((int) screenW-500,screenH-500,500,500);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setVisible(true);
panel=new JPanel();
frame.add(panel);
panel.setVisible(true);
panel.setLayout(new GridLayout(9, 9));
JTextField [][] table = new JTextField[9][9];
for(int m = 0; m < 9; m++) {
for(int n = 0; n < 9; n++) {
table[m][n]=new JTextField(m+" "+n);
table[m][n].setVisible(true);
panel.add(table[m][n]);
}
}
}
}
There are a number of problems with this code. The main ones that you asked about, can be fixed by adding all the components, then calling pack()
before finally calling setVisible(true);
.
If the code as seen above does those things, the GUI won't be 500 x 500 in size, and will not be centered. Each has it's own best approach.
Firstly, it seems you want the content pane to be square (500 x 500), and that won't happen if the frame is 500 x 500, because it has a title bar and possibly borders to render. Then centering a GUI on screen is as simple as frame.setLocationRelativeTo(null)
.
You've already marked this correct, but was just preparing an example of what is written above, so here it is!
import java.awt.*;
import javax.swing.*;
public class Gui_Class {
JFrame frame;
JPanel panel;
public Gui_Class() {
frame = new JFrame("Suduko");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
panel = new JPanel(new GridLayout(9, 9));
frame.add(panel);
//panel.setVisible(true); //unnecessary
JTextField[][] table = new JTextField[9][9];
for (int m = 0; m < 9; m++) {
for (int n = 0; n < 9; n++) {
table[m][n] = new SquareTextField(m + " " + n);
panel.add(table[m][n]);
}
}
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
Runnable r = () -> {
new Gui_Class();
};
SwingUtilities.invokeLater(r);
}
}
class SquareTextField extends JTextField {
int size = 30;
SquareTextField(String s) {
super(s);
setFont(getFont().deriveFont((float)size));
int sz = size/6;
setMargin(new Insets(sz, sz, sz, sz));
}
@Override
public Dimension getPreferredSize() {
Dimension d = super.getPreferredSize();
int w = d.width;
int h = d.height;
int max = w>h ? w : h;
return new Dimension(max, max);
}
}