Phi*_*ess 1 java user-interface
我从书中输入了这段代码
public class SimpleGui3C {
JFrame frame;
public static void main (String[] args) {
SimpleGui3C gui = new SimpleGui3C();
gui.go();
}
public void go() {
frame = new JFrame("My own code");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MyDrawPanel drawPanel = new MyDrawPanel();
frame.getContentPane().add(BorderLayout.CENTER, drawPanel);
frame.setSize(420,300);
frame.setVisible(true);
}}
class MyDrawPanel extends JPanel {
public void painComponent(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);
}}
Run Code Online (Sandbox Code Playgroud)
这是本书的原始代码,我从本书的网站上下载了这段代码
public class SimpleGui3C {
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);
MyDrawPanel drawPanel = new MyDrawPanel();
frame.getContentPane().add(BorderLayout.CENTER, drawPanel);
frame.setSize(420,300);
frame.setVisible(true);
}}
class MyDrawPanel extends JPanel {
public void paintComponent(Graphics g) {
g.fillRect(0,0,this.getWidth(), this.getHeight());
// make random colors to fill with
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);
}}
Run Code Online (Sandbox Code Playgroud)
我一次又一次地检查它以确保它们是相同的,似乎它们是相同的.但为什么GUI不同?
请帮助,提前谢谢.
在您自己的代码中,方法名称painComponent应该是它应该的时间paintComponent.
提示:添加@Override到重写方法,然后编译器将告诉您有关这样的错误:
@Override
public void painComponent(Graphics g) {
Run Code Online (Sandbox Code Playgroud)