简体   繁体   中英

How would I use a JButton to change a JLabel with every click of a button?

I need to start off with a JLabel, for example a JLabel that reads,"Old Text". With a button click, I want to update that JLabel to, "Updated Text". I am able to do this with the code I posted below, but my issue is I want to be able to click the button again to go back to "Old Text" and so on. Basically, I need the button to allow me to alternate between those two texts but I can't get that to work.

// this doesn't switch back to "Old Code"

public void actionPerformed(ActionEvent event) {
    if(event.getSource() == jbutton)
        jlabel.setText("Updated Text");

    if(event.getSource() == jbutton)
        jlabel.setText("Old Text");

}

This works but isn't what I fully need because it only changes the JLabel once.

public void actionPerformed(ActionEvent event) {
    if(event.getSource() == jbutton)
        jlabel.setText("Updated Text");
}

The reason your code isn't work is, both if statements evaluate to true , so both get executed

There are several ways you might do this, probably the simplest is just to inspect the state of the text of the label and make some decision about what to do, for example...

public void actionPerformed(ActionEvent event) { if(event.getSource() == jbutton) jlabel.setText("Updated Text");

    if(event.getSource() == jbutton) {
        if (!jlabel.getText().equals("Old Text")) {
            jlabel.setText("Old Text");
        } else {
            jlabel.setText("Updated text");
        }
    }

}

Now, if you wanted to be "really" fancy, you could use a little bit of modular maths...

private int trigger = 0;
@Override
public void actionPerformed(ActionEvent e) {
    trigger++;
    if ((trigger % 2) == 0) {
        label.setText("Old text");
    } else {
        label.setText("Updated text");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM