Note that there are some explanatory texts on larger screens.

plurals
  1. POJava basic if/else statement state change
    primarykey
    data
    text
    <p>please see my attached code below and then my question at the end.</p> <pre><code>class events extends JFrame{ private JLabel label; private JButton button; public events() { setLayout(new FlowLayout()); button = new JButton("Click for text"); add(button); label = new JLabel(""); add(label); event e = new event(); button.addActionListener(e); } public class event implements ActionListener { public void actionPerformed(ActionEvent e) { int x = 0; if (x == 0) { label.setText("the new label"); System.out .println("setting x to 0 and label to display a label"); x = 1; System.out.println(x); } else { label.setText("newerer label"); System.out.println("i reached the else segment"); x = 0; System.out.println(x); } } } public static void main(String args[]) { events gui = new events(); gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); gui.setTitle("Events Test"); gui.setSize(300, 100); gui.setVisible(true); } } </code></pre> <p>Background: I am learning java and attempting to understand a concept. With this program I was attempting to create a small gui with a button that when clicked would assign a JLabel the String value of "the new label." I wanted to use that same button however to change the label to "newerer label" if clicked a second time and back again if clicked a third. I attempted to do this using an If/ Else statement with a variable x to hold essentially a state of 1 or 0. At the end of each portion of the If/Else i change the state of x to either 1 or 0 appropriately. When attempting to run the program in eclipse however, I have run into some kind of error. I assigned a system.out.println to each portion of the If/Else in an attempt to see how the program switches between the two states but it appears that my else statement is never reached. </p> <p>Questions: </p> <ol> <li>Is an If/Else statement appropriate to perform such a simple 2 state switch?</li> <li>Is there a more appropriate way to do this? (i know about switch statements but opted for this as it was only a two state project).</li> <li>What did I do wrong and why is my Else path never achieved when the state should be 1?</li> </ol> <p>Thank you for your responses, Pano</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload