2013-07-01 50 views
0

我有一個程序在按下JButton時會截屏,但出於某種原因它不會顯示在我的JFrame中。我知道該方法的工作原理是因爲JFrame重新調整大小,就像我告訴它,但由於某種原因它不會顯示該鏡頭。想要我的屏幕截圖在JFrame中顯示

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

我有我的作用就在這裏。

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 

} 

} 
+0

哦,'g2d'爲空。 – johnchen902

+0

你在哪裏初始化/獲取'Graphics2D g2d'對象? – asteri

+0

@Jeff在頂部我做靜態Graphics2D g2d; –

回答

3

的Graphics.drawImage(...)方法應該只從withing繪畫方法,像一個的類,它的風俗畫的的paintComponent()方法調用。有關更多信息,請參閱Custom Painting上的Swing教程。

最簡單的解決方案是使用圖像創建一個ImageIcon,然後設置已添加到幀中的JLabel的圖標。然後標籤會自動重新繪製。

另外,不要使用靜態變量。再次使用教程中的示例來更好地構建您的程序。

+0

如何將bufferedImage更改爲ImageIcon? –

+0

閱讀ImageIcon API。或者閱讀「如何使用圖標」的Swing教程。您可以通過從上一個教程鏈接獲取目錄來查找本教程。 – camickr