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 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误