swing Java GUI布局建议
对于学校作业,我需要有两个面板
右边需要有3x3个按钮(我在设置GUI时将其变成黑色以便于识别),左边有1个标签和4个按钮
标签应显示当前图片的名称(随机放置在3x3网格中的按钮上),3个按钮用于随机放置图像,一个按钮用于清除图像。我不需要逻辑上的帮助,我可以做那部分
我在设置面板时遇到了问题,所以它看起来有点像样。我想把它做成1x5网格,但我不知道怎么做。我花了好几个小时查找如何做,以及尝试我自己的东西(注意被注释掉的东西)。任何帮助都将不胜感激
public class Characters extends JFrame {
private Container pane;
private JButton Button1, Button2, Button3, Button4, Button5, Button6;
private JButton Button7, Button8, Button9;
private JButton BMolly, BOctavious, BJimmy, BClear;
private ImageIcon Molly, Octavious, Jimmy;
private JLabel LName;
public Characters() {
setTitle("Characters");
pane = getContentPane();
pane.setLayout(new GridLayout(3, 3));
Button1 = new JButton((Icon) Button1);
Button1.setBackground(Color.BLACK);
pane.add(Button1);
Button2 = new JButton((Icon) Button2);
Button2.setBackground(Color.BLACK);
pane.add(Button2);
Button3 = new JButton((Icon) Button3);
Button3.setBackground(Color.BLACK);
pane.add(Button3);
Button4 = new JButton((Icon) Button4);
Button4.setBackground(Color.BLACK);
pane.add(Button4);
Button5 = new JButton((Icon) Button5);
Button5.setBackground(Color.BLACK);
pane.add(Button5);
Button6 = new JButton((Icon) Button6);
Button6.setBackground(Color.BLACK);
pane.add(Button6);
Button7 = new JButton((Icon) Button7);
Button7.setBackground(Color.BLACK);
pane.add(Button7);
Button8 = new JButton((Icon) Button8);
Button8.setBackground(Color.BLACK);
pane.add(Button8);
Button9 = new JButton((Icon) Button9);
Button9.setBackground(Color.BLACK);
pane.add(Button9);
LName = new JLabel(" ");
pane.add(LName);
BMolly = new JButton("Molly");
pane.add(BMolly);
BOctavious = new JButton("Octavious");
pane.add(BOctavious);
BJimmy = new JButton("Jimmy");
pane.add(BJimmy);
BClear = new JButton("Clear");
pane.add(BClear);
pack();
setResizable(false);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(final String[] args) {
new Characters();
}
}
# 1 楼答案
您的代码有一些问题,按照惯例,变量名以小写字母开头,并且每行代码只应执行一项操作(甚至声明变量)。此外,除非要扩展类的功能,否则不应该“扩展”类,如果要做的只是使用它,那么只需创建自己的
对于你的问题,你需要考虑使用多个布局(它们甚至可以相互嵌入来提供一些非常复杂的效果)-Swing layoutsJFrame
实例。(哦,当你在fourms上发布代码寻求帮助时,如果你觉得有必要添加注释以忽略未使用的警告,那么你可能也不需要在问题中发布它:p)我使用了borderLayout和BoxLayout来实现你所需要的东西
# 2 楼答案
您需要的是两个不同的面板
如果它仍然不工作,我可以添加完整的代码
# 3 楼答案
处理布局管理器的非常好的起点是Java documentation。对于您的需要,看起来BorderLayout manager应该是不错的选择
阅读how to use layout managers的例子,它给你第一眼