Change photo when you click a button

2019-03-04 19:10发布

问题:

import javax.swing.Icon;
import javax.swing.ImageIcon;


public class Stage1 extends javax.swing.JFrame {


    int score = 0;
    int iter = 1;


    public Stage1() {
        initComponents();
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setTitle("Stage 1");
        Icon ic = new ImageIcon("a"+ iter + ".jpg");
        pic.setIcon(ic);


    }


    private void submitActionPerformed(java.awt.event.ActionEvent evt) {                                       

        if(answer.getText().equals("input"))
        {
            score++;
            iter++;
            answer.setText("");
            String sc = Integer.toString(score);
            jLabel1.setText(sc);
            jLabel2.setText(Integer.toString(iter));
        }
        else
        {
            iter++;
            Icon ic = new ImageIcon("a"+ iter +".jpg");
            answer.setText("");
            jLabel2.setText(Integer.toString(iter));
        }


    }                                      


    public static void main(String args[]) {

        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Stage1().setVisible(true);
            }
        });
    }


    private javax.swing.JTextField answer;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel pic;
    private javax.swing.JButton submit;

}

I deleted the unnecessary codes. How to change the photo every time you click a button? When I click the button, the iter variable increments. But it doesn't change the photo. It only shows the a1.jpg What I want to happen is that every time I click the button, it will show the next photo (a2.jpg, a3.jpg, a4.jpg ...)

回答1:

You never call pic.setIcon(...) on the JLabel within your ActionListener. You only call it once within the Stage1 constructor, and so the JLabel's Icon will never change. The solution is to call this method within the listener.

Your problem is one of "magical thinking", thinking that if you change the object that a variable refers to, all other references to the object will change as well, but that's not how Java works. When you change the Icon that ic refers to, this has no effect on the current object displayed in the JLabel. You have to write code to change it yourself.