2017-08-05 117 views
0

如何在單擊按鈕的幫助下在圖片之間切換。 我犯了一個x變量,因爲這樣我可以讓if語句不同,而是因爲我做錯了什麼事是沒有工作對我來說,可能是......這是到目前爲止我的代碼:如何使用JButton更改圖像

public class Main extends JFrame{ 

    private JButton changePic; 
    private JPanel panel; 
    private JLabel pic1; 
    private JLabel pic2; 
    private JLabel pic3; 
    private JLabel picture; 
    private int x = 0; 

    public Main(){ 

     panel = new JPanel(); 
     add(panel); 

     changePic = new JButton("Change Button"); 
     panel.add(changePic); 


     pic1 = new JLabel(new ImageIcon("pic1.png")); 
     pic2 = new JLabel(new ImageIcon("pic.png")); 
     pic3 = new JLabel(new ImageIcon("pic3.png")); 

     panel.add(pic1); 
     panel.add(pic2); 
     panel.add(pic3); 

     changePic.addActionListener(new ActionListener(){ 
      public void actionPerformed(ActionEvent e){ 
       if(e.getSource() == changePic){ 

       } 
      } 
     }); 
     getContentPane().setBackground(Color.white); 
     setSize(300, 300); 
     setVisible(true); 
     setDefaultCloseOperation(EXIT_ON_CLOSE); 

    } 

    public static void main(String[] args){ 
     Main fr = new Main(); 
    } 
} 
+1

‘但並沒有爲我工作’,你可以澄清‘沒有工作’ ?你期望你的代碼做什麼,是什麼讓你思考,以及發生了什麼? – Pshemo

+0

當我按下它沒有交換圖片的按鈕。我看到的唯一圖像是第一(PIC1)\t changePic.addActionListener(新的ActionListener(){ \t \t \t公共無效的actionPerformed(ActionEvent的發送){ \t \t \t \t如果(e.getSource()== changePic){ \t \t \t \t \t如果(X == 0){ \t \t \t \t \t \t panel.add(PIC1); \t \t \t \t \t} else if(x == 1){ \t \t \t \t \t \t panel.add(pic2); \t \t \t \t \t}否則如果(X == 2){ \t \t \t \t \t \t panel.add(PIC3); \t \t \t \t \t} \t \t \t \t \t X ++; \t \t \t \t \t如果(X> 2) \t \t \t \t \t \t X = 0; \t \t \t \t} \t \t \t} \t \t}); –

+2

使用[編輯]選項更新您的問題與問題描述和您的代碼(因爲它在評論部分是不可讀的)。 – Pshemo

回答

0
public class Main extends JFrame{ 

    private JButton changePic; 
    private JPanel panel; 

    private JLabel pic1; 
    private int x = 0; 

    public Main(){ 

     panel = new JPanel(); 
     add(panel); 

     changePic = new JButton("Change Button"); 
     panel.add(changePic); 


     pic1 = new JLabel(); 
     panel.add(pic1); 
     ImageIcon icon1 = new ImageIcon("pic1.gif"); 
     ImageIcon icon2 = new ImageIcon("pic2.gif"); 
     ImageIcon icon3 = new ImageIcon("pic3.gif"); 

     changePic.addActionListener(new ActionListener(){ 

      public void actionPerformed(ActionEvent e){ 
       if(e.getSource() == changePic){ 
        if(x == 0){ 
         pic1.setIcon(icon1); 
        }else if(x == 1){ 
         pic1.setIcon(icon2); 
        }else if(x == 2){ 
         pic1.setIcon(icon3); 
        } 
        Main.this.pack(); 
        x++; 
        if(x > 2) x = 0; 

       } 
      } 
     }); 
     getContentPane().setBackground(Color.white); 
     setSize(300, 300); 
     setVisible(true); 
     setDefaultCloseOperation(EXIT_ON_CLOSE); 

    } 

    public static void main(String[] args){ 
     Main fr = new Main(); 
    } 
} 
  • 您不需要多個JLabel s,而是使用3 ImageIcon s。
  • 需要調用每一個你有UI變化時JFramepack()(在 這種情況下,改變圖像)