【发布时间】:2014-05-28 01:45:01
【问题描述】:
我正在使用 Java,并且正在从 ppm 文件中读取,代码为 P3。
P3
# The P3 means colors are in ASCII, then 3 columns and 2 rows,
# then 255 for max color, then RGB triplets
3 2
255
255 0 0 0 255 0 0 0 255
255 255 0 255 255 255 0 0 0
我使用此文件的目标是使用上述 rgb 值绘制 6 张图像,但是所有图像始终保持与最后一个 rgb 值相同的颜色。这是我的代码:
public class Window2 extends JFrame {
public JMenuBar menubar;
public JMenuItem importFile;
public Scanner filePath;
StringTokenizer tokens = null;
ArrayList<BufferedImage> image = new ArrayList<>();
int[][][] images;
JPanel panelDown = new JPanel();
MyPanel myPanel;
Color myColor;
int[] coords = new int[2];
int i = 0, j = 0;
public class MyPanel extends JPanel {
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
for (BufferedImage image1 : image) {
g.drawImage(image1, 0, 0, null);
}
}
}
public Window2() {
super("Exercise 2");
menubar = new JMenuBar();
setLayout(new BorderLayout());
JPanel panelBar = new JPanel();
add(panelBar, BorderLayout.NORTH);
add(panelDown, BorderLayout.CENTER);
importFile = new JMenuItem("Import", 'I');
panelBar.add(menubar);
menubar.add(importFile);
importFile.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
FileDialog fd = new FileDialog(Window2.this, "Import Maze", FileDialog.LOAD);
fd.setFile(".txt");
fd.setLocation(Window2.this.getX() + 100, Window2.this.getY() + 100);
fd.show();
if (!fd.getFile().endsWith(".txt")) {
JOptionPane.showMessageDialog(Window2.this, "Wrong file extension", "Error", JOptionPane.WARNING_MESSAGE);
} else {
File theFile = new File(fd.getDirectory() + "\\" + fd.getFile());
try {
filePath = new Scanner(theFile);
} catch (FileNotFoundException ex) {
Logger.getLogger(Window2.class.getName()).log(Level.SEVERE, null, ex);
}
images = readFile(filePath);
panelDown.setLayout(new GridLayout(coords[0], coords[1]));
int z=0;
for (int k = 0; k < coords[0]; k++) {
for (int l = 0; l < coords[1]; l++) {
int red = images[k][l][0];
int green = images[k][l][1];
int blue = images[k][l][2];
myPanel = new MyPanel();
panelDown.add(myPanel);
image.add(new BufferedImage(30, 30, BufferedImage.TYPE_INT_ARGB));
myColor = new Color(red,green,blue,255);
for (int i = 0; i < 30; i++) {
for (int j = 0; j < 30; j++) {
image.get(z).setRGB(i, j, myColor.getRGB());
}
}
z++;
}
}
myPanel.repaint();
}
}
});
setSize(500, 500);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
这里缺少一种方法,它是 readFile。它分别返回一个数组[][][]、行数、列数和 rgb 值。关于如何解决此问题的任何想法?
【问题讨论】:
-
而且每张图片的颜色值都是你所期待的?
-
另外,图像在您的
paintComponent方法中相互叠加... -
图像应该是红色、绿色、蓝色、黄色、白色、黑色,但所有六个图像都显示为黑色。如果它们相互重叠,我怎么能看到 6 个不同的图像?
-
您看到相同的图像 6 次,因为您的
paintComponent方法在MyPanel的每个实例的上下文中的同一位置绘制所有图像。尝试仅绘制 1,可能通过将z传递给MyPanel以便它知道要绘制哪个图像...
标签: java bufferedimage paintcomponent ppm