程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长


+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

Icon,Imagelcon(图标)

发布于2021-10-05 12:20     阅读(150)     评论(0)     点赞(24)     收藏(3)


1.文字图标

  1. package com.jia.lesson;
  2. import javax.swing.*;
  3. import java.awt.*;
  4. public class IconDemo extends JFrame implements Icon {
  5. private int width;
  6. private int height;
  7. public IconDemo() {
  8. }
  9. public IconDemo(int width, int height) {
  10. this.width = width;
  11. this.height = height;
  12. }
  13. public void init() {
  14. IconDemo iconDemo = new IconDemo(15,15);
  15. //图标放在标签,也可以放在按钮上
  16. JLabel label = new JLabel("icontest", iconDemo, SwingConstants.CENTER);
  17. Container container =this.getContentPane();
  18. container.add(label);
  19. this.setVisible(true);
  20. this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
  21. }
  22. @Override
  23. public void paintIcon(Component c, Graphics g, int x, int y) {
  24. g.fillOval(x, y, width, height);
  25. }
  26. @Override
  27. public int getIconWidth() {
  28. return this.width;
  29. }
  30. @Override
  31. public int getIconHeight() {
  32. return this.height;
  33. }
  34. public static void main(String[] args) {
  35. new IconDemo().init();
  36. }
  37. }

2.图片图标

注意问题:

图片添加后显示空指针,此时重启idea就好了

  1. package com.jia.lesson;
  2. import javax.swing.*;
  3. import java.awt.*;
  4. import java.net.URL;
  5. public class ImageIconDemo extends JFrame{
  6. //构造器
  7. public ImageIconDemo() {
  8. //获取图片的地址,图片和代码在同级目录
  9. JLabel label = new JLabel("ImageIcon");
  10. URL url=ImageIconDemo.class.getResource("dsBuffer.jpg");
  11. ImageIcon imageIcon = new ImageIcon(url);
  12. label.setIcon(imageIcon);
  13. label.setHorizontalAlignment(SwingConstants.CENTER);
  14. Container container =getContentPane();
  15. container.add(label);
  16. setVisible(true);
  17. setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
  18. }
  19. //主程序
  20. public static void main(String[] args) {
  21. new ImageIconDemo();
  22. }
  23. }

原文链接:https://blog.csdn.net/qq_49759937/article/details/120602658



所属网站分类: 技术文章 > 博客

作者:javajava我最强

链接:http://www.javaheidong.com/blog/article/297025/3b8c5875c143db1b9c71/

来源:java黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

24 0
收藏该文
已收藏

评论内容:(最多支持255个字符)