首页 > 解决方案 > 为什么 Repaint() 和 add() 方法不起作用?

问题描述

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

public class Main {

public Main(){
    JPanel panel = new JPanel();
    panel.setSize(500,600);
}

public void paint(Graphics g){
    g.setColor(Color.BLACK);
    g.fillRect(0,0,500,600);

    g.setColor(Color.RED);
    g.fillOval(20,30,50,50);

    repaint();

}

public static void main(String[] args) {

    JFrame frame = new JFrame("Practice");
    Main ball = new Main();
    frame.add(ball);
    frame.pack();
    frame.setResizable(false);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(500,600);
    frame.setVisible(true);

 }
}

在这我得到两个错误,我在 youtube 上学习了这段代码。

视频 1 视频 2

我不知道为什么我不能写出问题中的错误。这就是我在评论部分写的原因。

标签: javaswingjframejpanel

解决方案


首先,停下来。把视频放一边。喝杯热咖啡,阅读在 AWT 和 Swing中执行自定义绘画和绘画,以更好地了解绘画系统的核心方面如何在 Swing 中工作。

Swing 提供了许多“钩子”,您可以在其中执行自定义绘画,主要paintComponentJComponent.

为了利用这一点,您首先需要一个从其JComponent子级或其子级扩展的类(通常JPanel

public class TestPane extends JPanel {

    public TestPane() {
        setBackground(Color.BLACK);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        // The background is painted for us, so we don't need to
        // You shouldn't be relying on "magic" numbers anyway
        //g.setColor(Color.BLACK);
        //g.fillRect(0,0,500,600);

        g.setColor(Color.RED);
        g.fillOval(20,30,50,50);      
        // Never, ever, call repaint in here
        // bad things happen, fairies lose wings
        // black holes suck small children to oblivion
        // Fire Fly gets cancelled  
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(500, 600);
    }
}

现在你有一个自定义组件,你只需要它可以显示的东西

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            JFrame frame = new JFrame("Practice");
            TestPane ball = new TestPane();
            frame.add(ball);
            frame.pack();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
        }
    });

}

推荐阅读