JFrame 刷新問題


先看下面的一段代碼:

import java.awt.Container;
import java.net.URL;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;


public class Icon extends JFrame {
    private ImageIcon icon;
    private JLabel label1;
    private JPanel panel;
    public Icon()
    {
        Container container=getContentPane();
        setSize(1000,1000);
        setVisible(true);
        icon=createImageIcon("image/yanzi.png","燕姿");
        //label1=new JLabel( "icon display",icon,JLabel.CENTER);
        label1=new JLabel(icon);
        label1.setBounds(0, 0,300,500);
        this.add(label1);
        
        setLayout(null);
        setTitle("icon");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
    }
    protected  ImageIcon createImageIcon(String path, String description) {
        // TODO Auto-generated method stub
        URL imgURL=getClass().getResource(path);
    
        
        if(imgURL!=null)
            return new ImageIcon(imgURL,description);
        else
            System.out.println("couldn't find file "+path);
        return null;
    }
    public static void main(String[] args)
    {
        Icon icon=new Icon();
    }    
    
}
運行后顯示的是一個空白的JFrame,只有當改變jframe大小時,圖片才顯示,因為構造函數里setVisible(true)是出現在添加組件的前面,jframe顯示時是沒有label的,改變大小時就會刷新jframe顯示圖片。可以改成如下:
  先添加組件在顯示。setVisible(true);放在添加組件后。
或者在添加組件后立即重繪,repaint();
還可以 重新布局

setVisible(true);
添加組件
invalidate();

   validate();

Class Container 方法

validate 
public   void   validate() 驗證此容器及其所有子組件。   
使用   validate   方法會使容器再次布置其子組件。已經布置容器后,在修改此容器的子組件的時候(在容器中添加或移除組件,或者更改與布局相關的信息),應該調用上述方法。 




當畫出JFrame的以后,有時候需要響應某些監聽事件,向JFrame里添加組件。這時候如果不做任何處理的話,JFrame是不會刷新的(除非窗口最小化,大小改變),所以需要我們強制刷新,用的方法是updateUI(),下面是一個實驗程序,響應單選框選中,加入一個JButton,注意這里我使用的是JFrame,如果換成Frame的話,則無效果
public class Text extends JFrame{
JCheckBox a = new JCheckBox("1");
JFrame f = new JFrame("text");
JPanel p= new JPanel(new GridLayout(4,1));

public void lantchFrame(){
   f.addWindowListener(new WindowAdapter(){
    public void windowClosing(WindowEvent e){
     System.exit(0);
    }
   });
   p.add(a);
   f.add(p);
   a.addActionListener(new MyListener());
   f.pack();
   f.setSize(320,240);
   f.setVisible(true);
}
class MyListener implements ActionListener {
   public void actionPerformed(ActionEvent e) {
    if(a.isSelected()){
     JButton jb3 = new JButton("jb3");
     p.add(jb3);
    p.updateUI();
    }
   }
}
public static void main(String [] args){
   new Text().lantchFrame();
}
}
JPanel updateUI() 
          Resets the UI property with a value from the current look and feel.

 

 
       


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM