【发布时间】:2015-08-20 06:17:56
【问题描述】:
我正在尝试制作一个 2x2 网格布局,左上角有一个 JLabel,其他三个空格上有三个按钮。当我这样做时,我得到一个大按钮(填满整个 JDialog)的意外结果,上面写着“你想推我吗”。不知道为什么会出现这个结果,请帮忙,谢谢!
public void sinceyoupressedthecoolbutton() {
JDialog replacementwindow = new JDialog(); //Like a window
JButton best = new JButton("best");
JButton first = new JButton("FIRST");
JButton second = new JButton("Second");
replacementwindow.setLayout(new GridLayout(2,3,0,0)); //Row, column, distance horizontally, distance vertical
JPanel panel = new JPanel();
replacementwindow.add(panel); //adding the JPanel itself
replacementwindow.add(first);
replacementwindow.add(second);
replacementwindow.add(best);
replacementwindow.setSize(500, 500);
replacementwindow.setTitle("NEW WINDOW!");
replacementwindow.setVisible(true);
}
【问题讨论】:
-
不,您编辑的代码不是我建议的。您将组件添加到“面板”,然后将组件添加到“replacementWindow”。不要将组件直接添加到对话框中。
-
尝试你的方法后,网格外观丢失了..?当我将组件添加到面板时,它看起来像是多个按钮排列在一起。为什么会这样?
-
it looked like multiple buttons just lined up- 因为您没有将布局管理器设置为 GridLayout。 JPanel 的默认布局管理器是 FlowLayout。最后一个答案,您需要花时间阅读教程以学习一些基础知识。问我一个关于您阅读的内容的问题,我会回答,但我不是在这里教您基础知识,即教程中的示例的用途。您甚至可以查看教程中的How to Use a GridLayout演示以获取工作代码。从教程中学习正确的技术。 -
好的,我非常感谢您为给我详细解释所付出的时间和精力。如果我在阅读您推荐的教程后有任何问题,我一定会告诉您!谢谢你,我喜欢你的回答!
标签: java swing jbutton layout-manager grid-layout