试图更新我的JFrame,为什么不重绘工作?

时间:2013-02-01 02:27:30

标签: java swing user-interface jframe jlabel

我将运行该程序,但是当我激活该事件时,JFrame将不会更新(它只会移除JLabel),除非我手动拖动窗口来调整它的大小,即使在事件发生后调用repaint()也是如此地点。怎么了?

public Driver() {
    setLayout( new FlowLayout() );

    pass = new JPasswordField( 4 );
        add( pass );

    image = new ImageIcon( "closedD.png" );
    label = new JLabel( "Enter the password to enter the journal of dreams" , image , JLabel.LEFT );
        add( label );

    button = new JButton( "Enter" );
        add( button );

    event e = new event();
        button.addActionListener( e );

    setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    setVisible( true );
    setSize( 1600/2 , 900/2 );
    setTitle( "Diary" );
}

//main method
//
//
public static void main( String[] args ) {
    win = new Driver();
}

public class event implements ActionListener {
    private boolean clickAgain = false;

    public void actionPerformed( ActionEvent e ) {
        if ( passEquals( password ) && clickAgain == false ) {
            image2 = new ImageIcon( "openD.png" );
            remove( label );

            label = new JLabel( "Good Job! Here is the journal of dreams." , image2 , JLabel.LEFT );
                add( label );

                clickAgain = true;
        }

        repaint();
    }
}

1 个答案:

答案 0 :(得分:8)

每次添加或删除组件时,都必须告诉其容器重新布局它所拥有的当前组件。您可以通过调用revalidate()来执行此操作。然后,您将在重新验证调用之后调用repaint()以使容器自行重新绘制。

public void actionPerformed( ActionEvent e ) {
    if ( passEquals( password ) && clickAgain == false ) {
        image2 = new ImageIcon( "openD.png" );
        remove( label );

        label = new JLabel( "Good Job! Here is the journal of dreams.", 
             image2 , JLabel.LEFT );
            add( label );

            clickAgain = true;
    }
    revalidate(); // **** added ****
    repaint();
}

注意:您的问题措辞的方式与您认为我们知道您要做的事情一样。请在下次给我们更多信息。问题越多越好,信息越多,答案越好,信息越多。

编辑2:
我想知道你是否可以简化你的代码。而不是删除和添加JLabel,最好只是简单地设置当前JLabel的文本和图标:

public void actionPerformed( ActionEvent e ) {
    if ( passEquals( password ) && clickAgain == false ) {
        image2 = new ImageIcon( "openD.png" );
        // remove( label );  // removed

        label.setText( "Good Job! Here is the journal of dreams.");
        label.setIcon(image2);
    }
}