我有一個自定義JLayeredPane
和兩個自定義子JPanel
的。我在Thread
的while
循環中重繪了所有內容。我已使用RepaintManager.currentManager(backPanel).markCompletelyClean(backPanel);
來停止重新繪製backPanel
JPanel
。至於不浪費系統資源。但是,這不起作用。正如我們在paintComponent
方法中看到的那樣,如果您運行並編譯下面的代碼,您將看到在輸出中從paintComponent
方法中的System.out.println("Reccursion")
方法調用中遞歸地重複了語句「Reccursion」。爲什麼這個JPanel仍然被重新繪製?
爲什麼backPanel
JPanel
仍然被粉刷一新,爲什麼仍然被調用的方法System.out.println("Reccursion")
,當我用RepaintManager.currentManager(backPanel).markCompletelyClean(backPanel);
。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Main extends JLayeredPane {
static JFrame frame;
static Main main;
static Dimension screenSize;
public Main() {
JPanel backPanel = new BackPanel();
JPanel frontPanel = new FrontPanel();
add(backPanel, new Integer(7));
add(frontPanel, new Integer(8));
new Thread(() -> {
while (true){
repaint();
}
}).start();
RepaintManager.currentManager(backPanel).markCompletelyClean(backPanel);
}
public static void main(String[] args) {
screenSize = Toolkit.getDefaultToolkit().getScreenSize();
frame = new JFrame("Game"); // Just use the constructor
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
main = new Main();
frame.add(main, BorderLayout.CENTER);
frame.pack();
frame.setSize(screenSize);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public class BackPanel extends JPanel{
public boolean drawn = false;
public BackPanel(){
setVisible(true);
setOpaque(false);
setSize(screenSize);
JLabel test1 = new JLabel("Test1");
JLabel test2 = new JLabel("Test2");
add(test1);
add(test2);
}
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.red);
g.fillRect(0, 0, screenSize.width, 200);
System.out.print("Reccursion");
}
}
public class FrontPanel extends JPanel{
public FrontPanel(){
setVisible(true);
setOpaque(false);
setSize(screenSize);
JLabel test = new JLabel("Test");
add(test);
}
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.blue);
g.fillRect(0+screenSize.width/2, 0, screenSize.width/4, 300);
}
}
}
你的代碼已經過時,不碰的RepaintManager和線程暫停時,使用SwingTimer,更多的信息在這裏搜索,前閱讀的Java2D甲骨文教程,和風俗畫太 – mKorbel
我不知道如何RepaintManager.currentManager(backPanel).markCompletelyClean(backPanel);作品。這是很多絨毛。如果你開始一個線程,重新繪製endlesly這將會發生。你必須創建一些機制來阻止它。例如,如果您想在兩次後停止重新繪製,請在該處放置一個計數器。所以陳述你的目標。 – gpasch