繁体   English   中英

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

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

当我运行该程序时,我看到的只是一个空白的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();
    }
}

你必须这样做

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

     });

您正在向您的JFrame添加一个普通的JPanel ,其中不包含您的自定义绘制逻辑。 去掉

JPanel panel = new JPanel();

并添加

frame.add(this);

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

暂无
暂无

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

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