因此,我正在编写代码,该代码应该采用名为 text2.png 的已保存 png 图像并将其绘制在 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,我不知道如何让它自己绘制图像。谢谢!
最佳答案
How to get BufferedImage painted onto JFrame
无需进行自定义绘画。
只需使用 JLabel 即可显示图像。
BufferedImage img = ImageIO.read(file);
JLabel label = new JLabel( new ImageIcon(img) );
...
testFrame.add(label, BorderLayout.CENTER);
关于java - 如何将 BufferedImage 绘制到 JFrame 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34441784/