第一个Java程序,简单的打开图片并显示在面板上
代码如下:
1 import java.awt.Component;2 import java.awt.EventQueue;
3 import java.awt.Graphics;
4 import java.awt.event.*;
5 import java.io.*;
6 import javax.swing.*;
7
8 public class HelloWorld {
9
10 /**
11 * @param args
12 */
13 public static void main(String[] args) {
14 // TODO Auto-generated method stub
15 EventQueue.invokeLater(new Runnable() {
16
17 @Override
18 public void run() {
19 // TODO Auto-generated method stub
20 JFrame frame = new ImageViewerFrame();
21 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
22 frame.setVisible(true);
23 }
24 });
25 }
26 }
27
28 class ImageViewerFrame extends JFrame{
29 public ImageViewerFrame(){
30 setTitle("ImageViewer");
31 setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
32 label = new JLabel();
33 add(label);
34 chooser = new JFileChooser();
35 chooser.setCurrentDirectory(new File("."));
36 JMenuBar menubar = new JMenuBar();
37 setJMenuBar(menubar);
38 JMenu menu = new JMenu("File");
39 menubar.add(menu);
40 JMenuItem openItem = new JMenuItem("Open");
41 menu.add(openItem);
42 JMenuItem exitItem = new JMenuItem("Close");
43 menu.add(exitItem);
44 openItem.addActionListener(new ActionListener() {
45
46 @Override
47 public void actionPerformed(ActionEvent arg0) {
48 // TODO Auto-generated method stub
49 int result = chooser.showOpenDialog(null);
50 if(result == JFileChooser.APPROVE_OPTION){
51 String name = chooser.getSelectedFile().getPath();
52 label.setIcon(new ImageIcon(name));
53 }
54 }
55 });
56 exitItem.addActionListener(new ActionListener() {
57
58 @Override
59 public void actionPerformed(ActionEvent arg0) {
60 // TODO Auto-generated method stub
61 System.exit(0);
62 }
63 });
64 }
65 private JLabel label;
66 private JFileChooser chooser;
67 private static final int DEFAULT_WIDTH = 300;
68 private static final int DEFAULT_HEIGHT = 400;
69 }
显示效果如下:
以上是 第一个Java程序,简单的打开图片并显示在面板上 的全部内容, 来源链接: utcz.com/z/394702.html