[英]Java - change from Panel1 to Panel2
我想創建一個簡單的Java應用程序,但遇到一些問題。 這是我的主要課程:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.Component;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class MainWindow {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainWindow window = new MainWindow();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public MainWindow() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.getContentPane().add(panel, BorderLayout.CENTER);
JButton btnNewButton = new JButton("First B");
panel.add(btnNewButton);
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
SecWindow SW = new SecWindow();
//-----
}
});
}
}
次生類:
import javax.swing.JButton;
import javax.swing.JPanel;
public class SecWindow {
public SecWindow() {
SecPanel();
}
public void SecPanel() {
JPanel panel2 = new JPanel();
JButton btnNewButton_2 = new JButton("Sec B");
panel2.add(btnNewButton_2);
}
}
我該怎么做:當我按下“ First B
”時,我想刪除第一個面板並創建一個新的類SecWindow()
。
我該怎么做:當我按下“ First B”時,我想刪除第一個面板並創建一個新的SecWindow()類。
您應該使用CardLayout
。 CardLayout允許您交換框架中的面板。
閱讀Swing教程中有關如何使用CardLayout的部分, 以獲取更多信息和工作示例。
該示例使用組合框交換面板,因此您只需要將該代碼移動到按鈕的ActionListener即可。
try{
secWindow secondWindow = new secWindow();
secondWindow.frame.setVisible(true);
window.frame.setVisible(false);
} catch (Exception e) {
e.printStackTrace();
這將隱藏第一個窗口,並顯示第二個窗口。 您不能完全“刪除”其中具有main方法的對象。 您的應用將以主要方法開始和結束。
相反,您可以創建新類並在那兒轉移主要方法
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.