如何使用JButton将JFrame类与另一个JPanel链接

时间:2018-12-20 13:42:29

标签: java swing jframe jpanel jbutton

我在学校有一个构建应用程序的项目。因为我对Java世界还很陌生,所以我一直在努力。

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

然后,我创建了另一个JPanel类,我想使用JFrame类中的Jbutton链接到JFrame类。但是,我不知道在JFrame类中如何调用JFrame,这意味着我无法动态添加或删除任何内容。

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

我还尝试仅调用JFrameFrame.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);
    } 

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

1 个答案:

答案 0 :(得分:0)

看来您是Java和swing的新手。因此,我首先提供以下代码作为示例。我认为它可以满足您的需求。因此,请稍作尝试,并尝试了解发生了什么。

您可能需要再玩几个示例UI才能理解Java和swing的“模式”。

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