我想创建一个简单的 Java 应用程序,但遇到一些问题。 这是我的主要类(class):
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()
。
最佳答案
How can I do this: when I press the "First B" I wanna delete the first panel and create a new one class SecWindow().
您应该使用CardLayout
。 CardLayout 将允许您交换框架中的面板。
阅读 Swing 教程中关于 How to Use CardLayout 的部分了解更多信息和工作示例。
该示例使用组合框来交换面板,因此您只需将该代码移至按钮的 ActionListener 即可。
关于Java - 从Panel1更改为Panel2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33350020/