当我切换 JPanels 时什么也没有出现

Nothing is appearing when i switch JPanels

我是 Java 的新手,我创建了一个主页和几个按钮,当我单击其中一个按钮时,它会将主页面板的可见性设置为 false,打开一个新的 class 并将 classes Jpanel 设置为可见。

homePanel.setVisible(false);
Goodsin Barcode = new Goodsin();
Goodsin.setVisible(true);

但是,一旦打开新的 class "Goodsin",它就不会显示任何按钮或文本文件。我知道它正在打开新的 class 作为 System.out.println 打印到控制台,但 JFrame 中没有任何显示,我不知道为什么。

这是我的新代码 class

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;


public class Goodsin {

    public JPanel Goodsin;
    public JTextField item1;
    public String code;
    public JButton btn1;

    public Goodsin() {

        System.out.println("TEST");

        Goodsin = new JPanel();
        item1 = new JTextField(10);
        btn1 = new JButton("Look up Barcode");

        Goodsin.setVisible(true);

        Goodsin.add(item1);
        item1.setSize(80, 30);

        Goodsin.add(btn1);
        btn1.setSize(80, 30);

    }

    public void getString(String code) {
        System.out.println(code);

    }

}

我确定我没有正确使用 Jpanel 或添加文本字段或按钮,但到目前为止我看到的所有答案都没有用。

我建议您将面板添加到 JFrame。您可以通过从 class 扩展 JFrame 或在您的构造函数中简单地实例化一个 JFrame 来做到这一点。然后您可以根据需要简单地添加和删除(或设置 visible/invisible)。不过,请务必在更改可见性后验证您的 JFrame/JPanel。

尝试做这样的事情:

    Goodsin = new JPanel();
      item1 = new JTextField(10);
      btn1 = new JButton("Look up Barcode");

       item1.setSize(80, 30);
       Goodsin.add(item1);

       btn1.setSize(80, 30);
      Goodsin.add(btn1);

    JFrame frame = new JFrame("JFrame Example");
      Goodsin.setLayout(new FlowLayout());
      frame.add(Goodsin);

我建议您尝试以下代码:

public class Goodsin extends JFrame{

    public static void main(String[] args) {
        Goodsin ui = new Goodsin();
        JTextField item1 = new JTextField(10);
        JButton btn1 = new JButton("Look up Barcode");
        JPanel centralPanel = new JPanel(new FlowLayout());
        centralPanel.add(item1);
        centralPanel.add(btn1);
        item1.setSize(80, 30);
        btn1.setSize(80, 30);
        ui.add(centralPanel);

        ui.pack();
        ui.setVisible(true);

    }
}

在我的示例中,一切都在 main 方法中完成,但是您仍然可以改进此代码并以更好的方式重构它。

只需要在面板中设置Bounds of Goods或者设置Size然后在首页frame中添加即可