我想通过打开按钮来打开存在本地磁盘上的某张图片,然后按照JLabel的大小来显示出图片,请问各位高手怎样实现啊?

解决方案 »

  1.   

    现在能打开图片了,可是想再通过按钮更改图片作不到,怎么解决啊?我的程序如下:
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Container;
    import java.awt.Image;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFileChooser;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.border.LineBorder;public class openphoto extends JFrame { /**
     * @param args
     */
    private JLabel l1=null;
    private JPanel p1=new JPanel();
    private JButton b1=new JButton("打开");
    private String photopath=null;
    public openphoto()
    {
    creatGUI();
    this.setSize(140, 180);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setLocationRelativeTo(null);
    this.setVisible(true);
    }
    private void creatGUI() {
    // TODO Auto-generated method stub
    Container cp=this.getContentPane();
    cp.setLayout(new BorderLayout());
    p1.setLayout(new BorderLayout());
    cp.add(p1,BorderLayout.CENTER);
    cp.add(b1,BorderLayout.SOUTH);
    b1.addActionListener(new open());

    }
    public static void main(String[] args) {
    // TODO Auto-generated method stub
    openphoto op=new openphoto(); }
    class open implements ActionListener
    { public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub
    JFileChooser jfc=new JFileChooser();
    int returnval=jfc.showOpenDialog(openphoto.this);
    if(returnval==JFileChooser.APPROVE_OPTION)
    {
    photopath=jfc.getSelectedFile().getAbsolutePath();
    //System.out.println(photopath);
    ImageIcon image = new ImageIcon(photopath);
    image.setImage(image.getImage().getScaledInstance(108, 135, Image.SCALE_DEFAULT));
    l1=new JLabel(image);
    l1.setBorder(new LineBorder(Color.black, 1, false));
    p1.add(l1,BorderLayout.CENTER);
    l1.updateUI();

    }

    }

    }}
      

  2.   

    //现在能打开图片了,可是想再通过按钮更改图片作不到,怎么解决啊?我的程序如下:
    //这属于你写程序的问题,你应该在构造函数中或者creatGUI()中构造完JLabel
    //你在listener中每次都构造了一个新JLabel,而你第一次构造的那个JLabel还是显示的原来的图片
    //这样改
    //将开头处的private JLabel l1=null;改为
    private JLabel l1=new JLabel();//将open类中中l1=new JLabel(image);改为
    l1.setIcon(image);
      

  3.   

    谢谢uloveu(自己爱自己) 了.给分:)20分不会嫌少吧?