单击按钮时更改照片 [英] Change photo when you click a button

查看:117
本文介绍了单击按钮时更改照片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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;

}

我删除了不必要的代码。
每次点击按钮时如何更改照片?
单击按钮时,iter变量递增。
但它不会改变照片。它只显示a1.jpg
我想要发生的是,每次点击按钮,它都会显示下一张照片(a2.jpg,a3.jpg,a4.jpg ......)

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 ...)

推荐答案

你永远不会在JLabel上调用 pic.setIcon(...)你的ActionListener。您只能在Stage1构造函数中调用一次,因此JLabel的Icon将永远不会更改。解决方案是在侦听器中调用此方法。

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.

你的问题是一个神奇的思考,认为如果你改变一个变量引用的对象,对该对象的所有其他引用也会改变,但是这不是Java的工作方式。当您更改ic引用的Icon时,这对JLabel中显示的当前对象没有影响。你必须编写代码来自行更改。

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.

这篇关于单击按钮时更改照片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆