gpt4 book ai didi

java - 从子类中删除 JLabel

转载 作者:太空宇宙 更新时间:2023-11-04 06:13:56 25 4
gpt4 key购买 nike

假设我有这门课:

public class ExitView extends JPanel {

private static final long serialVersionUID = 1L;

public ExitView() {
JLabel title = new JLabel("Exit?");
title.setFont(new Font("Ariel", Font.PLAIN, 44));
this.add(title);
}
}

这也是:

public class EndView extends ExitView {

public ExitView() {
this.remove(title);
}
}

此代码已被彻底删除,但在我的代码中,这并没有删除 EndView 中的 JLabel。我只能 title.setText("") 但这并没有真正摆脱它。谁能解释一下为什么不删除标签?谢谢。

最佳答案

您正在基类构造函数中创建一个标签,并将其直接添加到 JPanel。但在后面的检查中,您不使用对创建的 JLabel 的引用,而是使用其他引用。 b/c 变量超出范围,可能很难再次引用它。修复方法正如 Paco 提到的那样。将变量移出构造函数范围并进行全局设置。

public class ExitView extends JPanel {

private static final long serialVersionUID = 1L;

public ExitView() {
JLabel title = new JLabel("Exit?"); // <- here you create a JLabel
// in that scope where is the
// reference for later use??
title.setFont(new Font("Ariel", Font.PLAIN, 44));
this.add(title);
}
}

public class EndView extends ExitView {

public ExitView() {
this.remove(title); <- // the reference you create here doesn't
// equals the JLabel created earlier
}
}

关于java - 从子类中删除 JLabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28346397/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com