gpt4 book ai didi

java - 制作在 JPanel 上显示的网格布局

转载 作者:行者123 更新时间:2023-12-02 09:18:07 24 4
gpt4 key购买 nike

我的任务是在 JPAnel 上创建检查板。为此,我尝试使用具有边框的 JPanel 填充父 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。

关于java - 制作在 JPanel 上显示的网格布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58864319/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com