本帖最後由 tonyh 於 2015-10-3 14:11 編輯
實作指標位置對準圖片, 點擊滑鼠左鍵切換圖片.
- import javax.swing.JFrame;
- import javax.swing.JLabel;
- import javax.swing.ImageIcon;
- import java.awt.event.MouseListener;
- import java.awt.event.MouseEvent;
- public class Ch88 implements MouseListener{
-
- private JFrame fm;
- private JLabel lb;
- private ImageIcon icon1,icon2,icon3;
- private int x=100,y=100;
-
- Ch88()
- {
- icon1=new ImageIcon(Ch88.class.getResource("pic/star.png"));
- icon2=new ImageIcon(Ch88.class.getResource("pic/gift-green.png"));
- icon3=new ImageIcon(Ch88.class.getResource("pic/hippo.png"));
-
- lb=new JLabel(icon2);
- lb.setBounds(x, y, 128, 128);
- lb.addMouseListener(this);
-
- fm=new JFrame("點按滑鼠切換圖形");
- fm.setBounds(100, 100, 420, 320);
- fm.setIconImage(icon1.getImage());
- fm.setResizable(false);
- fm.setLayout(null);
- fm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- fm.add(lb);
- }
-
- public void mousePressed(MouseEvent e)
- {
- if(lb.getIcon()==icon2)
- lb.setIcon(icon3);
- else
- lb.setIcon(icon2);
- }
- public void mouseReleased(MouseEvent e){}
-
- public void mouseClicked(MouseEvent e){}
-
- public void mouseEntered(MouseEvent e){}
-
- public void mouseExited(MouseEvent e){}
- public static void main(String[] args) {
- Ch88 app=new Ch88();
- }
- }
複製代碼 |