[英]JFrame frame calls JPanel paintComponent
我實際上正在學習Java語言中的圖形。 我不明白這個JFrame
對象如何在MyDrawpanel
調用paintComponent
方法,該方法擴展了JPanel
。
frame.repaint()
再次調用paintComponent
但是如何? 為什么我不能用drawPanel
的對象MyDrawPanel
像drawPanel.repaint()
;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SimpleGui3C implements ActionListener
{
JFrame frame;
public static void main(String[] args)
{
SimpleGui3C gui = new SimpleGui3C();
gui.go();
}
public void go()
{
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Change Colors");
button.addActionListener(this);
MyDrawPanel drawPanel = new MyDrawPanel();
frame.getContentPane().add(BorderLayout.SOUTH, button);
frame.getContentPane().add(BorderLayout.CENTER, drawPanel);
frame.setSize(300,300);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent event)
{
frame.repaint();
}
}
class MyDrawPanel extends JPanel
{
public void paintComponent(Graphics g)
{
g.fillRect(0,0,this.getWidth(), this.getHeight());
int red = (int)(Math.random() * 255);
int green = (int)(Math.random() * 255);
int blue = (int)(Math.random() * 255);
Color randomColor = new Color(red,green,blue);
g.setColor(randomColor);
g.fillOval(70,70,100,100);
}
}
為什么我不能使用MyDrawPanel的drawPanel對象,如drawPanel.repaint();?
當前,您的frame
變量被定義為instance
變量,因此可以在該類的任何方法中進行引用。
但是,您的drawPanel
變量定義為local
變量,因此只能在定義它的方法中引用它。
更改drawPanel
變量,使其定義為instance
變量,而不是local
變量。 然后,您可以在actionPerformed(...)
方法中使用drawPanel.repaint()
。
在面板上調用repaint()會更有效,因為將僅重新繪畫面板,而不是框架和按鈕。
另外,您正在使用add(...)方法的舊版本。
frame.getContentPane().add(BorderLayout.SOUTH, button);
您應該使用:
frame.getContentPane().add(button, BorderLayout.SOUTH);
現在框架將把add(...)請求轉發到內容窗格,因此您實際上可以使用:
frame.add(button, BorderLayout.SOUTH);
節省一些打字時間。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.