javacheckboxalways-on-top

Always on top with Checkbox on Java


Hello all I am trying to make a new software that it gives me modulo of any number I gave. What I want is I put a JCheckBox on my gui and when it's checked the window should be

setAlwaysOnTop(true); 

and when deselected

setAlwaysOnTop(false);

Some of my code is

boolean top = false;

    Check = new JCheckBox("Always on top");
    Check.setLocation(140, 105);
    Check.setSize(150, 20);
    Check.setSelected(top);
    Check.addItemListener(new CheckBoxListener());

    add(Check);
    setAlwaysOnTop(top);

    private class CheckBoxListener implements ItemListener{
        public void itemStateChanged(ItemEvent e){
            if(e.getSource()==Check){ 
                if(Check.isSelected()){
                    top = true;
                }else{
                    top = false;
                }
            }
        }
    }

Solution

  • setAlwaysOnTop does not observe further state changes to your boolean top. It takes the value of top when it is passed.

    In your listener, write:

    if(e.getSource() == Check) {
      setAlwaysOnTop(Check.isSelected());
    }