我在学校有一个构建应用程序的项目。因为我对Java世界还很陌生,所以我一直在努力。
我决定在NetBeans中工作,并尝试以某种方式动态创建应用程序。我在Source Packages中动态创建了一个JFrame
类,并在那里(动态地)添加了几个按钮。
然后,我创建了另一个JPanel
类,我想使用JFrame
类中的Jbutton链接到JFrame
类。但是,我不知道在JFrame
类中如何调用JFrame
,这意味着我无法动态添加或删除任何内容。
我尝试创建一个名为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);
}
我的预期结果是:在JButton
中单击JFrame
时,将出现JPanel
。
答案 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"));
}
}
}