0

So I'm writing code that should take a saved png image named text2.png and draws it inside of a JFrame. Here is my code:

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");
    }
}

My code just draws an empty JFrame, and I can't figure out how to have it draw the image itself. Thanks!

  • 2
    Don't try to draw on a JFrame. Create a JPanel that is the child of theJFrame, override its `paintComponent()` method and do any painting there. And don't read the image file in the paintComponent method - you should read it once in the constructor. – FredK Dec 23 '15 at 18:46

2 Answers2

1

How to get BufferedImage painted onto JFrame

No need to do custom painting.

Just use a JLabel to display the image.

BufferedImage img = ImageIO.read(file);
JLabel label = new JLabel( new ImageIcon(img) );
...
testFrame.add(label, BorderLayout.CENTER);
camickr
  • 321,443
  • 19
  • 166
  • 288
0

Your code shouldn't call your paint method directly. Instead, you should call repaint(). The windowing toolkit will then invoke the paint method with an appropriate Graphics object. You should draw into that object. Define your BufferedImage as an instance variable. You can probably do something like this:

public class TrainFromData extends Component{
    BufferedImage img;
    public void train(String fileName) throws Exception
    {
        try
        {
             File file = new File(fileName);
             img = ImageIO.read(file);
             repaint();  
        }
        catch(IOException ex)
        {
            ex.printStackTrace();
        }
    }
    @Override
    public void paintComponent(Graphics g) //instead of paint()
    {
        super.paintComponent(g);
        if ( img != null )
             g.drawImage(img, 50, 50, 150, 150, null);
    } 
    //etc.
LIProf
  • 436
  • 2
  • 5