一个jbutton对应一个jpanel
时间: 2023-06-24 12:06:51 浏览: 84
可以通过在JButton的ActionListener中切换JPanel来实现一个JButton对应一个JPanel的效果。具体实现步骤如下:
1. 创建一个主JPanel,作为容器,用于显示多个JPanel。
2. 创建多个子JPanel,每个子JPanel都包含需要显示的内容。
3. 为每个JButton添加一个ActionListener,当用户点击按钮时,切换到对应的JPanel。
4. 在ActionListener中,先从主JPanel中移除当前显示的JPanel,然后再添加需要显示的JPanel。
示例代码如下:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ButtonPanelDemo extends JFrame implements ActionListener {
private JPanel mainPanel;
private JPanel panelOne;
private JPanel panelTwo;
private JButton buttonOne;
private JButton buttonTwo;
public ButtonPanelDemo() {
setTitle("Button Panel Demo");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainPanel = new JPanel();
mainPanel.setLayout(new CardLayout());
panelOne = new JPanel();
panelOne.setBackground(Color.RED);
mainPanel.add(panelOne, "Panel One");
panelTwo = new JPanel();
panelTwo.setBackground(Color.BLUE);
mainPanel.add(panelTwo, "Panel Two");
buttonOne = new JButton("Panel One");
buttonOne.addActionListener(this);
buttonTwo = new JButton("Panel Two");
buttonTwo.addActionListener(this);
JPanel buttonPanel = new JPanel();
buttonPanel.add(buttonOne);
buttonPanel.add(buttonTwo);
add(mainPanel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == buttonOne) {
CardLayout layout = (CardLayout) mainPanel.getLayout();
layout.show(mainPanel, "Panel One");
} else if (e.getSource() == buttonTwo) {
CardLayout layout = (CardLayout) mainPanel.getLayout();
layout.show(mainPanel, "Panel Two");
}
}
public static void main(String[] args) {
ButtonPanelDemo demo = new ButtonPanelDemo();
demo.setVisible(true);
}
}
```
在这个例子中,我们创建了一个包含两个JPanel的主JPanel,并为每个JPanel创建了一个JButton。当用户点击按钮时,我们通过CardLayout来切换JPanel。
阅读全文