[英]How to link a JFrame class with another JPanel using JButton
我在學校有一個構建應用程序的項目。 因為我對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);
}
我的預期結果是:在JFrame
單擊JButton
時,將顯示JPanel
。
看來您是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"));
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.