-1

I'm just starting with Java and I wanted to make a little program that opens a jFrame with a text field in which you can write a number. Then you press a button and another jFrame with a jPanel, which will turn green if the number is even, and black if it's odd. I edited the code of the jPanel so that the color changes depending on the number, but the problem is that it will only work once. If I write "2" and press the button, the jFrame will appear with a green panel, but then if I write another odd number and press it again, the frame will stay green.

How could I solve this so that the background color changes whenever I press the button? I should also say that I made an "if-else", so that you could only open the second jFrame once because I didn't know how to make it close and then open again, so maybe that has to do with the problem. Thanks!

This is the code in the Panel. To make it easier, I tried to just turn it green if a zero was introduced, and now it doesn't even work:

jPanel1 = new javax.swing.JPanel();
if ("0".equals(Taller2.opcion)) {
jPanel1.setBackground(new java.awt.Color(0, 255, 0));
}
else {
jPanel1.setBackground(new java.awt.Color(0, 0, 0));
}
jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 255, 255)));

// Code of sub-components - not shown here

// Layout setup code - not shown here

// Code adding the component to the parent container - not shown here

Here is the pretty basic main class:

public class Taller2 {

/**
 * @param args the command line arguments
 */
public static String opcion;
public static boolean panelabierto;
public static void main(String[] args) {
    Pregunta a = new Pregunta();
    a.setVisible(true);
    opcion = null;
    panelabierto = false;
    }
}

The second jFrame (the one with the jPanel inside) only has the basic code generated by Netbeans on the designer. If you need the code for the jFrame with the text field, I could add it too, although I believe the problem lies within the jPanel.

  • [The Use of Multiple JFrames, Good/Bad Practice?](http://stackoverflow.com/q/9554636/418556), [How to Use Buttons, Check Boxes, and Radio Buttons](http://docs.oracle.com/javase/tutorial/uiswing/components/button.html), [How to Write an Action Listeners](http://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html), [How to Use Text Fields](http://docs.oracle.com/javase/tutorial/uiswing/components/textfield.html) – MadProgrammer May 27 '15 at 07:50
  • 2
    By coding, what have you tried? Show your code. – Dhanuka May 27 '15 at 07:50
  • You can change the background color of most components by using `setBackground` and passing a `java.awt.Color` – MadProgrammer May 27 '15 at 07:50
  • @MadProgrammer Thank you, for these resource links. They are very helpful. – Dhanuka May 27 '15 at 07:57
  • Don't create a new `JPanel` each time, use the old one – MadProgrammer May 27 '15 at 08:14
  • @MadProgrammer How? Should I delete the `jPanel1 = new javax.swing.jPanel();` line? Sorry, but I said I'm pretty new to Java. – MightyGreenPanda May 27 '15 at 08:17
  • 1
    For better help sooner, post an [MCVE](http://stackoverflow.com/help/mcve) (Minimal Complete Verifiable Example) or [SSCCE](http://www.sscce.org/) (Short, Self Contained, Correct Example). – Andrew Thompson May 27 '15 at 08:47

2 Answers2

1

Don't create more instances of JPanel, simply create one and change it's state.

EventOdd

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.NumberFormat;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
            JFormattedTextField field = new JFormattedTextField(NumberFormat.getInstance());
            field.setColumns(4);

            setLayout(new GridBagLayout());

            add(field);

            field.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    long value = (Long)field.getValue();
                    if ((value % 2) == 0) {
                        setBackground(Color.GREEN);
                    } else {
                        setBackground(Color.RED);
                    }
                }
            });

            setBackground(Color.BLACK);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

    }

}
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • I think it would be better if you saw the actual code. As I said, I used the designer, so I don't really know where would the problem be on it. [Here's a zip with the code](https://www.dropbox.com/s/9q6chfboughscbz/Taller2.zip?dl=0). – MightyGreenPanda May 27 '15 at 08:28
0

Are you sure your code is correct? My best guess (without you providing your code) is that your code for checking whether the number is odd or even does not work correctly.

The best way to determine whether a number is odd or even in Java is to use the modulus (%) operator:

if ((num%2)==0) {
// Number is even
} else {
// Number is odd
}

(Replace "num" with the number you want to test.)

Dog Lover
  • 618
  • 1
  • 6
  • 18
  • Yes, I've checked that a couple times, and I believe it's correct. I've previously done a few apps to check if a number is even or odd and they all worked correctly, so I don't think that's the issue. – MightyGreenPanda May 27 '15 at 07:55
  • @MightyGreenPanda You should probably add your code to the question then. – Dog Lover May 27 '15 at 07:56
  • @MightyGreenPanda Consider providing a [runnable example](https://stackoverflow.com/help/mcve) which demonstrates your problem. This is not a code dump, but an example of what you are doing which highlights the problem you are having. This will result in less confusion and better responses – MadProgrammer May 27 '15 at 07:56