【发布时间】:2016-06-05 17:49:34
【问题描述】:
抱歉,这可能是一个非常基本的问题,但我有一个名为蝴蝶的类,其中包含用于绘制蝴蝶对象的代码,如下所示:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BasicStroke;
public class butterfly extends JPanel {
public butterfly() {
}
public void draw(Graphics2D g2){
//the width of the oval. A petal is an oval.
//TODO: Your code goes IN HERE (not in main), ALL OF IT. Replace the code below.
//draw one oval of length 300pixels from center to edge
g2.setColor(Color.blue);
g2.fillOval(500,55, 70, 70);
g2.fillOval(450, 40, 70, 70);
g2.fillOval(460,100, 40, 40);
g2.fillOval(495, 110, 40, 40);
g2.setColor(Color.black);
g2.setStroke(new BasicStroke(13));
g2.drawLine(520, 50, 490, 150);
}
}
然后我试着把它放在这个组件中,这样我就可以用它放更多的对象,但它甚至不会画蝴蝶?
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class RippingOffofAmy extends JComponent
{
private butterfly yay;
public RippingOffofAmy()
{
yay = new butterfly();
}
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
//checks to see if rectangle has moves 100 places yet
//if has, then adds new obstacle and resets count
yay.draw(g2);
//draws obstacle and avatar
}
}
为什么? (忽略我使用的一些朋友代码的类名和 cmets)如果我遗漏了什么,有人可以具体说明要添加的内容,因为我在 java 方面很糟糕,谢谢!
【问题讨论】:
-
这不是如何进行 Swing 绘图,看起来你正在疯狂猜测如何做到这一点,不要。你看过教程了吗?这就是我要开始的地方:Lesson: Performing Custom Painting
-
如果您在查看教程后仍然卡住,然后考虑创建并发布一个 sscce 或 minimal example program/mcve 将您的代码压缩成仍然可以编译和运行的最小位,没有外部依赖项(例如需要链接到数据库或图像),没有与您的问题无关的额外代码,但仍能证明您的问题。
-
1) 蝴蝶不一定是面板 2) 显示 GUI 的主要方法在哪里?
-
@user2130108 那就学习吧。说你很烂而不主动尝试提高你的知识是不好的。
-
发布您的minimal reproducible example,让我们看看到底发生了什么。据我们所知,您的 RippingOffofAmy 类的大小为 0 x 0。此外,您应该在覆盖中调用 super 的 paintComponent 方法。