[英]Trying to update my JFrame, why won't repaint work?
我將運行程序,但是當我激活事件時,除非我手動拖動窗口以調整其大小,否則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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.