开发者

Java Refreshing a screen

I have a screen in which one of its comp开发者_StackOverflowonents is made invisible depending on a boolean value. If the boolean changes after the screen has been created, how do I refresh the screen to take this into account?


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

From the JavaDoc:

Supports deferred automatic layout.

Calls invalidate and then adds this component's validateRoot to a list of components that need to be validated. Validation will occur after all currently pending events have been dispatched. In other words after this method is called, the first validateRoot (if any) found when walking up the containment hierarchy of this component will be validated. By default, JRootPane, JScrollPane, and JTextField return true from isValidateRoot.

This method will automatically be called on this component when a property value changes such that size, location, or internal layout of this component has been affected. This automatic updating differs from the AWT because programs generally no longer need to invoke validate to get the contents of the GUI to update.


Call the validate() method on the container that needs to be laid out -- probably your window's content pane.


Try calling repaint() which in turn will call paintComponent().


I thought that (with Java 6?) you need not do anything... This should happen automatically - no?

With the following example, it does happen 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 like GridBagLayout would also solve the problem of "Re-Laying out" the page.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜