AlstonWilliams 2015-03-18 08:16 采纳率: 0%
浏览 9197

java中怎样设置图片的大小

import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
public class ButtonFrame extends JFrame
{
private JButton plainJButton;//button with just text
private JButton fancyJButton;//button with icons

//ButtonFrame  adds  JButtons  to  JFrame
public  ButtonFrame()
{
    super("Testing  Buttons");
    setLayout(new  FlowLayout());//set  frame  layout

    plainJButton=new JButton("Plain  Button");//button  with   text
    add(plainJButton);//add  plainJButton  to  JFrame

    Icon  bug1=new  ImageIcon(getClass().getResource("t013971ecacef25bf25.jpg"));
    Icon  bug2=new  ImageIcon(getClass().getResource("t019bbb4841bb28712f.jpg"));
    fancyJButton=new  JButton("Fancy  Button",bug1);//set  image
    fancyJButton.setRolloverIcon(bug2);
    add(fancyJButton);//add  fancyJButton  to  JFrame

    //create  new  ButtonHandler  for  button  event  handling
    ButtonHandler  handler=new ButtonHandler();
    fancyJButton.addActionListener(handler);
    plainJButton.addActionListener(handler);
}//end  buttonFrame  constructor

//inner  class  for  button  event  handling
private  class  ButtonHandler  implements  ActionListener
{
    //handle  button  event
    public  void  actionPerformed(ActionEvent  event)
    {
        JOptionPane.showMessageDialog(ButtonFrame.this, String.format("You  pressed:%s", event.getActionCommand()));

    }//end method  actionPerformed
}//end  private  inner  class  buttonHandler

}//end class ButtonFrame
根据书上的代码加入了图片,但是图片总是太大,不满足我的需求,请问怎样或者说用什么函数才能调整图片的大小呢?请大神指教,帮我修改一下上面的代码

  • 写回答

1条回答

  • weixin_44483663 2019-01-21 12:45
    关注

    利用int 声明height,width,并赋予初值(你要设置的图片大小)。然后通过下述代码进行:
    URL resource=this.getClass().getResource("img5.JPG");//this是在本类的意思,即这张图片已经复制在本类了,你可以根据你的需求进行写入路径
    ImageIcon icon=new ImageIcon(resource);
    icon.setImage(icon.getImage().getScaledInstance(width, height,Image.SCALE_DEFAULT ));
    label.setIcon(icon)//label是你创建的标签实例对象

    评论

报告相同问题?

悬赏问题

  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献