java - 希望我的屏幕截图显示在 JFrame 中

标签 java image swing screenshot jlabel

我有一个程序,可以在按下 JButton 时截取屏幕截图,但由于某种原因,它不会显示在我的 JFrame 中。我知道该方法有效,因为 JFrame 按照我的指示重新调整大小,但由于某种原因它不会显示镜头。

代码

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() {

我的行动就在这里。

 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();

}

这没有任何作用。

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

}

}

最佳答案

Graphics.drawImage(...) 方法只能在绘画方法中调用,就像执行自定义绘画的类的 PaintComponent() 方法一样。阅读 Custom Painting 上的 Swing 教程了解更多信息。

最简单的解决方案是使用图像创建 ImageIcon,然后只需设置已添加到框架中的 JLabel 的图标。然后标签将自动重新绘制。

另外,不要使用静态变量。再次使用教程中的示例来更好地构建您的程序。

关于java - 希望我的屏幕截图显示在 JFrame 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17407817/

相关文章:

java - 小程序中的多线程

java - 如何在不是来自 JNDI 的 JPA EntityMangerFactory 上设置数据源

c - OpenCV 获取/设置 IplImage RGB 值

javascript - HTMLImageElement 作为 React Child 无效

java - JButton 不适用于文本字段

java - 无法让 @Secured 在 Spring MVC 中工作

javascript - 图像边距不变。可能是由于我的 javascript?

java - DialogDisplayer 文本可复制

Java 事件绑定(bind)

java - 在 OS X Eclipse 上使用 Maven 安装 Mahout