1、打开eclipse
2、新建一个java 项目
输入以下代码:
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class GUIExample {
private JFrame frame;
private JPanel panel1;
private JPanel panel2;
public GUIExample() {
frame = new JFrame("界面切换与背景颜色示例");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
panel1 = new JPanel();
panel1.setLayout(new FlowLayout());
JButton button1 = new JButton("切换到面板2");
button1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
frame.setContentPane(panel2);
frame.getContentPane().setBackground(Color.YELLOW);
frame.revalidate();
}
});
panel1.add(button1);
panel2 = new JPanel();
panel2.setLayout(new FlowLayout());
JButton button2 = new JButton("切换到面板1");
button2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
frame.setContentPane(panel1);
frame.getContentPane().setBackground(Color.GRAY);
frame.revalidate();
}
});
panel2.add(button2);
frame.setContentPane(panel1);
frame.getContentPane().setBackground(Color.GRAY);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new GUIExample();
}
});
}
}
运行结果展示如下:
最后:“码《图文》不易,浏览到此文也算是缘分,还请留下点痕迹再离开哟”!!!!!!!!!!
喜欢的小伙伴记得收藏点赞哦,谢谢支持!