62,623
社区成员
发帖
与我相关
我的任务
分享import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MultiPanel extends JPanel {
private static final long serialVersionUID = 1L;
private JButton changeButton1;
private JButton changeButton2;
private JButton changeButton3;
private JPanel panel1;
private JPanel panel2;
private JPanel panel3;
private JPanel currentPanel;
public MultiPanel() {
this.setLayout(new BorderLayout());
changeButton1 = new JButton("<html><font color=red>Red Panel</font></html>");
changeButton2 = new JButton("<html><font color=green>Green Panel</font></html>");
changeButton3 = new JButton("<html><font color=blue>Blue Panel</font></html>");
panel1 = new JPanel();
panel2 = new JPanel();
panel3 = new JPanel();
panel1.setBackground(Color.RED);
panel2.setBackground(Color.GREEN);
panel3.setBackground(Color.BLUE);
currentPanel = panel1;
Box box = Box.createHorizontalBox();
box.add(changeButton1);
box.add(changeButton2);
box.add(changeButton3);
this.add(box, BorderLayout.SOUTH);
this.add(currentPanel, BorderLayout.CENTER);
addButtonActionListener();
}
private void addButtonActionListener() {
changeButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
currentPanel.setVisible(false);
currentPanel = panel1;
currentPanel.setVisible(true);
add(currentPanel, BorderLayout.CENTER);
validate();
}
});
changeButton2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
currentPanel.setVisible(false);
currentPanel = panel2;
currentPanel.setVisible(true);
add(currentPanel, BorderLayout.CENTER);
validate();
}
});
changeButton3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
currentPanel.setVisible(false);
currentPanel = panel3;
currentPanel.setVisible(true);
add(currentPanel, BorderLayout.CENTER);
validate();
}
});
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("Multi Panel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 600);
MultiPanel panel = new MultiPanel();
frame.getContentPane().add(panel, BorderLayout.CENTER);
frame.setVisible(true);
}
/**
* @param args
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
MultiPanel.createAndShowGUI();
}
});
}
}