我一直在尝试在画布上画画,但我无法使它工作,我可以看到JFrame
但是它似乎并没有在Mover()
调用paint方法正在添加{1}}对象。这是第一次使用画布,所以我不知道我错过了什么。这是代码:
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.util.*;
import java.awt.*;
import java.io.File;
public class Move extends Canvas
{
private static int [][]imgRGB;
public Move()
{
try
{
BufferedImage hugeImage = ImageIO.read(new File("C:/Users/pc/Pictures/Nave.gif"));
imgRGB = convertToRGB(hugeImage);
}
catch(IOException e)
{
System.out.println(e);
}
}
public void Paint(Graphics g)
{
super.paint(g);
for(int i=0 ; i<imgRGB.length ; i++)
{
for(int j=0 ; j<imgRGB[i].length; j++)
{
g.setColor(new Color(imgRGB[i][j]));
g.drawLine(i,j,i,j);
}
}
}
private static int[][] convertToRGB(BufferedImage image) {
final byte[] pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
final int width = image.getWidth();
final int height = image.getHeight();
final boolean hasAlphaChannel = image.getAlphaRaster() != null;
int[][] result = new int[height][width];
if (hasAlphaChannel) {
final int pixelLength = 4;
for (int pixel = 0, row = 0, col = 0; pixel < pixels.length; pixel += pixelLength) {
int argb = 0;
argb += (((int) pixels[pixel] & 0xff) << 24); // alpha
argb += ((int) pixels[pixel + 1] & 0xff); // blue
argb += (((int) pixels[pixel + 2] & 0xff) << 8); // green
argb += (((int) pixels[pixel + 3] & 0xff) << 16); // red
result[row][col] = argb;
col++;
if (col == width) {
col = 0;
row++;
}
}
} else {
final int pixelLength = 3;
for (int pixel = 0, row = 0, col = 0; pixel < pixels.length; pixel += pixelLength) {
int argb = 0;
argb += -16777216; // 255 alpha
argb += ((int) pixels[pixel] & 0xff); // blue
argb += (((int) pixels[pixel + 1] & 0xff) << 8); // green
argb += (((int) pixels[pixel + 2] & 0xff) << 16); // red
result[row][col] = argb;
col++;
if (col == width) {
col = 0;
row++;
}
}
}
return result;
}
public static void main(String[] args)
{
JFrame container = new JFrame("pixel");
container.add(new Move());
container.setSize(400,400);
container.setVisible(true);
container.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
答案 0 :(得分:1)
public void Paint(Graphics g)
方法名称区分大小写。您应该覆盖paint(...)
。
始终使用@Override注释,当您尝试覆盖不存在的方法时,编译器会通知您:
@Override
public void paint(Graphics g)
{
...
}
但是,您不应该在Swing应用程序中覆盖Canvas。
相反,您应该扩展JPanel
,然后您应该覆盖paintComponent(...)
方法。
阅读Custom Painting上Swing教程中的部分,了解更多信息和工作示例。