[英]Do the paint() and repaint() methods of java applet and application behave the same way?
[英]How to repaint paint methods in java applet?
我想使用applet在2個“框架”之間切換。
我想使用小程序來繪制某些內容,然后將其刪除並繪制其他內容。 有什么辦法嗎?
例:
if(true){
public void paint1(Graphics g) {
g.setColor(Color.black);
g.fillRect( 80,400, 20, 10 );
}
}else
public void paint2(Graphics g) {
g.setColor(Color.green);
g.fillRect( 50,440, 70, 60 );
}
}
我為此所做的所有嘗試都使applet崩潰了。
我的項目:我和我的朋友正在編寫一個簡單的代碼,我們需要使用某種applet圖形。 我們提出了制作一個程序,其中兩個字符上下跳躍的想法。 問題是我們將擁有一個“ AI”,只要他感覺到它就會跳躍。 所以CardLayout無法正常工作,因為那時我們可以控制一切。
如果打算在兩個圖形之間“切換”,我建議使用CardLayout 。
但是,如果要根據條件進行繪制以繼續使用當前的功能,則可以執行以下操作:
class DrawingSpace extends JPanel{
private BufferedImage display;
//Other variables, initializations, constructors not shown
private void init(){
display = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
}
public void draw(){
if(whatever){ //if whatever == true
Graphics2D g2 = display.createGraphics();
g2.setColor(Color.BLACK);
g2.fillRect( 80, 400, 20, 10 );
repaint();
}else{
Graphics2D g2 = display.createGraphics();
g2.setColor(Color.GREEN);
g2.fillRect( 50, 440, 70, 60 );
repaint();
}
}
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(display, 0, 0, width, height, null);
}
}
那么第一個問題是:您什么時候要切換? 按一下按鈕? 幾毫秒后?
使用一個按鈕,它非常簡單:您只需要繪制2個面板並默認顯示第一個面板即可。 單擊按鈕后,可以使用repaint()和revalidate()方法刷新JFrame。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.