簡體   English   中英

對於Jpanel和Jframe,重繪方法有何不同?

[英]How repaint method differs for a Jpanel and Jframe?

我有以下代碼可為從左上角到右下角的球設置動畫。

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
class MainFrame{ 
    int i=0,j=0;
    JFrame frame = new JFrame();
    public void go(){   
         Animation anim = new Animation();
         anim.setBackground(Color.red);//Why color is not changing to red for the panel.
         frame.getContentPane().add(anim);
         frame.setVisible(true);
         frame.setSize(475,475);
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         for(i=0,j=0;i<frame.getHeight()&&j<frame.getWidth();++i,++j){
               anim.repaint();//Main problem is here,described below.
               try{
                   Thread.sleep(50);
               }
               catch(Exception ex){}
         }
    }
    public static void main(String[] args) {
         MainFrame mf = new MainFrame();
         mf.go();
    }

    class Animation extends JPanel{
         public void paintComponent(Graphics g){
             Graphics2D g2d = (Graphics2D)g;
             g.fillOval(i,j,25,25);
         }
    }
}

問題

  1. 當我做anim.repaint()方法中go ,我不把球從左上角到動畫右下角,但它被塗下來path.But如果我更換frame.repaint()我得到的預期的結果是移動的球。那么這兩次repaint調用之間有什么區別?
  2. 為什么anim.setBackground(Color.red);之后面板的顏色沒有改變anim.setBackground(Color.red); go方法?
  3. 如果運行此程序,您會發現球不完全在底部邊緣,那么我該如何做到?

); //為什么面板的顏色沒有變為紅色

覆蓋paintComponent(...)方法時,應始終調用super.paintComponent(g) 默認代碼負責繪制背景。

但它被塗抹在小路

與上述相同的答案。 您需要繪制背景,以便刪除所有舊畫。

球不完全在底部邊緣

如果您的意思是球不在面板上的對角線上,那是因為您手動設置了框架的大小,而沒有考慮標題欄和邊框的大小。 如果要使面板為(475,475),則重寫面板的getPreferredSize()方法以返回該尺寸。 然后在代碼中,將frame.setSize()替換為frame.pack()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM