1

当我运行这个程序时,我看到的只是一个空白的 JFrame。我不知道为什么paintComponent 方法不起作用。这是我的代码:

package com.drawing;

import java.awt.Color;
import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class MyPaint extends JPanel {

    private void go() {
        JFrame frame = new JFrame();
        JPanel panel = new JPanel();
        frame.setSize(400, 400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.add(panel);
        frame.setVisible(true);
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.YELLOW);
        g.fillRect(50, 50, 100, 100);
    }

    public static void main(String[] args) {
        My paintTester = new MyPaint();
        paintTester.go();
    }
}
4

2 回答 2

4

你必须这样做

private void go() {
        JFrame frame = new JFrame();
        frame.setSize(400, 400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.add(this);
        frame.pack();
        frame.setVisible(true);
    }

但我会重构你的班级和单独的责任..

go()不应在此类中声明

public class MyPaint extends JPanel {

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

}

在另一个班级

// In another class 
public static void main(String[] args) {
    JPanel paintTester = new MyPaint();
    JFrame frame = new JFrame();
    frame.setSize(400, 400);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocationRelativeTo(null);
    frame.add(paintTester);
    frame.pack();
    frame.setVisible(true);
}

或者,如果您只在一个站点中使用此面板,您可以采用匿名课程的方法

     JFrame frame = new JFrame();
     frame.add(new JPanel(){
        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.setColor(Color.YELLOW);
            g.fillRect(50, 50, 100, 100);
        }

     });
于 2013-07-14T19:57:17.677 回答
2

您正在向您添加一个不包含您的自定义绘制逻辑的纯JPanel文本JFrame。消除

JPanel panel = new JPanel();

并添加

frame.add(this);

但最好维护 2 个类:一个主类和一个JPanel带有绘制逻辑的自定义类,用于关注点分离

于 2013-07-14T19:52:22.253 回答