简体   繁体   English

我为什么不能在我的JPanel上绘画?

[英]Why can't I paint to my JPanel?

When I run this program all I see is a blank JFrame. 当我运行该程序时,我看到的只是一个空白的JFrame。 I have no idea why the paintComponent method isn't working. 我不知道为什么paintComponent方法不起作用。 Here's my code: 这是我的代码:

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();
    }
}

You have to do this 你必须这样做

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);
    }

But i would refactor your class and separate responsabilities.. 但是我会重构您的班级并单独负责。

go() shouldn't be declared in this class 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);
    }

}

And in another class 在另一堂课

// 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);
}

Or if you only gonna use this panel in one site you can take approach of anonymous classes 或者,如果您只想在一个站点中使用此面板,则可以采用匿名课程的方法

     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);
        }

     });

You're adding a plain JPanel to your JFrame which does not contain your custom paint logic. 您正在向您的JFrame添加一个普通的JPanel ,其中不包含您的自定义绘制逻辑。 Remove 去掉

JPanel panel = new JPanel();

and add 并添加

frame.add(this);

but better to maintain 2 classes: a main class and a custom JPanel with paint logic for separation of concerns . 但最好保留2个类:一个主类和一个具有绘制逻辑的自定义JPanel ,用于分离关注点

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM