Change photo when you click a button

十年热恋 提交于 2019-12-02 16:43:21

问题


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.



来源:https://stackoverflow.com/questions/42894194/change-photo-when-you-click-a-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!