我用Robot類創建了一個簡單的程序,它可以生成計算機的屏幕截圖。它會在您點擊JButton時創建屏幕截圖。JButton不會顯示
我試圖讓屏幕截圖時JFrame消失。不幸的是,JButton不會顯示... 你能告訴我我的代碼有什麼問題嗎?
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();
}
}
不要忘記,'pack()'是倒數第二個:) –
@LittleChild,除非你想'setLocationRelativeTo(null);'call;) – Obicere
'setLocation(fancyCoordinates)'已經被使用。你的論點和我的貓一樣無效,因爲缺少一個更好的比較* –