我在JLabel中为图标创建边框时遇到问题。我有JPanel,我将其设置为GridLayout。我在JPanel上添加了Jlabel。 JLabel的大小取决于图标的大小。但是,当我尝试在图标上设置边框时,它会根据网格的大小创建边框,而不是网格内图标的大小。
如何围绕图像创建边框而不是网格尺寸?
为什么边框遵循网格的大小而不是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);
答案 0 :(得分:1)
我解决了这个问题。感谢此网站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);
答案 1 :(得分:-2)
使用FlowLayout将标签添加到面板,然后将面板添加到GridLayout面板。