所以我正在制作一个绘图程序,它通过从IRC服务器聊天室输入命令来绘制。所以除了绘图之外的所有东西都可以工作并且我检查了它(你可以看到检查系统:P)但是drawLine()命令并没有做它的事情。请帮忙!
PS:这是项目中的一个类文件,发送到这里的所有其他工作都信任我!
代码:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class PadDraw extends JComponent
{
//this is gonna be your image that you draw on
Image image;
//this is what we'll be using to draw on
Graphics2D graphics2D;
//these are gonna hold our coordinates
int currentX = 0, currentY = 0, oldX = 0, oldY = 0;
public PadDraw()
{
}
public void onCommand(String msg)
{
if(msg.equalsIgnoreCase("up"))
{
if(oldY > 0)
{
currentY = currentY - 30;
if(graphics2D != null)
graphics2D.drawLine(oldX, oldY, currentX, currentY);
repaint();
oldX = currentX;
oldY = currentY;
}
}
if(msg.equalsIgnoreCase("down"))
{
if(oldY < 861)
{
System.out.println(msg);
System.out.println("Starting Y: " + currentY);
currentY = currentY + 30;
System.out.println("Ending Y: " + currentY);
if(graphics2D != null)
graphics2D.drawLine(oldX, oldY, currentX, currentY);
repaint();
oldX = currentX;
oldY = currentY;
System.out.println("Old Y: " + oldY);
}
}
if(msg.equalsIgnoreCase("left"))
{
if(oldX > 0)
{
currentX = currentX - 30;
if(graphics2D != null)
graphics2D.drawLine(oldX, oldY, currentX, currentY);
repaint();
oldX = currentX;
oldY = currentY;
}
}
if(msg.equalsIgnoreCase("right"))
{
if(oldX < 847)
{
currentX = currentX + 30;
if(graphics2D != null){
graphics2D.drawLine(oldX, oldY, currentX, currentY);
repaint();
}
oldX = currentX;
oldY = currentY;
}
}
}
public void paintComponent(Graphics g)
{
if(image == null)
{
image = createImage(getSize().width, getSize().height);
graphics2D = (Graphics2D)image.getGraphics();
graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
clear();
}
g.drawImage(image, 0, 0, null);
}
答案 0 :(得分:0)
您忘记在super.paintComponent
方法中调用paintComponent
。有些人会错误地将其排除在外,以其正确的方式来实现“连续”绘画,但你实际所做的是打破油漆链,以及你是什么实际上看到的是油漆工件,这会让你相信有连续的油漆功能。
你这样做的方式不会产生“连续”的画。首先,您甚至没有将行绘制到JComponent
图形上下文中。其次,一旦你在super.paintComponent
方法中正确地调用了paintComponent
,你就会丢失之前的一幅画
拥有Line2D
个对象的列表。
List<Line2D> lines = new ArrayList<>();
循环List
方法中的paintComponent
并绘制它们
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
...
for (Line2D line : lines) {
g2.draw(line);
}
}
哦顺便说一下,paintComponent
应该是protected
而不是public
如果您想在图纸中添加一行,只需将另一个Line2D
对象添加到列表中,然后repaint()
lines.add(new Line2D.Double(x1, y1, x2, y2));
repaint();