在JFrame打开并显示图片,如何让打开图片的尺寸和JFrame的尺寸保持一致!即:JFrame的尺寸跟隨打开图片文件的尺寸不同而发生变化,保证图片充满整个JFrame。现在的问题是图片不能完全充满。代码可直接运行,一个主类,一个文件过滤器。import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;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;import com.gjg.MyFilter;public class ImageViewer {
public static void main(String[] args) {
JFrame frame = new ImageViewerFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(0, 0); // 定位
frame.setVisible(true);
}
}class ImageViewerFrame extends JFrame {
private static final long serialVersionUID = 1L; private JLabel label; public ImageViewerFrame() { setTitle("ImageViewer");
setSize(400, 400);
label = new JLabel();
add(label);
JMenuBar menuBar = new JMenuBar();
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) {
JFileChooser fc = new JFileChooser();
// Add filefilter & fileview
MyFilter filter = new MyFilter(new String[] { "jpg", "gif",
"png" }, "图片文件");
fc.addChoosableFileFilter(filter);
fc.removeChoosableFileFilter(fc.getAcceptAllFileFilter());
fc.setFileFilter(filter);
int result = fc.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
String name = fc.getSelectedFile().getPath();
ImageIcon imageIcon = new ImageIcon(name);
int p_width = imageIcon.getIconWidth();
int p_height = imageIcon.getIconHeight();
setSize(p_width, p_height);
label.setIcon(imageIcon);
}
}
}); JMenuItem exitItem = new JMenuItem("Exit");
menu.add(exitItem);
exitItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
}
}package com.gjg;import java.io.File;
import java.util.Enumeration;
import java.util.Hashtable;import javax.swing.filechooser.FileFilter;
public class MyFilter extends FileFilter  {
private Hashtable filters = null; private String description = null; private String fullDescription = null; private boolean useExtensionsInDescription = true;
public MyFilter() {
this.filters = new Hashtable();
}
public MyFilter(String extension) {
this(extension, null);
}
public MyFilter(String extension, String description) {
this();
if (extension != null)
addExtension(extension);
if (description != null)
setDescription(description);
}
public MyFilter(String[] filters) {
this(filters, null);
}
public MyFilter(String[] filters, String description) {
this();
for (int i = 0; i < filters.length; i++) {
// add filters one by one
addExtension(filters[i]);
}
if (description != null)
setDescription(description);
}
public boolean accept(File f) {
if (f != null) {
if (f.isDirectory()) {
return true;
}
String extension = getExtension(f);
if (extension != null && filters.get(getExtension(f)) != null) {
return true;
}
;
}
return false;
}
public String getExtension(File f) {
if (f != null) {
String filename = f.getName();
int i = filename.lastIndexOf('.');
if (i > 0 && i < filename.length() - 1) {
return filename.substring(i + 1).toLowerCase();
}
;
}
return null;
}
public void addExtension(String extension) {
if (filters == null) {
filters = new Hashtable(5);
}
filters.put(extension.toLowerCase(), this);
fullDescription = null;
}
public String getDescription() {
if (fullDescription == null) {
if (description == null || isExtensionListInDescription()) {
fullDescription = description == null ? "(" : description
+ " (";
// build the description from the extension list
Enumeration extensions = filters.keys();
if (extensions != null) {
fullDescription += "." + (String) extensions.nextElement();
while (extensions.hasMoreElements()) {
fullDescription += ", ."
+ (String) extensions.nextElement();
}
}
fullDescription += ")";
} else {
fullDescription = description;
}
}
return fullDescription;
}
public void setDescription(String description) {
this.description = description;
fullDescription = null;
}
public void setExtensionListInDescription(boolean b) {
useExtensionsInDescription = b;
fullDescription = null;
}
public boolean isExtensionListInDescription() {
return useExtensionsInDescription;
}
}

解决方案 »

  1.   

    加pack();int p_width = imageIcon.getIconWidth();
    int p_height = imageIcon.getIconHeight();
    setSize(p_width, p_height);
    label.setIcon(imageIcon);
    pack();
      

  2.   

    先读取图像的宽和高,这个在图像的文件中保存得有,在图像的信息头中,如TGA图像的是第13个字节处,不同的图片保存宽和高在图像中的位置不一样,得分开处理,然后再用这个宽和高来设置frame的宽和高。
      

  3.   

    楼主,我是个新手,不过我也想过来参与一下,你看这样行不行:你在JBUILDER中把容器的布局管理器换成BORDERLAYOUT,再让组件居中(center),学习,关注中......
      

  4.   

    正如“boby”所说,加pack();可以解决问题,但又遇到了新问题,我想做一个图片截取器,大致操作是,选择并打开图片文件,移动鼠标时,会有一个选取框跟着移动,点击鼠标左键则保存选取的图片,窗口打开时,会有一个默认的图片,当重新打开的图片尺寸小于默认图片时,一切正常,但重新打开的图片尺寸大于默认图片时,图片仍然不能完全充满JFrame。文件过滤器类不变,换成下面的代码看看。
      

  5.   

    package com.gjg;import java.awt.BorderLayout;
    import java.awt.Graphics;
    import java.awt.GridLayout;
    import java.awt.Image;
    import java.awt.Point;
    import java.awt.Rectangle;
    import java.awt.Robot;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionAdapter;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.net.URL;import javax.imageio.ImageIO;
    import javax.swing.ImageIcon;
    import javax.swing.JFileChooser;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JMenuItem;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JPopupMenu;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;public class CutPic extends JFrame { private static final long serialVersionUID = 1L; int mouseX = 0; int mouseY = 0; static int defultW = 128; static int defultH = 128; String fileName = "/resources/images/splash.jpg"; TestPanel jp = null; private JPopupMenu popupMenu = new JPopupMenu(); private JMenuItem selectFileMenuItem = new JMenuItem("选择文件"); private JMenuItem setConfigMenuItem = new JMenuItem("设置"); private JMenuItem aboutMenuItem = new JMenuItem("关于作者"); private JMenuItem exitMenuItem = new JMenuItem("退出"); JFrame jframe; public CutPic() {
    popupMenu.add(selectFileMenuItem);
    popupMenu.add(setConfigMenuItem);
    popupMenu.add(aboutMenuItem);
    popupMenu.add(exitMenuItem); jframe = new JFrame("手机壁纸截取器V1.0");
    jp = new TestPanel(fileName, jframe); jframe.add(popupMenu);
    jframe.add(jp, BorderLayout.CENTER);
    jframe.setLocation(0, 0); // 定位
    jframe.setUndecorated(true);
    jframe.setVisible(true); // 鼠标经过动作 监听器 注册 记录鼠标位置
    jp.addMouseListener(new MouseAdapter() {
    public void mousePressed(MouseEvent mouseEvent) {
    if (mouseEvent.getButton() == MouseEvent.BUTTON1) {
    mouseX = mouseEvent.getX();
    mouseY = mouseEvent.getY();
    }
    }
    });
    // 鼠标拖动窗口动作 监听器 注册
    jp.addMouseMotionListener(new MouseMotionAdapter() {
    public void mouseDragged(MouseEvent e) {
    if (e.getModifiers() == MouseEvent.BUTTON1_MASK) {
    jframe.setLocation(jframe.getX() + e.getX() - mouseX,
    jframe.getY() + e.getY() - mouseY);
    }
    }
    }); // 鼠标右击动作 监听器 注册
    jp.addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
    if (SwingUtilities.isRightMouseButton(e)) {
    popupMenu.show(jframe, e.getX(), e.getY());
    }
    }
    }); // 鼠标左击动作 监听器 注册 保存图片
    jp.addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
    try {
    if (SwingUtilities.isLeftMouseButton(e)) {
    // 拷贝屏幕到一个BufferedImage对象screenshot
    BufferedImage screenshot = (new Robot())
    .createScreenCapture(new Rectangle(jframe
    .getX()
    + (e.getX() - (defultW / 2)), jframe
    .getY()
    + (e.getY() - (defultH / 2)), defultW,
    defultH)); JFileChooser chooser = new JFileChooser();
    MyFilter filter = new MyFilter(new String[] { "jpg",
    "gif", "png" }, "图片文件");
    chooser.removeChoosableFileFilter(chooser
    .getAcceptAllFileFilter());
    chooser.setFileFilter(filter); if (JFileChooser.APPROVE_OPTION == chooser
    .showSaveDialog(jframe)) {
    String sfilename = chooser.getSelectedFile()
    .getPath(); // 获得文件路径
    boolean b = false;
    if (sfilename != null
    && sfilename.compareTo("") != 0) {
    // 如果没有扩展名,则默认为jpg格式
    if (sfilename.indexOf(".") == -1) {
    sfilename += ".jpg";
    b = true;
    } else {
    b = sfilename.endsWith(".jpg")
    || sfilename.endsWith(".gif")
    || sfilename.endsWith(".png");
    }
    }
    if (!b) {
    JOptionPane.showMessageDialog(new JPanel(),
    "文件名不正确!必须为图像文件!", "错误",
    JOptionPane.ERROR_MESSAGE);
    } else {
    File f = new File(sfilename);
    // 将screenshot对象写入图像文件
    ImageIO.write(screenshot, sfilename
    .substring(sfilename.indexOf(".") + 1),
    f);
    }
    }
    }
    } catch (Exception ex) {
    System.out.println(ex);
    }
    }
    }); // 鼠标移动动作 监听器 注册
    jp.addMouseMotionListener(new MouseMotionAdapter() {
    public void mouseMoved(MouseEvent e) {
    Point p1 = new Point(e.getX() - defultW / 2, e.getY() + defultH
    / 2);
    Point p2 = new Point(e.getX() + defultW / 2, e.getY() + defultH
    / 2);
    Point p3 = new Point(e.getX() - defultW / 2, e.getY() - defultH
    / 2);
    Point p4 = new Point(e.getX() + defultW / 2, e.getY() - defultH
    / 2);
    jp.setPoint(p1, p2, p3, p4);
    }
    }); // 环境设置 监听器 注册
    setConfigMenuItem.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    GridLayout gridLayout = new GridLayout(2, 2);
    JPanel jpl10 = new JPanel(gridLayout);
    Object[] message = new Object[4];
    message[0] = new JLabel("长:");
    message[1] = new JTextField("128", 3);
    message[2] = new JLabel("宽:");
    message[3] = new JTextField("128", 3); String[] options = { "设置", "取消" }; int result = JOptionPane.showOptionDialog(jpl10, message,
    "环境设置", JOptionPane.DEFAULT_OPTION,
    JOptionPane.INFORMATION_MESSAGE, null, options,
    options[0]);
    switch (result) {
    case 0:
    defultW = Integer.parseInt(((JTextField) message[1])
    .getText());
    defultH = Integer.parseInt(((JTextField) message[3])
    .getText());
    break;
    default:
    break;
    }
    }
    }); // 退出 监听器 注册
    exitMenuItem.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    System.exit(0);
    }
    }); // 关于作者 监听器 注册
    aboutMenuItem.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    JPanel jpl12 = new JPanel();
    ImageIcon imageIcon = new ImageIcon(getClass().getResource(
    "/resources/images/sun.gif"));
    URL img = getClass().getResource("/resources/images/me.jpg");
    String imagesrc = "<img src=\"" + img
    + "\" width=\"55\" height=\"55\">";
    String message = "作者:\n" + "E_mail:[email protected]\n"
    + "BLOG:http://blog.csdn.net/myid\n" + "QQ:12331741\n"
    + "版本:V 1.0";
    JOptionPane.showMessageDialog(jpl12, "<html>" + imagesrc
    + "<br><center>" + message, "关于作者",
    JOptionPane.INFORMATION_MESSAGE, imageIcon);
    }
    }); // 选择图片 监听器 注册
    selectFileMenuItem.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    JFileChooser fc = new JFileChooser();
    // Add filefilter & fileview
    MyFilter filter = new MyFilter(new String[] { "jpg", "gif",
    "png" }, "图片文件");
    fc.addChoosableFileFilter(filter);
    fc.removeChoosableFileFilter(fc.getAcceptAllFileFilter());
    fc.setFileFilter(filter);
    // show the filechooser
    int result = fc.showOpenDialog(jp);
    // if we selected an image, load the image
    if (result == JFileChooser.APPROVE_OPTION) {
    File file = fc.getSelectedFile();
    fileName = file.getPath();
    if (file.exists()) {
    jp.setImage(fileName, jframe);
    } else {
    JOptionPane.showMessageDialog(new JPanel(),
    "你选择的图像文件不存在!请重新选择!", "错误",
    JOptionPane.ERROR_MESSAGE);
    }
    }
    }
    });
    } public static void main(String args[]) {
    new CutPic();
    }}
      

  6.   


    class TestPanel extends JPanel {
    private static final long serialVersionUID = 1L; int p_width = 0; int p_height = 0; Image img = null; private Point p1; private Point p2; private Point p3; private Point p4; public TestPanel(String picName, JFrame jframe) {
    ImageIcon imageIcon = new ImageIcon(getClass().getResource(picName));
    img = imageIcon.getImage();
    p_width = imageIcon.getIconWidth();
    p_height = imageIcon.getIconHeight();
    setBounds(0, 0, p_width, p_height);
    jframe.setSize(p_width, p_height);
    } public void paint(Graphics g) {
    if (img != null) {
    g.drawImage(img, 0, 0, p_width, p_height, this);
    if (p1 != null && p2 != null && p3 != null && p4 != null) {
    g.drawLine((int) p1.getX(), (int) p1.getY(), (int) p3.getX(),
    (int) p3.getY());
    g.drawLine((int) p1.getX(), (int) p1.getY(), (int) p2.getX(),
    (int) p2.getY());
    g.drawLine((int) p2.getX(), (int) p2.getY(), (int) p4.getX(),
    (int) p4.getY());
    g.drawLine((int) p3.getX(), (int) p3.getY(), (int) p4.getX(),
    (int) p4.getY());
    }
    } } public void setImage(String fileName, JFrame jframe) {
    ImageIcon imageIcon = new ImageIcon(fileName);
    img = imageIcon.getImage();
    p_width = imageIcon.getIconWidth();
    p_height = imageIcon.getIconHeight();
    setBounds(0, 0, p_width, p_height);
    jframe.setSize(p_width, p_height);
    repaint();
    } public void setPoint(Point p1, Point p2, Point p3, Point p4) {
    this.p1 = p1;
    this.p2 = p2;
    this.p3 = p3;
    this.p4 = p4;
    repaint();
    }}
      

  7.   

    在你每次改变jframe的size后要加上jframe.validate();让jframe再次布置子组件.