因此,我正在编写代码,应该将保存的名为text2.png的png图像绘制到JFrame中。这里是我的代码:如何获取缓存图像绘制到JFrame上
public class TrainFromData extends JComponent{
public void train(String fileName) throws Exception
{
try
{
File file = new File(fileName);
BufferedImage img = ImageIO.read(file);
Graphics2D g2d = img.createGraphics();
g2d.drawImage(img, 50, 50, 150, 150, null);
paint(g2d);
g2d.dispose();
}
catch(IOException ex)
{
ex.printStackTrace();
}
}
public void paint(Graphics g)
{
super.paint(g);
}
public static void main(String[] args) throws Exception {
JFrame testFrame = new JFrame();
testFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
final TrainFromData comp = new TrainFromData();
comp.setPreferredSize(new Dimension(320, 200));
testFrame.getContentPane().add(comp, BorderLayout.CENTER);
testFrame.pack();
testFrame.setVisible(true);
comp.train("text2.png");
}
}
我的代码只是绘制一个空的JFrame,我无法弄清楚如何把它绘制图像本身。谢谢!
不要尝试在JFrame上绘图。创建一个JPanel,它是JFrame的子节点,覆盖它的'paintComponent()'方法并在那里做任何绘画。并且不要读取paintComponent方法中的图像文件 - 您应该在构造函数中读取一次。 – FredK
'JLabel'也许? – MadProgrammer