Reputation: 23
I've created a simple program with the Robot class which generates a screen capture of your computer. It creates the screen capture when you click on a JButton.
I've tried to make the JFrame disappear when the screen capture is being made. Unfortunately, the JButton won't display... Can you tell me what is wrong with my code?
package Threads;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.*;
public class ScreenCapture extends JFrame implements ActionListener{
private JButton b;
public ScreenCapture() throws Exception{
this.setTitle("Etfeld");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
this.pack();
this.setResizable(false);
this.setLocation(1366/2-100,678/2);
ImageIcon jamil=new ImageIcon("Logo.png");
Image logo=jamil.getImage();
this.setIconImage(logo);
JPanel jp=new JPanel();
b=new JButton("Capture!");
b.addActionListener(this);
this.add(jp);
jp.add(b);
}
@Override
public void actionPerformed(ActionEvent ae) {
Object obj=ae.getSource();
if(obj instanceof JButton){
try {
Robot robot = new Robot();
this.setVisible(false);
BufferedImage im=robot.createScreenCapture(new Rectangle(0,0,1366,768));
Toolkit.getDefaultToolkit().beep();
this.setVisible(true);
File outputfile = new File("saved.png");
ImageIO.write(im, "png", outputfile);
} catch (Exception v) {v.printStackTrace();}
}
}
public static void main(String []args) throws Exception{
ScreenCapture sc=new ScreenCapture();
}
}
Upvotes: 2
Views: 156
Reputation: 159754
The frame has been made visible before the button is added. Ensure that this statement appears after the component has been added. Invoke pack
prior to making the frame visible to ensure that the frame is large enough to make the button visible
pack();
setVisible(true);
Upvotes: 4
Reputation: 24998
You need to rearrange the calls to your methods. You should call pack()
just before making the frame visible; after you have added all your UI components.
Then, use setVisible(true)
to make the JFrame
visible.
Upvotes: 3