【问题标题】:Something strange happening with JPanel and java g.fillOval() methodJPanel 和 java g.fillOval() 方法发生了一些奇怪的事情
【发布时间】:2012-08-16 13:16:08
【问题描述】:

我正在使用 Graphics 在 JPanel 上绘制椭圆。最低的椭圆形正在发生一些事情,它不是保持一种颜色,而是在椭圆形上呈条纹状的多种颜色。其他椭圆不会发生这种情况。

我的 JFrame 大小是 600 x 600。 这是我的代码:

package virus;

import javax.swing.JPanel;
import java.awt.Graphics;
import java.awt.Color;
import java.awt.event.MouseListener;
import java.util.Random;

public class VirusGamePanel extends JPanel {
    private static final long serialVersionUID = 1L;
    Random colour = new Random();
    int score = 0;

    public void paint(Graphics g)
    {
        super.paint(g);
        g.setColor(Color.magenta);
        g.drawString("Score: "+ score,200,200);
        g.setColor(Color.orange);
        g.drawOval(200,150,200,200);
        Color rand = new Color(colour.nextInt(255),colour.nextInt(255),colour.nextInt(255));
        g.setColor(rand);
        g.fillOval(270,50,50,50);
        g.fillOval(100,100,50,50);
        g.fillOval(450,100,50,50);//this line is causing the problem
        g.fillOval(100,400,50,50);
    }
}

【问题讨论】:

  • 永远不要覆盖paint(...),对于这样一个小东西的JPanel/JComponent。总是为这个东西覆盖paintComponent(...) :-)

标签: java graphics colors jpanel


【解决方案1】:

我编写了一个小测试程序,它在 JFrame 中绘制您的面板,并且对我来说一切都很好(我没有条纹)。我正在使用 Java 7。也许您的错误出在程序的其他部分:)。

这个程序你也遇到同样的错误吗?

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

public class VirusGamePanel extends JPanel {
    private static final long serialVersionUID = 1L;
    Random colour = new Random();
    int score = 0;

    public void paint(Graphics g)
    {
        super.paint(g);
        g.setColor(Color.magenta);
        g.drawString("Score: "+ score,200,200);
        g.setColor(Color.orange);
        g.drawOval(200,150,200,200);
        Color rand = new Color(colour.nextInt(255),colour.nextInt(255),colour.nextInt(255));
        g.setColor(rand);
        g.fillOval(270,50,50,50);
        g.fillOval(100,100,50,50);
        g.fillOval(450,100,50,50);//this line is causing the problem
        g.fillOval(100,400,50,50);
    }

    public static void main(String[] args) {
        JFrame f=new JFrame();
        f.setSize(600,600);
        f.add(new VirusGamePanel());
        f.setVisible(true);

    }
}

【讨论】:

  • 我也没有得到这个程序的错误——但是我编写的程序从外部文件添加了 JPanel(所以它创建了 JFrame,然后在构造函数方法中添加了面板)。这可能是问题吗?谢谢您的帮助! :)
猜你喜欢
  • 2011-12-05
  • 2021-09-25
  • 2011-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多