Creating border around ImageIcon on a JLabel, not around the Jlabel
I have problem with creating border for an icon in JLabel. I have JPanel in which I set it into GridLayout. I added Jlabel on the JPanel. The size of the JLabel were according to the size of the icon. However when I tried to set the border on the icon, it created border according t开发者_Python百科o 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?
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
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);
Add your label to a panel with FlowLayout, and add the panel to the GridLayout panel.
精彩评论