简体   繁体   English

自定义 JFrame 类没有出现

[英]Custom JFrame class doesn't appear

This compiles fine but nothing is visible when it executes the code.这编译得很好,但在执行代码时什么都看不到。 What do I need to change?我需要改变什么?

I've removed my Swing/AWT imports so I could post the question.我已经删除了我的 Swing/AWT 导入,所以我可以发布问题。 The code is short and so is my question but apparently that's not good enough...代码很短,我的问题也是如此,但显然这还不够好......

class Exercise1 {
    public static void main(String[] args) {
        new MyFrame("Test");
    }
}

class MyFrame extends JFrame{
    public MyFrame(String title){
        super(title);
        int i = 2;
        int j = 2;
        JPanel[][] panelHolder = new JPanel[i][j];    
        setLayout(new GridLayout(i,j));
        for(int m = 0; m < i; m++) {
            for(int n = 0; n < j; n++) {
                panelHolder[m][n] = new JPanel();
                add(panelHolder[m][n]);
            }
        }
        JTextField t1 = new JTextField();
        JTextField t2 = new JTextField();
        JTextField t3 = new JTextField();
        panelHolder[2][0].add(t1);
        panelHolder[2][1].add(t2);
        panelHolder[2][2].add(t3);
        setVisible(true);
    }
}

This compiles fine but nothing is visible when it executes the code.这编译得很好,但在执行代码时什么都看不到。

Because you get a run time Exception.因为你得到一个运行时异常。

Array indexes are 0 based.数组索引从 0 开始。

    int i = 2;
    int j = 2;
    JPanel[][] panelHolder = new JPanel[i][j];   

You create a 2D array with room for 2 values in each of your 2 rows.您创建了一个二维数组,在 2 行中的每一行中都有 2 个值的空间。

    panelHolder[2][0].add(t1);
    panelHolder[2][1].add(t2);
    panelHolder[2][2].add(t3);

But you try to add components to the third row/value, which causes the Exception.但是您尝试将组件添加到第三行/值,这会导致异常。

Change you array sizes to 3, or only use indexes 0 and 1.将数组大小更改为 3,或仅使用索引 0 和 1。

Also, when you create a JTextField use:此外,当您创建 JTextField 时,请使用:

new JTextField(10);

so the text fields has a reasonable size.所以文本字段有一个合理的大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM