2010-12-02 40 views
-1

我正在處理一個包含按鈕的JFrame /面板。當用戶點擊按鈕時,我想要一個圖像(它將被存儲在電腦硬盤中)在前屏幕上打開。如何使用Java打開.bmp/.jpeg圖像

button.addActionListener(new ActionListener(){ 
     public void actionPerformed(ActionEvent e){ 
     //here i want a code that will somehow open the image from a given directory 
      }}); 

有關如何去解決這個問題的任何建議?我必須告訴圖像的存儲位置,並觸發虛擬「雙擊」,以使圖像在前屏幕上彈出。甚至有可能使用java來同步這些計算機功能?

+0

這似乎是你在之後http://stackoverflow.com/questions/526037/java-how-to-open-user-system-preffered-editor-for-given-file – Karl 2010-12-02 22:53:23

回答

3

我不知道一個很短的路,但我會用這樣的事情(如qick破解得到的印象):

try { 
    // this is a new frame, where the picture should be shown 
    final JFrame showPictureFrame = new JFrame("Title"); 
    // we will put the picture into this label 
    JLabel pictureLabel = new JLabel(); 

    /* The following will read the image */ 
    // you should get your picture-path in another way. e.g. with a JFileChooser 
    String path = "C:\\Users\\Public\\Pictures\\Sample Pictures\\Koala.jpg"; 
    URL url = new File(path).toURI().toURL(); 
    BufferedImage img = ImageIO.read(url); 
    /* until here */ 

    // add the image as ImageIcon to the label 
    pictureLabel.setIcon(new ImageIcon(img)); 
    // add the label to the frame 
    showPictureFrame.add(pictureLabel); 
    // pack everything (does many stuff. e.g. resizes the frame to fit the image) 
    showPictureFrame.pack(); 

    //this is how you should open a new Frame or Dialog, but only using showPictureFrame.setVisible(true); would also work. 
    java.awt.EventQueue.invokeLater(new Runnable() { 

     public void run() { 
     showPictureFrame.setVisible(true); 
     } 
    }); 

    } catch (IOException ex) { 
    System.err.println("Some IOException accured (did you set the right path?): "); 
    System.err.println(ex.getMessage()); 
    } 
0

我認爲這會工作...

代碼:

process = new ProcessBuilder(「mspaint」,「yourFileName.jpeg」)。start();

這將打開MSPAINT圖像文件.....

,還可以使用* Java高級圖像(JAI) *

0

試試這個代碼

try 
{ 
    // the line that reads the image file 
    BufferedImage image; 


    // work with the image here ... 
     image = ImageIO.read(new File("C://Users//Neo//Desktop//arduino.jpg")); 


     jLabel1.setIcon(new ImageIcon(image)); 
} 
catch (IOException e) 
{ 
    // log the exception 
    // re-throw if desired 
} 
0

我不確定,但試試這個...

try 
{ 

    JLabel picture=new JLabel(); 

    ImageIcon ic=new ImageIcon(Toolkit.getDefaultToolkit().getImage(getClass().getResource("C:\\Users\\Desktop\\xyz.jpg"))); 

    picture.setIcon(ic); 

} 
catch(Exception) 
{ 
}