简体   繁体   中英

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. 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. 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(). You should rename the test to Test. It's best practice.

在此处输入图片说明

I made a test object and called test method which was calling 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();
    }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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