簡體   English   中英

文件正確編譯,但未顯示JFrame

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

我一直在嘗試使此代碼正常工作,但我不知道它有什么問題。 我顯示的所有內容都表明可以正確聲明JFrame,但是我已經完成了它,但是它沒有出現。 這是我的代碼:

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

我對編碼的理解不足以診斷問題,因此我來這里尋求幫助。 先感謝您!

那是因為您沒有調用test()方法。 看來您的意圖是使此方法成為構造函數:

  public void test() {
    gui();
  }

相反,它應該是(構造函數沒有返回類型):

  public test() {
    gui();
  }

這是一個簡單的錯誤。 您需要一個類的創建實例,然后調用方法gui()。 您應該將測試重命名為Test。 這是最佳做法。

在此處輸入圖片說明

我制作了一個測試對象,並調用了名為gui();測試方法gui(); 在里面。

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