最近天天加班陪测试组做测试,以前都是开发J2EE,下载来一本电子书,里边有个例子,是个小小的图片浏览器,
这个东西很粗糙,JFrame的大小不能随图片大小而改变,我想着去改进下,JFrame的大小是随图片大小改变了,但是JMenuBar和JLabel的大小却变不了,百度了下,都没有找到解决方法:
代码如下:
package com.yejq.Swing; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import javax.swing.ImageIcon; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; /* * 图片预览器 */ public class ImageViewer { /** * @param args */ 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() { this.setTitle("图片预览器"); this.setSize(DEFAULT_WITH, DEFAULT_HEIGHT); label = new JLabel(); this.add(label); chooser = new JFileChooser(); chooser.setCurrentDirectory(new File(".")); JMenuBar menuBar = new JMenuBar(); this.setJMenuBar(menuBar); JMenu menu = new JMenu("File"); menuBar.add(menu); JMenuItem openItem = new JMenuItem("open"); menu.add(openItem); openItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { //show file chooser dialog int result = chooser.showOpenDialog(null); //if file selected, set it as icon of the label if(result == JFileChooser.APPROVE_OPTION) { String name = chooser.getSelectedFile().getPath(); ImageIcon image = new ImageIcon(name); changeSize(image.getIconWidth(),image.getIconHeight()); label.setIcon(image); } } }); JMenuItem exitItem = new JMenuItem("exit"); menu.add(exitItem); exitItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { System.exit(0); } }); } public void changeSize(int width, int height) { this.setSize(width,height); } private JLabel label; private JFileChooser chooser; private static final int DEFAULT_WITH = 300; private static final int DEFAULT_HEIGHT = 400; }