Java Screen Refresh

I have a screen in which one of its components becomes invisible depending on a boolean value. If there are logical changes after screen creation, how do I update the screen to take this into account?

+2


a source to share


4 answers


I think revalidate () is more appropriate here if you are dealing with JComponents.

From JavaDoc:



Supports deferred auto-layout.

Raises invalidation and then adds this validateRoot component to the list of components to be validated. The check will be performed after all pending events have been sent. In other words, after calling this method, the first validateRoot (if any) will be checked when traversing this component's containment hierarchy. By default, JRootPane, JScrollPane and JTextField return true from isValidateRoot.

This method will be automatically called on this component when the property value is changed in such a way that the size, location, or internal layout of this component is affected. This automatic update differs from AWT because programs generally no longer need to invoke a check to update the GUI content.

+3


a source


Call a method validate()

on the container that needs to be laid out - probably your window content pane.



+1


a source


Try to call repaint()

, which in turn will call paintComponent()

.

+1


a source


I thought that (since Java 6?) You don't have to do anything ... This should happen automatically - no?

In the following example, this happens automatically ...

public class TT extends JFrame
{
    public TT()
    {
        setLayout(new FlowLayout());
        JLabel label = new JLabel();
        label.setText("Label:");
        add(label);

        final JTextField textField = new JTextField();
        add(textField);

        JButton button = new JButton();
        button.setText("Button");
        button.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent event)
            {
                if (textField.isVisible())
                {
                    textField.setVisible(false);
                }
                else
                {
                    textField.setVisible(true);
                }
            }
        });
        add(button);
    setSize(100,100);
    }

    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                TT frame = new TT();
                frame.setDefaultCloseOperation(TT.EXIT_ON_CLOSE);
                frame.setVisible(true);
            }
        });
    }
}

      

[Add] And using a layout manager such as GridBagLayout

will also fix the "Reinstall" page issue.

+1


a source







All Articles