用java的swing实现一个框架上有两个分页面,按钮实现页面跳转
时间: 2024-02-03 18:15:54 浏览: 84
好的,下面是一个简单的实现:
```java
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class DemoFrame extends JFrame implements ActionListener {
private JPanel cardPanel;
private CardLayout cardLayout;
public DemoFrame() {
setTitle("分页面跳转示例");
setSize(500, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 创建两个分页面
JPanel page1 = new JPanel();
page1.add(new JButton("这是第一页"));
JPanel page2 = new JPanel();
page2.add(new JButton("这是第二页"));
// 创建按钮面板
JPanel btnPanel = new JPanel();
JButton btn1 = new JButton("第一页");
btn1.setActionCommand("page1");
btn1.addActionListener(this);
btnPanel.add(btn1);
JButton btn2 = new JButton("第二页");
btn2.setActionCommand("page2");
btn2.addActionListener(this);
btnPanel.add(btn2);
// 创建卡片布局面板
cardLayout = new CardLayout();
cardPanel = new JPanel(cardLayout);
cardPanel.add(page1, "page1");
cardPanel.add(page2, "page2");
add(cardPanel, BorderLayout.CENTER);
add(btnPanel, BorderLayout.SOUTH);
}
@Override
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
// 根据按钮的指令切换分页面
cardLayout.show(cardPanel, cmd);
}
public static void main(String[] args) {
DemoFrame frame = new DemoFrame();
frame.setVisible(true);
}
}
```
运行程序后,可以看到一个带有两个按钮和两个分页面的窗口。点击按钮可以实现页面的切换。
阅读全文