Java学习之图像文件浏览器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | import java.awt.*; import java.awt.event.*; import java.io.*; import javax.swing.*; /** 一个浏览图像的程序 */ public class ImageViewer { public static void main(String[] args) { JFrame Frame = new ImageViewerFrame(); Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Frame.setVisible(true); } } /** 用一个窗体上的标签显示图像 */ class ImageViewerFrame extends JFrame { public ImageViewerFrame() { setTitle("图像浏览器"); setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); //新建标签,用来显示图像 Label = new JLabel(); add(Label); //新建选择文件 chooser = new JFileChooser(); chooser.setCurrentDirectory(new File(".")); //新建菜单栏 JMenuBar MenuBar = new JMenuBar(); setJMenuBar(MenuBar); JMenu menu = new JMenu("文件"); MenuBar.add(menu); JMenuItem openItem = new JMenuItem("打开"); menu.add(openItem); openItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent Event) { //显示文件选择对话框 int result = chooser.showOpenDialog(null); //如果选定的文件,设置为图标标签 if (result == JFileChooser.APPROVE_OPTION) { String name = chooser.getSelectedFile().getPath(); Label.setIcon(new ImageIcon(name)); } } }); JMenuItem exitItem = new JMenuItem("退出"); menu.add(exitItem); exitItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent Event) { System.exit(0); } }); } private JLabel Label; private JFileChooser chooser; private static final int DEFAULT_WIDTH = 300; private static final int DEFAULT_HEIGHT = 400; } |
如果在Visual Basic中,编写这个程序可能相当简单,只要简单的拖拽再加几行代码就可以了,但是JDK没有可视化的界面,所以必须通过编写代码来完成这一切工作。推荐用Eclipse来编写,因为刚刚编写的时候难免会有出错,Eclipse的错误提醒是个不错的卖点,推荐。
标签:java, 图像, 学习, 文件, 浏览器
赵健
近期评论