本文教程,主要提供一个简单的例子,使用java swing完成点击按钮能够切换图片。
目录
一、程序预览
二、程序代码
一、程序预览
二、程序代码
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();}});}
}