在小部件上绘制2D图形?请从Head First Java书中为我清楚这个例子

时间:2017-04-30 11:38:24

标签: java swing

到目前为止,这本书大多是清晰和一致的,有时候我不得不回去重读,但在这个例子中我真的被卡住了,无论我读多少,我都没有得到它。它或者是书中遗漏的东西,或者我错过了重点。所以,如果你能为我清楚这一点,那就非常困扰我了,我不想继续阅读这本书而没有做到这一点。

import java.awt.*;
import javax.swing.*;

public class MyDrawPanel extends JPanel {
    public static void main(String[] args) {
        MyDrawPanel pan = new MyDrawPanel();
        pan.go();
    }

    private static final long serialVersionUID = 2; // this was not mentioned in the book, but i had to put it to get rid of the warning the compiler gives without it (i googled it)

    public void go() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300,300);
        frame.setVisible(true);

    }
    // In the book it's mentioned that you never call this method yourself (i don't quite get it how that works...)
    public void paintComponent(Graphics g) {
        g.setColor(Color.orange);
        g.fillRect(20,50,100,100);
    }

}

上面的代码编译并运行得很好但没有任何反应。

我试图实例化一个Graphics对象并玩弄它,但显然是抽象的Graphics类..

谢谢!

编辑:我有本书的第2版,所以你可以转到第364页第12章如果你也有(我绘制JFrame的代码来自前面的例子 - 我认为paintComponent( )方法示例只是添加到上一个示例。

2 个答案:

答案 0 :(得分:3)

主要问题是您永远不会将MyDrawPanel的实例添加到您在go()方法中创建的框架,因此它仍为空。

解决此问题的一种方法是在this方法中明确添加MyDrawPanel的当前go)实例,例如

public void go() {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(300,300);
    frame.add(this);       //  <-- add this line, 
                           //  you can also use frame.setContentPane(this)
    frame.setVisible(true);
}

答案 1 :(得分:1)

您应始终致电super.paintComponent(g);

此外,您应该选择不同的设计来创建框架和面板。我个人会用这个:

public class MyGui extends JFrame {
    public MyGui() {
        DrawPanel myDrawPanel = new DrawPanel();
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.add(myDrawPanel);
        this.pack();
        this.setVisible(true);
    }
}

public class MyDrawPanel extends JPanel {
    public MyDrawPanel() {
        this.setPreferredSize(new Dimension(300, 300));
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.orange);
        g.fillRect(20,50,100,100);
    }
}

了解super.paintComponent(g)做什么的有用答案:What does super.paintComponent(g) do?

相关问题