我已经创建了一个矩形,现在我必须将一个 JLabel 放入其中。那么我怎样才能将 JLabel 放在矩形内。
代码在这里:-
public class ColoredRect extends JPanel
{
private double x, y, width, height;
public ColoredRect(double x,double y)
{
this.x = x;
this.y = y;
width = 100;
height =40;
rect = new Rectangle2D.Double(this.x , this.y,width,height);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.cyan);
g2.fill(rect);
}
}
请给我一些实现这个的想法。
提前致谢。
最佳答案
有很多方法可以达到类似的结果。但是,您不应该真正使用您的方法。使用paintComponent就像用它来真正绘画一样,不要在上面放置swing组件,我相信它的做法更清晰。
您可以使用 JLayeredPane,将标签放置在一层中,将绘图放置在另一层上。
我会考虑在标签中使用边框 - 也许在这种情况下您根本不需要矩形。 请参阅此处的示例:Labels with Borders
希望这有帮助
关于java - 如何将 JLabel 放在矩形内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11239225/