我的任务是在JPAnel上创建选中的板。为此,我试图用带有边框的JPanels填充父级JPanel,但是由于某些原因,代码未给出期望的结果,并且未显示任何错误来调查原因。这是代码:
private static class GlassView extends JFrame {
private static int width = 600;
private static int height = 750;
public GlassView() {
this.setSize(width, height);
this.setVisible(true);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void workingFrame() {
int cols = 0;
int rows = 0;
String frameName = "Bot World";
WorkFrame workF = new WorkFrame(0, 0, frameName);
wfFrame = workF.newFrame();
wfFrame.setExtendedState(JFrame.MAXIMIZED_BOTH);
wfFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
wfFrame.setVisible(true);
JSplitPane splitPane = new JSplitPane();
splitPane.setSize(width, height);
splitPane.setDividerSize(0);
splitPane.setDividerLocation(150);
splitPane.setOrientation(JSplitPane.HORIZONTAL_SPLIT);
JPanel panelLeft = createLftPanel();
JPanel panelRight = createRightPanel();
splitPane.setLeftComponent(panelLeft);
splitPane.setRightComponent(panelRight);
wfFrame.add(splitPane);
}
}
这是需要检查的panelRight的代码:
public static JPanel createRightPanel() {
JPanel panel = new JPanel();
int rows = 100;
int cols = 100;
panel.setLayout(new GridLayout(rows, cols));
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
JPanel pane = new JPanel();
pane.add(new JTextField("both"));
pane.setBorder(BorderFactory.createLineBorder(Color.black));
panel.add(new JButton(""));
}
}
return panel;
}
任何帮助将不胜感激。谢谢
[好吧,我的第二个猜测是,在调用]之后,框架没有重新布置>
wfFrame.setVisible(true);
对我来说,下面的例子:
public class Framed { public static void workingFrame() { JFrame frame = new JFrame(); frame.setExtendedState(JFrame.MAXIMIZED_BOTH); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); frame.getContentPane().add(createRightPanel(10, 10)); frame.revalidate(); // <-- HERE } public static JPanel createRightPanel(int rows, int cols) { JPanel panel = new JPanel(new GridLayout(rows, cols)); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { JPanel pane = new JPanel(); pane.setBackground((i+j)%2==0?Color.black:Color.white); panel.add(pane); } } return panel; } public static void main(String... none) throws Exception { workingFrame(); } }
显示一个检查器网格,但是您是否删除了对它的调用>
frame.revalidate(); // <-- HERE
然后不显示网格(直到您对框架进行某些操作以使其再次布局为止)。比调用revalidate()更好的方法是只在添加所有组件之后才调用setVisible。