本帖最後由 tonyh 於 2019-6-22 12:58 編輯
試分別使用「成員內部類別」與「匿名內部類別」,實作「MouseListener介面」或繼承「MouseAdapter類別」,完成如下的視窗程式,視窗上的圖案點擊便能置換,且彼此不會相互干擾。
JFrame的設定: 100, 100, 420, 320
JLabel的設定:
50, 20, 128, 128
250, 20, 128, 128
50, 160, 128, 128
250, 160, 128, 128
- import javax.swing.JFrame;
- import javax.swing.JLabel;
- import javax.swing.ImageIcon;
- import java.awt.event.MouseListener;
- import java.awt.event.MouseAdapter;
- import java.awt.event.MouseEvent;
- public class Ch101{
-
- private JFrame fm;
- private JLabel lb1,lb2,lb3,lb4;
- private ImageIcon ii,ii1,ii2,ii3,ii4,iig1,iig2,iig3,iig4;
- private Try1 try1=new Try1();
- Ch101()
- {
- ii=new ImageIcon(Ch101.class.getResource("pic/star.png"));
- ii1=new ImageIcon(Ch101.class.getResource("pic/1.png"));
- ii2=new ImageIcon(Ch101.class.getResource("pic/2.png"));
- ii3=new ImageIcon(Ch101.class.getResource("pic/3.png"));
- ii4=new ImageIcon(Ch101.class.getResource("pic/4.png"));
- iig1=new ImageIcon(Ch101.class.getResource("pic/g1.png"));
- iig2=new ImageIcon(Ch101.class.getResource("pic/g2.png"));
- iig3=new ImageIcon(Ch101.class.getResource("pic/g3.png"));
- iig4=new ImageIcon(Ch101.class.getResource("pic/g4.png"));
-
- lb1=new JLabel(iig1);
- lb1.setBounds(50, 20, 128, 128);
- lb1.addMouseListener(try1);
- lb2=new JLabel(iig2);
- lb2.setBounds(250, 20, 128, 128);
- lb2.addMouseListener(new Try2());
-
- lb3=new JLabel(iig3);
- lb3.setBounds(50, 160, 128, 128);
- lb3.addMouseListener(new MouseListener(){ //匿名式
- public void mousePressed(MouseEvent e)
- {
- if(lb3.getIcon()==iig3)
- lb3.setIcon(ii3);
- else
- lb3.setIcon(iig3);
- }
- public void mouseReleased(MouseEvent e){}
- public void mouseClicked(MouseEvent e){}
- public void mouseEntered(MouseEvent e){}
- public void mouseExited(MouseEvent e){}
- });
-
- lb4=new JLabel(iig4);
- lb4.setBounds(250, 160, 128, 128);
- lb4.addMouseListener(new MouseAdapter(){ //匿名式
- public void mousePressed(MouseEvent e)
- {
- if(lb4.getIcon()==iig4)
- lb4.setIcon(ii4);
- else
- lb4.setIcon(iig4);
- }
- });
-
- fm=new JFrame("滑鼠指標拖曳圖形");
- fm.setBounds(100, 100, 420, 320);
- fm.setIconImage(ii.getImage());
- fm.setVisible(true);
- fm.setResizable(false);
- fm.setLayout(null);
- fm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- fm.add(lb1);
- fm.add(lb2);
- fm.add(lb3);
- fm.add(lb4);
- }
- class Try1 implements MouseListener //成員式
- {
- public void mousePressed(MouseEvent e)
- {
- if(lb1.getIcon()==iig1)
- lb1.setIcon(ii1);
- else
- lb1.setIcon(iig1);
- }
- public void mouseReleased(MouseEvent e){}
- public void mouseClicked(MouseEvent e){}
- public void mouseEntered(MouseEvent e){}
- public void mouseExited(MouseEvent e){}
- }
- class Try2 extends MouseAdapter //成員式
- {
- public void mousePressed(MouseEvent e)
- {
- if(lb2.getIcon()==iig2)
- lb2.setIcon(ii2);
- else
- lb2.setIcon(iig2);
- }
- }
- public static void main(String[] args) {
- new Ch101();
- }
- }
複製代碼 |