我正在开发一个包含按钮的JFrame /面板。当用户单击该按钮时,我想要一个图像(预先存储在计算机硬盘中)在前面的屏幕上打开。
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 :(得分:3)
我不知道一个非常短的方式,但我会使用这样的东西(因为qick hack得到一个印象):
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());
}
答案 1 :(得分:0)
我认为这会奏效......
代码:
process = new ProcessBuilder(“mspaint”,“yourFileName.jpeg”)。start();
这将使用mspaint打开您的图像文件.....
并使用 * Java高级成像(JAI) *
答案 2 :(得分: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
}
答案 3 :(得分: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)
{
}