ndfkj asdkfh
ndfkj asdkfh

Reputation: 316

Want My Screenshot To Display In A JFrame

I have a program that takes a screenshot when a JButton is pressed, but for some reason it wont show in my JFrame. I know that the method works because the JFrame re-sizes like I tell it to but for some reason it wont display the shot.

CODE

public class main implements ActionListener{
public static Font f = new Font(Font.DIALOG, Font.BOLD, 25);
static JButton button = new JButton("Press For A Screen Shot!");
static JFrame frame = new JFrame("Snipping Tool+");
static JLabel label;
static Graphics2D g2d;
static JPanel panel;
BufferedImage shot;

public main(){

    frame.setSize(400, 350);
    frame.setResizable(false);

    button.setFont(f);
    button.setBackground(Color.BLACK);
    button.setForeground(Color.white);
    button.addActionListener(new ActionListener() {

I have my action right here.

 public void actionPerformed(ActionEvent e)
        {
              System.out.println("sh");       
            try {
                shot = new Robot().createScreenCapture(new          
Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
            } catch (HeadlessException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (AWTException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }               
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            frame.setSize(screenSize);
            Image ii = (BufferedImage) shot;
            g2d.drawImage(shot, Image.SCALE_AREA_AVERAGING, 0, 0, 0, null);
        }
    });      

    ImageIcon image = new ImageIcon("res//images//SnippingTool.png");
    label = new JLabel(image);
    frame.add(button, BorderLayout.NORTH);
    frame.add(label, BorderLayout.SOUTH);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
}

public static void main(String args[]){
    main m = new main();

}

This doesn't do anything.

@Override
public void actionPerformed(ActionEvent arg0) {
    // TODO Auto-generated method stub

}

}

Upvotes: 0

Views: 208

Answers (1)

camickr
camickr

Reputation: 324088

The Graphics.drawImage(...) method should only be invoked from withing a painting method, like the paintComponent() method of a class that does custom painting. Read the Swing tutorial on Custom Painting for more information.

The easiest solution is to create an ImageIcon using the image and then just set the Icon of a JLabel that you have added to your frame. Then the label will repaint itself automatically.

Also, don't use static variables. Again use the examples from the tutorial to better structure your program.

Upvotes: 3

Related Questions