简体   繁体   English

文件正确编译,但未显示JFrame

[英]File compiles correctly, yet JFrame doesn't appear

I've been trying for a bit to get this code to work, and I don't know what's wrong with it. 我一直在尝试使此代码正常工作,但我不知道它有什么问题。 Everything I've shown says to declare JFrame properly, but I've already done it and it doesn't appear. 我显示的所有内容都表明可以正确声明JFrame,但是我已经完成了它,但是它没有出现。 Here's my code: 这是我的代码:

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

public class test extends JFrame {

  private JFrame f;
  private JPanel p;
  private JButton b1;
  private JLabel lab;

  public void test() {
    gui();
  }

  public void gui() {
    JFrame f = new JFrame("Frame");
    f.setBounds(30, 30, 700, 1000);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setVisible(true);
    f.setFocusable(true);

    p = new JPanel();
    p.setBackground(Color.YELLOW);

    b1 = new JButton("Button");
    lab = new JLabel("Label");

    p.add(b1);
    p.add(lab);

    f.add(p, BorderLayout.SOUTH);
  }

  public static void main(String[] args) {
    new test();
  }
}

I don't understand coding enough to be able to diagnose the problem, so I've come here for assistance. 我对编码的理解不足以诊断问题,因此我来这里寻求帮助。 Thank you in advance! 先感谢您!

That is because you are not calling the test() method. 那是因为您没有调用test()方法。 It seems though that your intention was to make this method a constructor: 看来您的意图是使此方法成为构造函数:

  public void test() {
    gui();
  }

It should instead be (constructors don't have a return type): 相反,它应该是(构造函数没有返回类型):

  public test() {
    gui();
  }

It was a simple mistake. 这是一个简单的错误。 You need a create instance of the class and call the method gui(). 您需要一个类的创建实例,然后调用方法gui()。 You should rename the test to Test. 您应该将测试重命名为Test。 It's best practice. 这是最佳做法。

在此处输入图片说明

I made a test object and called test method which was calling gui(); 我制作了一个测试对象,并调用了名为gui();测试方法gui(); in it. 在里面。

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

public class test extends JFrame {

    private JFrame f;
    private JPanel p;
    private JButton b1;
    private JLabel lab;

    public void test() {
      gui();
    }

    public void gui() {
        JFrame f = new JFrame("Frame");
        f.setBounds(30, 30, 700, 1000);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
        f.setFocusable(true);

        p = new JPanel();
        p.setBackground(Color.YELLOW);

        b1 = new JButton("Button");
        lab = new JLabel("Label");

        p.add(b1);
        p.add(lab);

        f.add(p, BorderLayout.SOUTH);
    }

    public static void main(String[] args) {
        test t1 =  new test();
        t1.test();
    }
  }

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

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