我的这个 Java程序怎么改,才能使得按钮具有缩小图片的功能
import javax.swing.*;
public class lianxi13 extends JFrame{
JPanel n;
JLabel n1;
JLabel n2;
ImageIcon n3;
JButton n4;
public lianxi13(){
super("fds");
setSize(286,168);
this.setVisible(true);
n=new JPanel();
n.setLayout(new BorderLayout());
n3=new ImageIcon("D://8.jpg");
n1=new JLabel(n3);
n2=new JLabel("带图标的组件");
n.add(n1,BorderLayout.WEST);
n.add(n2,BorderLayout.EAST);
n4=new JButton("缩小");
n.add(n4);
this.add(n);
}
public static void main(String[] args) {
new lianxi13();
}
} 展开
public lianxi13(){
super("fds");
setSize(286,168);
n=new JPanel();
n.setLayout(new BorderLayout());
n3=new ImageIcon("D://8.jpg");
Image scaleImg=n3.getImage().getScaledInstance(50, 50, Image.SCALE_AREA_AVERAGING);
ImageIcon scaleIcon=new ImageIcon(scaleImg);
n1=new JLabel(scaleIcon);
n2=new JLabel("带图标的组件");
n.add(n1,BorderLayout.WEST);
n.add(n2,BorderLayout.EAST);
n4=new JButton("缩小");
n.add(n4);
this.add(n);
this.setVisible(true);
}
public static void main(String[] args) {
new lianxi13();
}
n4.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
BufferedImage bi = new BufferedImage((int)(n3.getIconWidth()*0.8),(int)(n3.getIconHeight()*0.8),BufferedImage.TYPE_3BYTE_BGR);
bi.getGraphics().drawImage(n3.getImage(), 0, 0, (int)(n3.getIconWidth()*0.8), (int)(n3.getIconHeight()*0.8),null);
bi.getGraphics().dispose();
n3.setImage(bi);
repaint();
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
把这个代码加上试试。加在n4=new JButton("缩小");的后面
2014-10-30 · 知道合伙人软件行家