【发布时间】:2015-12-23 18:39:44
【问题描述】:
所以我正在编写代码,该代码应该采用名为 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,我不知道如何让它自己绘制图像。谢谢!
【问题讨论】:
-
不要尝试在 JFrame 上绘图。创建一个作为 theJFrame 子级的 JPanel,覆盖其
paintComponent()方法并在那里进行任何绘画。并且不要在 paintComponent 方法中读取图像文件 - 您应该在构造函数中读取一次。
标签: java swing jframe png bufferedimage