Search code examples
javanetbeansidejframejcheckbox

Java - setVisible only works after clicking on screen


I have a jframe with a jcheckbox and a jtextfield (it has many more components).

I set the label to setVisible(false) and when the checkbox is checked, it should turn the label visible. It actually does, but you just can´t see it until you click anywhere else on the frame.

Here is some of the code:

jTextField17 = new javax.swing.JTextField();
jTextField17.setText("Quantas?");
jTextField17.setVisible(false);
jTextField17.setMinimumSize(new java.awt.Dimension(52, 20));


jCheckBox1 = new javax.swing.JCheckBox();
jCheckBox1.setBackground(new java.awt.Color(153, 255, 153));
jCheckBox1.setText("Cabecinhas");
jCheckBox1.addActionListener(new java.awt.event.ActionListener() {
   public void actionPerformed(java.awt.event.ActionEvent evt) {
    jCheckBox1ActionPerformed(evt);
   }
});


private void jCheckBox1ActionPerformed(java.awt.event.ActionEvent evt) {                                           
    if (jCheckBox1.isSelected()){
        jTextField17.setVisible(true);
    }else{
        jTextField17.setVisible(false);
    }
}                                       

I don´t think there´s anything wrong with the code.

To sum up:

user clicks checkbox. checkbox gets marked, nothing else seems to happen. user clicks anywhere on screen (after checking checkbox) and the textfield appears.

I´m using netbeans GUI editor. I would like to show the whole code, but it´s 3000+ lines. If you need to see more, ask me what part you need and I´ll edit here. Thanks for reading this and thank you even more for trying to help.


Solution

  • Try using this.repaint(); and this.revalidate();

    private void jCheckBox1ActionPerformed(java.awt.event.ActionEvent evt) {                                           
        if (jCheckBox1.isSelected()){
            jTextField17.setVisible(true);
            this.repaint();
            this.revalidate();
    
        }else{
            jTextField17.setVisible(false);
        }
    }