Update jPanel background color when a button is pressed

孤街浪徒 提交于 2020-01-07 08:32:37

问题


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.


回答1:


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

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);
        }

    }

}



回答2:


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



来源:https://stackoverflow.com/questions/30476211/update-jpanel-background-color-when-a-button-is-pressed

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