目录

一、程序预览

二、程序代码


一、程序预览

java swing实现点击按钮切换图片(简单实现)-LMLPHP

二、程序代码

package learnProject.csdn;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

/**
 * 
 * @author Roc-xb
 *
 */
public class ImageSwitcher extends JFrame {
	private static final long serialVersionUID = 1L;
	private JLabel imageLabel;
	private JButton button1, button2, button3, button4;

	public ImageSwitcher() {
		setTitle("美女Switcher");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setSize(400, 400);
		setLayout(new BorderLayout());

		// 创建图片标签
		imageLabel = new JLabel();
		imageLabel.setHorizontalAlignment(JLabel.CENTER);
		add(imageLabel, BorderLayout.CENTER);

		// 创建按钮面板
		JPanel buttonPanel = new JPanel();
		buttonPanel.setLayout(new FlowLayout());

		// 创建按钮
		button1 = new JButton("美女1");
		button2 = new JButton("美女2");
		button3 = new JButton("美女3");
		button4 = new JButton("美女4");

		// 添加按钮点击事件监听器
		button1.addActionListener(new ButtonClickListener());
		button2.addActionListener(new ButtonClickListener());
		button3.addActionListener(new ButtonClickListener());
		button4.addActionListener(new ButtonClickListener());

		// 将按钮添加到按钮面板
		buttonPanel.add(button1);
		buttonPanel.add(button2);
		buttonPanel.add(button3);
		buttonPanel.add(button4);

		// 将按钮面板添加到窗口底部
		add(buttonPanel, BorderLayout.SOUTH);

		// 模拟点击第一个按钮
		button1.doClick();

		// 显示窗口
		setVisible(true);
	}

	// 按钮点击事件监听器
	class ButtonClickListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			JButton source = (JButton) e.getSource();
			String buttonText = source.getText();

			// 根据按钮文本设置对应的图片
			switch (buttonText) {
			case "美女1":
				imageLabel.setIcon(new ImageIcon("C:\\Users\\Administrator\\Desktop\\sc\\01.jpeg"));
				break;
			case "美女2":
				imageLabel.setIcon(new ImageIcon("C:\\Users\\Administrator\\Desktop\\sc\\02.jpeg"));
				break;
			case "美女3":
				imageLabel.setIcon(new ImageIcon("C:\\Users\\Administrator\\Desktop\\sc\\03.jpeg"));
				break;
			case "美女4":
				imageLabel.setIcon(new ImageIcon("C:\\Users\\Administrator\\Desktop\\sc\\04.jpeg"));
				break;
			}
		}
	}

	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				new ImageSwitcher();
			}
		});
	}
}
10-14 23:12