如何使用 JButton link 一个 JFrame class 与另一个 JPanel

How to link a JFrame class with another JPanel using JButton

我在学校有一个构建应用程序的项目。由于我对 Java 世界很陌生,所以我很挣扎。

我决定在 NetBeans 中工作并尝试以某种方式动态创建应用程序。我在源包中动态创建了一个 JFrame class 并在那里(动态地)添加了几个按钮。

然后我创建了另一个 JPanel class,我想 link 使用 JFrame 中的 Jbutton link class class。但是我不知道 JFrameJFrame class 中是如何被调用的,这意味着我不能从中添加或删除任何东西,只能动态地进行。

我尝试创建一个名为 JFrame 的新实例,但它只会显示找不到符号。

我也尝试只调用 JFrame (Frame.add(nr)) 但它只写了

non-static method add cannot be referenced from a static context 

public class Frame extends javax.swing.JFrame {

    public Frame()  {
        initComponents();
    }

    private void createRecipeActionPerformed(java.awt.event.ActionEvent evt) {  

        intro.show(false);
        NewRecipe nr = new NewRecipe(); 
        Frame.add(nr); 
        nr.show(true);
    } 

我的预期结果是:当在 JFrame 中单击 JButton 时,将出现 JPanel

看来您是 java 和挥杆的新手。因此,我将提供以下代码作为示例供您开始使用。我认为它可以满足您的需求。所以,稍微玩一下,试着了解发生了什么。

您可能需要多玩几个示例 UI 才能理解 java 的 "pattern" 和摇摆。

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

public class Frame extends JFrame {

  private JButton button;

  public Frame() {
    initComponents();
  }

  private void initComponents() {
    button = new JButton("Add New Recipe Panel");
    button.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        Frame.this.getContentPane().add(new NewRecipe(), BorderLayout.CENTER);
        Frame.this.getContentPane().revalidate();
      }
    });
    this.getContentPane().add(button, BorderLayout.NORTH);
  }

  public static void main(String[] args) {
    Frame frame = new Frame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setBounds(200, 100, 400, 300);
    frame.setVisible(true);
  }

  class NewRecipe extends JPanel {

    NewRecipe() {
      this.add(new JLabel("New Recipe"));
    }
  }
}