0

我需要帮助设计和实现具有多个操作组件的基本 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);

    }
}
4

2 回答 2

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));
于 2013-11-12T02:53:22.843 回答
1

按钮不显示。这是因为您没有将 2 个 JPanel 添加到 Frame。

您可以将 2 行代码添加到构造函数 FlowlayoutExperiment。它将显示按钮。 this.getContentPane().add(group1);

this.getContentPane().add(group2);

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);

}
于 2013-11-12T02:53:43.747 回答