【问题标题】:How to add multiple layers onto JPanel如何在 JPanel 上添加多个图层
【发布时间】:2012-06-26 11:26:42
【问题描述】:

我需要一些有关 Java Swing 组件及其功能的帮助。我需要将JPanel 添加到JFrame 并在其上绘制Ellipse2D。在Ellipse2D 上,我想添加另一个元素,在我的情况下它是一张图片(现在我使用ImageIcon,可能是错误的)。如何实现添加Ellipse2D和面板上的图片,如我所附的图片所示?

我需要分离图像的原因是因为我有时需要更改椭圆的填充颜色。

感谢您的帮助。

【问题讨论】:

    标签: java swing paintcomponent


    【解决方案1】:

    您需要创建一个自定义的JPanel 实现并覆盖paintComponent 方法。

    在里面,你只需:

    public void paintComponent(Graphics g) {
    
        super.paintComponent(g);
    
        // Draw ellipse here
    
        // Draw your image here. It will be drawn on top of the ellipse.
    
    }
    

    这样就可以在CustomPanel类中保存椭圆填充颜色,改变颜色后调用repaint()方法即可。

    【讨论】:

    • 还需要设置preferredSize或覆盖getPreferredSize(),以便组件布局正确
    • 你将如何绘制图像? Graphics2D 提供了 drawImage() 方法,在我看来有点复杂,因为需要设置一些观察者。
    • 只需将观察者设置为空:stackoverflow.com/questions/1684422/…
    • 而是将观察者设置为this
    【解决方案2】:
    • Oracles 教程How to Decorate Components with the JLayer Class

    • 中可以很好地描述您的想法(包括代码示例)
    • notice JLayer 仅适用于 Java7,但它基于(适用于 Java6)JXLayer

    • 您也可以使用(我正在使用)GlassPane,与 Swing GUI 的输出相同/类似

    编辑

    使用OverlayLayout 非常简单和漂亮的输出,可以用Graphics 覆盖J/Component(s) 例如a few examples

    【讨论】:

      【解决方案3】:

      将两张图片作为图片图标

      ImageIcon car=new ImageIcon("image path");
      ImageIcon elipse=new ImageIcon("image path");
      

      将这两个图像图标添加两个标签

      JLabel carLabel=new JLabel(car);
      JLabel ellipseLabel=new JLabel(ellipse);
      

      并设置椭圆和汽车的位置

      carLabel.setBounds(0,0,50,50);
      ellipseLabel.setBounds(10,10,50,50);
      

      【讨论】:

        猜你喜欢
        • 2012-06-17
        • 1970-01-01
        • 2013-06-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-16
        • 1970-01-01
        • 2021-05-18
        相关资源
        最近更新 更多