【问题标题】:Java inheritance, using super()Java继承,使用super()
【发布时间】:2014-02-08 22:47:48
【问题描述】:

这部分作业是展示从 java 库的继承。我必须创建一个 java 类,在调用时将颜色标签设置为适当的背景:例如,如果主说 JLabel colorfulLabel = new JLabel(Color.Blue); 它会创建一个蓝色背景的标签。

这是我当前的彩色标签类代码:

import javax.swing.*;
import java.awt.*;
public class colorfulLabel extends JLabel{
    /*constructor uses one color parameter to represent background color
      creates label using background color
      calls parent constructor using super()
      private Color color;*/
    public colorfulLabel(Color color){
        super(color);

        JLabel l1 = new JLabel();
        setBackground(color);
    }
}

ps:是的,这是一小段代码,但我在 GUI 方面遇到了极大的困难,更不用说实现继承了。

尝试调用父构造函数时出现错误。

【问题讨论】:

  • 按照约定,所有类名都以大写字符开头。尽快尝试坚持,它会让你以后的 Java 生活更轻松。
  • "I get an error when trying to invoke the parent constructor." -- 当您询问一个错误消息时,请始终发布整个错误消息。请不要让我们猜测。

标签: java swing inheritance constructor


【解决方案1】:
  1. 您正在尝试调用一个不存在的构造函数super(color)。请检查JLabel API 以查看哪些构造函数是合法的。你为什么要调用这个构造函数呢?
  2. 在您的 JLabel 扩展类中创建另一个 JLabel 几乎没有意义。
  3. 如果您打算查看背景颜色,您可能需要在构造函数中使对象不透明。

最好是传入文本,或者通过添加 Color 参数来模仿其他有效的 JLabel 构造函数:

public class ColorLabel extends JLabel {
  public ColorLabel(String text, Color bg) {
    super(text); // **this** super makes sense
    setBackground(bg);
    setOpaque(true);
  }

  // + overloads for other constructors that accept Icon or text and Icon, or 
  // text, Icon and position,....
}

【讨论】:

  • 就像我说的,我对 Java 中的 GUI 感到很恐惧。它处于试错阶段,但这部分作业如下所述:一个名为 ColorfulLabel 的类 - 扩展 JLabel。构造函数将使用一个颜色参数来表示标签的背景颜色。构造函数将创建一个具有特定背景颜色的 jlabel 对象。不要忘记使用 Super() 调用父构造函数,然后设置 bg 颜色。例如:彩色标签 blueLabel = 新的彩色标签(Color.Blue);
  • @user3288392:这不是一个特定于 GUI 的问题。这实际上只是一个“学习阅读 Java API”类型的问题。
【解决方案2】:

试试这个:

// by convention class names should start with an uppercase character
public colorfulLabel(Color color) { character
    super(); // it's not necessary in this case, it's implicit 
    setBackground(color);
}

JLabel 没有接收Color 作为参数的构造函数,这就是导致错误的原因。另请注意,您实际上并不需要为此扩展一个类,您没有添加额外的属性或功能,只需通过 JLabel 类型的实例调用 setBackground() 即可满足您的所有需求。

【讨论】:

  • 我这样做只是因为指定的那部分作业......或者我假设......它说:一个名为 ColorfulLabel 的类 - 扩展 JLabel。构造函数将使用一个颜色参数来表示标签的背景颜色。构造函数将创建一个具有特定背景颜色的 jlabel 对象。不要忘记使用 Super() 调用父构造函数,然后设置 bg 颜色。例如:ColorfulLabel blueLabel = new ColorfulLabel(Color.Blue)
  • @user3288392 好的,这就是我上面的回答所做的。查看编辑
猜你喜欢
  • 1970-01-01
  • 2018-05-30
  • 2020-05-15
  • 1970-01-01
  • 2016-02-11
  • 2016-03-12
  • 2016-06-24
  • 2022-01-20
  • 1970-01-01
相关资源
最近更新 更多