你如何在Java中的面板中使用网格布局?

时间:2013-11-16 02:27:44

标签: java swing jframe jpanel grid-layout

我试图用两个面板创建一个JFrame。顶部面板将包含一个文本字段,底部面板将包含一个按钮网格。我已经使用gridLayout来排列按钮并将它们添加到面板中并将面板添加到JFrame但是根据编辑器,面板的值为NULL。第二个小组也是如此。有人可以帮我解决问题吗?

import java.awt.*;
import javax.swing.*;

public class frameClass extends JFrame{
    private static final long serialVersionUID = 1L;
private JFrame frame;

private JPanel panel;
private JPanel panel2;

private JButton button0;
private JButton button1;
private JButton button2;
private JButton button3;

public frameClass() {
    panel = new JPanel(new GridLayout(4,4,5,5));            

    panel.setBackground(Color.BLACK);

    Font font1 = new Font("SanSerif",Font.BOLD, 16);

    button0 = new JButton("0");
    button0.setFont(font1);
    button0.setBackground(Color.BLACK);
    button0.setForeground(Color.WHITE);
    panel.add(button0);

    button1 = new JButton("1");
    button1.setFont(font1);
    button1.setBackground(Color.WHITE);
    panel.add(button1);

    button2 = new JButton("2");
    button2.setFont(font1);
    button2.setBackground(Color.BLACK);
    button2.setForeground(Color.WHITE);
    panel.add(button2);

    button3 = new JButton("3");
    button3.setFont(font1);
    button3.setBackground(Color.WHITE);
    panel.add(button3);

            frame.add(panel);
            panel2 = new JPanel(new BorderLayout());
    panel2.add(new JTextField(21), BorderLayout.CENTER);

    frame.add(panel2);
    frame.setVisible(true);
}
public static void main(String[] args) {
    new calculator();       
}
}

1 个答案:

答案 0 :(得分:4)

“核心”问题不是面板是空的,而frame是空的......

// You extend from JFrame, which isn't highly recommended
// but you seem to ignore...
public class FrameClass extends JFrame {

    private static final long serialVersionUID = 1L;
    // Instance variable of frame, but it's never initialised...
    private JFrame frame;

    private JPanel panel;
    private JPanel panel2;

    //...

    public FrameClass() {
        // Create panel...
        panel = new JPanel(new GridLayout(4, 4, 5, 5));
        panel.setBackground(Color.BLACK);

        //...

        // Add it to frame, but frame is null...
        frame.add(panel);

        //...
    }

相反,请尝试删除extends JFrame并实例化JFrame

的实例
public class FrameClass {

    private static final long serialVersionUID = 1L;
    private JFrame frame;

    private JPanel panel;
    private JPanel panel2;

    //...

    public FrameClass() {
        panel = new JPanel(new GridLayout(4, 4, 5, 5));

        //...

        frame = new JFrame("Testing");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.add(panel);
        panel2 = new JPanel(new BorderLayout());
        panel2.add(new JTextField(21), BorderLayout.CENTER);

        frame.add(panel2);

        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }