从另一个 JPanel 更改 JFrames 的面板 class

Change the JFrames' panel from another JPanel class

所以我在我的 Main 中得到了这个 class:

public class Main extends JFrame {

public static void main(String[] args) {       
    JFrame Launch = new JFrame();
    Launch.setSize(800, 400);
    Launch.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Launch.setContentPane(new StartView());
    Launch.setTitle("De Hartige Hap");
    Launch.setVisible(true);        
    }
}

现在假设我在那个小组中 ("StartView()")

onClick 在按钮上,我想更改框架的内容窗格..

我该怎么做?

public class StartView extends javax.swing.JPanel {
public StartView() {
    initComponents();
}



private void OrderButtonActionPerformed(java.awt.event.ActionEvent evt) {                                            
   /*instead of Launch.setContentPane(new StartView());
    *it has to be (new otherView())
    */
}

将您的 Launch 对象传递给您的面板对象(即新 StartView(launch))。这样,您可以在 Launch 中创建一个方法 changeView(),您可以从您的面板 (launch.changeView()) 调用此方法,您可以在该方法中更改您的视图。

此外,如果我可以建议您,请查看 ModelViewController 模式。这确保您将视图(您的面板)和控制器(您的框架)分开,这样您就不会遇到这样的问题。