【问题标题】:Why can't I paint to my JPanel?为什么我不能在我的 JPanel 上绘画?
【发布时间】:2013-07-12 15:49:22
【问题描述】:

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

【问题讨论】:

  • go()中使用this而不是panel
  • 另外,为什么不将 JFrame 和 JPanel 放在两个不同的类中?
  • 只是一个建议,而不是在JFrame 上设置大小,最好覆盖getPreferredSize(),就像你覆盖paintComponent() 方法并调用frame.pack() 一样

标签: java eclipse swing drawing awt


【解决方案1】:

你必须这样做

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

     });

【讨论】:

  • 成功了!!谢谢!但是在这种情况下,“this”到底指的是什么?它是指我之前制作的新对象的 JPanel 吗?我的班级结构有什么问题?抱歉,在以良好的 OO 方式设计程序时,我是个菜鸟。
  • @BillyJean 我编辑我的答案,希望对您有所帮助.. this 指的是 this class 的实例,在您的情况下是您创建的类
【解决方案2】:

您正在向您的JFrame 添加一个普通的JPanel,它不包含您的自定义绘制逻辑。删除

JPanel panel = new JPanel();

并添加

frame.add(this);

但最好维护 2 个类:一个主类和一个自定义 JPanel,带有 separation of concerns 的绘制逻辑。

【讨论】:

  • 两个建议都奏效了!非常感谢!!但我到底做错了什么? Vanilla 是否意味着它是原始的 JPanel?
  • 您正在添加一个不同的组件,该组件没有实现您的自定义绘制逻辑(如上)。顺便说一句:vanilla 表示plain,在这种情况下,没有实现自定义绘画。
猜你喜欢
  • 1970-01-01
  • 2015-07-04
  • 1970-01-01
  • 2013-07-21
  • 2019-09-15
  • 2017-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多