簡體   English   中英

使用repaint()進行奇怪的重新定位;

[英]Strange repositioning using repaint();

我在JPanel中有一個JSlider,可以為我返回RGB的值。 我在JPanel的構造函數中創建它。 我在同一面板(使用paintComponent)中畫了一個小圓圈,然后使用Slider改變了它的顏色。 我希望在滑塊移動的同時改變顏色。 因此,我使用方法repaint。在Panel旁邊還有另一個Panel,帶有兩個按鈕。如果我在第一個panel中使用方法repaint,則第二個面板的按鈕在First Panel的topLeft中重復。 為什么? 謝謝。

第一小組:

public class OptionsPanel extends JPanel {


static JSlider RBG = new JSlider(0,255);
OptionsPanel(){

this.setVisible(false);
this.setSize(350,1000);
this.setLayout(null);
this.setBackground(new Color(200,200,0));
Main.f1.add(this); 



 RBG.setVisible(true);
 RBG.setSize(255,50);
 RBG.setLocation(30,240);


 this.add(RBG);



LotL lotl = new LotL();
Button save = new Button("Save");

save.setVisible(true);
save.setSize(100,40);
save.setLayout(null);
save.setLocation(60,300);
save.addActionListener(lotl); 
save.setBackground(Color.yellow);
save.identificatore=3;
this.add(save);







  }


  boolean draw=false;

  @Override
 public void paintComponent(Graphics g){



 g.drawOval(50,100,70,70);

 g.setColor(new Color(RBG.getValue(),180,200));
 g.fillOval(50,100,70,70);


 repaint();




}
}

第二小組:

public class FirstPanel extends JPanel{
FirstPanel(){

this.setVisible(true);
this.setSize(1000,1000);
this.setLayout(null);
this.setBackground(new Color(255,200,180)); 
Main.f1.add(this);

Button start = new Button("Start Game!");


Button options = new Button("Options");
LotL LotL = new LotL();  



start.setVisible(true);
start.setSize(200,80);
start.setLayout(null);
start.setLocation(400,450);
start.addActionListener(LotL); 
start.setBackground(Color.green);
start.identificatore=1;
this.add(start);

options.setVisible(true);
options.setSize(200,70);
options.setLayout(null);
options.setLocation(400,550);
options.addActionListener(LotL); 
options.setBackground(Color.green);
options.identificatore=2;
this.add(options);

}


}

你打破了油漆鏈...

@Override
public void paintComponent(Graphics g){

    g.drawOval(50,100,70,70);

    g.setColor(new Color(RBG.getValue(),180,200));
    g.fillOval(50,100,70,70);


    repaint();

}

Graphics是一種共享資源,該資源將傳遞給在給定繪制周期內繪制的所有組件。

paintComponent的工作之一是准備要繪畫的Graphics上下文,但要填充組件的背景色。

您必須在執行任何自定義繪制之前調用super.paintComponent

@Override
protected void paintComponent(Graphics g){
    super.paintComponent(g);
    g.drawOval(50,100,70,70);

    g.setColor(new Color(RBG.getValue(),180,200));
    g.fillOval(50,100,70,70);
}

另外,永遠不需要public paintComponent ,永遠都不要直接調用它,也永遠不要從任何可能觸發重新繪制的paint方法中修改組件的狀態,您將陷入無限循環,最終消耗您的CPU並使計算機無法使用。

看看AWT中的繪畫和搖擺執行自定義繪畫以了解更多詳細信息

您還應該避免使用null布局,像素完美布局是現代ui設計中的一種幻覺。 有太多因素會影響組件的單個大小,您無法控制。 Swing旨在與布局經理為核心一起工作,舍棄這些問題不會導致問題和問題的終結,您將花費越來越多的時間來嘗試糾正

暫無
暫無

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

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