[英]Java paint() Only Called Once From paintAll()
我有以下代碼被調用:
while(true){
view.onTick();
trySleep(55);
}
onTick()方法的描述如下:
public void onTick() {
mainFrame.paintAll(mainFrame.getGraphics());
}
這是我設置JFrame和JPanels等的地方(mainFrame是JFrame):
private void runProgramSetup(){
JPanel canvas = new JPanel();
canvas.setLayout(new BoxLayout(canvas, BoxLayout.Y_AXIS));
mainFrame.getContentPane().add(canvas);
//create the main game panel
mapPanel = new MapPanel(model, this);
mapPanel.setPreferredSize(new Dimension(TOTAL_FRAME_WIDTH, MAP_PANEL_HEIGHT));
mapPanel.setBackground(Color.cyan);
//create the menu panel
menuPanel = new MenuPanel(model, this);
menuPanel.setLayout(new BoxLayout(menuPanel, 0));
menuPanel.setPreferredSize(new Dimension(TOTAL_FRAME_WIDTH, MENUS_PANEL_HEIGHT));
//add the panels to the window
canvas.add(mapPanel);
canvas.add(menuPanel);
//make both panels visible
mapPanel.setVisible(true);
menuPanel.setVisible(true);
}
現在這是我的問題。 當repaintAll()稱為mapPanel的覆蓋paint(Graphics g)方法時,所有東西都會重新繪制:
@Override
public void paint(Graphics g) {
transformedImages.transformAndStoreImages(model);
paintGrid(g);
paintScenery(g);
paintElements(g);
paintDraggedElement(g);
paintUIOverlay(g);
}
它僅被調用一次。 這就對了。 但是,所有其他組件繼續重繪。 僅mapPanel繪制一次。 這是更奇怪的地方。 我在Ubuntu上運行並遇到此問題。 我團隊的其余成員都在Mac上運行,他們沒有這個問題。 我能夠解決此問題的唯一方法是用兩個繪畫調用替換onTick():
public void onTick() {
mainFrame.repaint();
mainFrame.paintAll(mainFrame.getGraphics());
}
這就是為我工作的全部。 我需要兩個電話。 兩者都不行。 我顯然不喜歡這樣做,因為效率低下..:/有什么想法嗎?
謝謝!
你應該重寫JPanel的
paintComponent(Graphics g)
不上漆
mainFrame.repaint()
強制刷新地圖的原因是因為repaint()
調用repaint(0, 0, 0, width, height)
,這將整個mainFrame
的區域標記為RepaintManager
標記為“臟”。 這是有意設計的,因為您通常不希望為更新組件而重新繪制JFrame中的每個像素。 因此,在onTick()
,當調用mainFrame.paintAll()
時,我的猜測是mapPanel
的區域尚未標記為臟,因此RepaintManager
跳過了該區域,以節省處理時間。 如果您確定每次調用onTick()
都希望重新繪制整個mapPanel,則最簡單的方法是在onTick()
方法內部調用mapPanel.repaint()
。 這會將整個mapPanel
標記為臟,因此將盡快重繪。 另外,如果您的menuPanel
僅使用常規的swing JComponents,則無需手動使它們重新繪制,如果正確使用API,則它們的值更改時將重新繪制它們。
我知道這是一個古老的問題,但是我想我會回答,以防其他人遇到類似問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.