【发布时间】:2014-05-27 02:57:30
【问题描述】:
我正在尝试使用 setRGB 绘制图像,然后从文本文件中获取 RGB 值,但是图像始终绘制为黑色。但是,如果我提供自己的价值观,它就会起作用。
以下是始终以黑色绘制的代码:
public JMenuBar menubar;
public JMenuItem importFile;
public Scanner filePath;
StringTokenizer tokens = null;
BufferedImage image;
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);
//g.setColor(myColor);
g.drawImage(image, 0, 0, null);
//g.drawRect(10, 10, 40, 50);
}
}
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]));
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 = new BufferedImage(30, 30, BufferedImage.TYPE_INT_RGB);
myColor = new Color(red,green,blue,255);
for (int i = 0; i < 30; i++) {
for (int j = 0; j < 30; j++) {
image.setRGB(i, j, myColor.getRGB());
}
}
myPanel.repaint();
}
}
}
}
});
setSize(500, 500);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
图像数组将这些值以 3 个一组的形式存储在一个文本文件中:
255 0 0 0 255 0 0 0 255
255 255 0 255 255 255 0 0 0
如果我改变这个:
int red = 180;
int green = 50;
int blue = 170;
它涂成另一种颜色。
不接受文本文件中的值的代码有什么问题?
【问题讨论】:
-
实际的runnable example that demonstrates your problem 需要更少的猜测和更好的响应
-
我也会在
for-loops 的末尾打电话给myPanel.repaint();而不是它 -
你需要展示你的数据加载器,因为目前
images[][][]可以是任何东西。 -
您可能需要重写 myPanel 的 paintComponent 方法或简单地调用 myPanel.getGraphics().drawImage(image);。请记住 Swing 组件不会重绘自己,因此我可能需要使用某种循环来始终将图像重绘到面板,因为 java 默认情况下会在每次调用后处理其图形。 (导致黑色或棕褐色背景颜色)
-
@StoneAgeCoder "默认情况下,每次调用后都会处理其图形" - 我不确定这是否完全正确 - 但无论哪种方式我都不相信。另外,你忘了提到 Swing 是单线程的,不是线程安全的,所以要小心你的循环;)
标签: java swing rgb bufferedimage