我有一個類(不是公開的,所以你可能不知道這個類)正在用picture.draw(g2)繪制圖片。使用 picture.changeToDry() 我可以更改圖片。當我呼叫圖片并在實作的 paintComponent() 方法中更改它時,它作業正常。但是當我呼叫 changeToDry() 并在它 repaint() 之后,它不起作用。它只顯示默認圖片,但不更新它。我該怎么做,才能更改圖片并以另一種方法更新 JPanel?它必須與 repaint() 相關,因為這些方法在 paintComponent() 中有效,但在其他地方無效。
編輯: update() 將在另一個類中呼叫。另外,正如我在評論中提到的,我不能提供更多關于這門課的資訊,因為它是一門私人的、僅限教學的課程。顯然它應該作業。否則我的老師不會給我們的。編輯 2:我有另一個正在繪制框架的類 ClimateFrame。我在那里打電話 update()
public class ClimatePanel extends JPanel {
ClimatePicture picture = new ClimatePicture(100, 100);
public void update() {
picture.changeToDry();
repaint(); // does not work
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
// picture.changeToDry() would work here
picture.draw(g2);
}
}
public class ClimateFrame extends JFrame {
public ClimateFrame() {
setTitle("A task");
setLayout(new BorderLayout());
add(new ClimatePanel(), BorderLayout.CENTER);
}
public static void main(String [] args) {
ClimateFrame frame = new ClimateFrame ();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 600);
frame.setVisible(true);
ClimatePanel climatePanel = new ClimatePanel();
climatePanel.update();
}
}
uj5u.com熱心網友回復:
有你的問題:
public class ClimateFrame extends JFrame {
public ClimateFrame() {
setTitle("A task");
setLayout(new BorderLayout());
add(new ClimatePanel(), BorderLayout.CENTER);
}
public static void main(String [] args) {
ClimateFrame frame = new ClimateFrame ();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 600);
frame.setVisible(true);
ClimatePanel climatePanel = new ClimatePanel(); // ****** here ****
climatePanel.update();
}
}
您正在指示的行創建一個新的 ClimatePanel 實體并更改其狀態,而不是最初創建和顯示的單獨的狀態。這與我在上面評論中的一個猜測一致:
現在我們可以猜測:
- 可能是 Swing 執行緒問題,
- 或者您可能正在更新錯誤的實體(這個)
解決方案:不要創建一個新的 ClimatePanel 實體,而是創建一個 ClimatePanel 欄位,給它一個單一的 ClimatePanel 參考,將它添加到 GUI,然后更新它的狀態,現在是顯示實體的狀態。
例如,
public class ClimateFrame extends JFrame {
private ClimatePanel climatePanel = new ClimatePanel(); // ADD
public ClimateFrame() {
setTitle("A task");
setLayout(new BorderLayout());
// add(new ClimatePanel(), BorderLayout.CENTER); // REMOVE
add(climatePanel, BorderLayout.CENTER); // ADD
}
// allow visibility of the climate panel method
public void updateClimatePanel() {
climatePanel.update();
}
public static void main(String [] args) {
ClimateFrame frame = new ClimateFrame ();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 600);
frame.setVisible(true);
// ClimatePanel climatePanel = new ClimatePanel(); // REMOVE
frame.updateClimatePanel();
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/475922.html
上一篇:JavaSwing等待
下一篇:JFrame在某個時間結束
