我需要设计方面的帮助,并实现具有多个动作组件的基本GUI。目标是创建两个面板和六个按钮。每个面板有三个按钮。
到目前为止,我在Java虚拟机中编码。我的代码似乎很正确,但输出不显示按钮。你能帮忙找出按钮没有显示的原因吗?
顺便说一句,我有一张照片。我希望我的设计像这样。
http://i1199.photobucket.com/albums/aa467/Jordan_Sanjaya/Picture1.png
我的代码:
import javax.swing.*;
import java.awt.*;
public class FlowlayoutExperiment extends JFrame {
FlowLayout experimentLayout = new FlowLayout();
private JButton firstButton = new JButton("Button 1");
private JButton secondButton = new JButton("Button 2");
private JButton thirdButton = new JButton("Button 3");
private JButton fourthButton = new JButton("Button 4");
private JButton fifthButton = new JButton("Button 5");
private JButton sixthButton = new JButton("Button 6");
public FlowlayoutExperiment ()
{
JPanel group1 = new JPanel();
setLayout(new GridLayout(3,1));
group1.add(firstButton);
group1.add(secondButton);
group1.add(thirdButton);
JPanel group2 = new JPanel();
setLayout(new GridLayout(3,1));
group2.add(fourthButton);
group2.add(fifthButton);
group2.add(sixthButton);
}
public static void main(String[] args)
{
FlowlayoutExperiment frame = new FlowlayoutExperiment();
frame.setTitle("Button Panel Example");
frame.setSize(600, 75);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
答案 0 :(得分:1)
您好像忘记将群组添加到任何内容
public FlowlayoutExperiment ()
{
JPanel group1 = new JPanel();
setLayout(new GridLayout(3,1));
group1.add(firstButton);
group1.add(secondButton);
group1.add(thirdButton);
JPanel group2 = new JPanel();
setLayout(new GridLayout(3,1));
group2.add(fourthButton);
group2.add(fifthButton);
group2.add(sixthButton);
// This is important ;)
add(group1);
add(group2);
}
您还要设置框架的布局而不是组
你可能想要改变......
JPanel group1 = new JPanel();
setLayout(new GridLayout(3,1));
//...
JPanel group2 = new JPanel();
setLayout(new GridLayout(3,1));
要
JPanel group1 = new JPanel();
group1.setLayout(new GridLayout(3,1));
//...
JPanel group2 = new JPanel();
group2.setLayout(new GridLayout(3,1));
答案 1 :(得分:1)
按钮未显示。这是因为您没有将2个JPanel添加到Frame。
您可以向构造函数FlowlayoutExperiment添加2行代码。它会使按钮显示出来。 的 this.getContentPane()添加(组1); 强>
<强> this.getContentPane()添加(组2); 强>
public FlowlayoutExperiment() {
JPanel group1 = new JPanel();
setLayout(new GridLayout(3, 1));
group1.add(firstButton);
group1.add(secondButton);
group1.add(thirdButton);
JPanel group2 = new JPanel();
setLayout(new GridLayout(3, 1));
group2.add(fourthButton);
group2.add(fifthButton);
group2.add(sixthButton);
this.getContentPane().add(group1);
this.getContentPane().add(group2);
}