gpt4 book ai didi

java - 尝试更新我的 JFrame,为什么重绘不起作用?

转载 作者:行者123 更新时间:2023-11-29 10:17:08 24 4
gpt4 key购买 nike

我将运行该程序,但是当我激活事件时,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();
}
}

最佳答案

任何时候你添加或删除一个组件,你必须告诉它的容器重新布局它持有的当前组件。您可以通过对其调用 revalidate() 来完成此操作。然后,您可以在 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);
}
}

关于java - 尝试更新我的 JFrame,为什么重绘不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14638767/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com