简体   繁体   English

在JLabel上的ImageIcon周围创建边框,而不是在Jlabel周围创建边框

[英]Creating border around ImageIcon on a JLabel, not around the Jlabel

替代文字

I have problem with creating border for an icon in JLabel. 我在JLabel中为图标创建边框时遇到问题。 I have JPanel in which I set it into GridLayout. 我在JPanel中将其设置为GridLayout。 I added Jlabel on the JPanel. 我在JPanel上添加了Jlabel。 The size of the JLabel were according to the size of the icon. JLabel的大小取决于图标的大小。 However when I tried to set the border on the icon, it created border according to the size of the grid and not the size of the icon inside the grid. 但是,当我尝试在图标上设置边框时,它根据网格的大小而不是网格内图标的大小创建了边框。

How can I create a border around the image not on the size of the grid? 如何在图像周围创建边框而不是网格大小?

Why the border followed the size of the grid and not the size of the imageIcon? 为什么边框跟随网格的大小而不是imageIcon的大小?

JPanel panel= new JPanel(new GridLayout(ROWS,COLS,2,2)); 
panel.setsize(600,600);

....
JLabel = new JLabel(icon, JLabel.LEFT);
label.setVerticalAlignment(SwingConstants.TOP);
...
label.setborder(BorderFactory.createLineBorder(Color.RED,5));
panel.add(label);

I solved the problem. 我解决了问题。 Thanks to this site http://forums.oracle.com/forums/thread.jspa?messageID=5785467 感谢这个网站http://forums.oracle.com/forums/thread.jspa?messageID=5785467。

Image image = icon.getImage().getScaledInstance(widthX,heightY, image.SCALE_SMOOTH);            
icon.setImage(image);   

int borderWidth = 1;
int spaceAroundIcon = 0;
Color borderColor = Color.BLUE;

BufferedImage bi = new BufferedImage(icon.getIconWidth() + (2 * borderWidth + 2 * spaceAroundIcon),icon.getIconHeight() + (2 * borderWidth + 2 * spaceAroundIcon), BufferedImage.TYPE_INT_ARGB);

Graphics2D g = bi.createGraphics();
g.setColor(borderColor);
g.drawImage(icon.getImage(), borderWidth + spaceAroundIcon, borderWidth + spaceAroundIcon, null);

BasicStroke stroke = new BasicStroke(5); //5 pixels wide (thickness of the border)
g.setStroke(stroke);

g.drawRect(0, 0, bi.getWidth() - 1, bi.getHeight() - 1);
g.dispose();

label = new JLabel(new ImageIcon(bi), JLabel.LEFT);
label.setVerticalAlignment(SwingConstants.TOP);      

panel.add(label);

使用FlowLayout将标签添加到面板中,然后将面板添加到GridLayout面板中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM