如何创建特定的类构造函数

发布于 2024-11-12 17:08:23 字数 662 浏览 6 评论 0原文

我有一个非常简单的 Java JTable 问题。 我创建这个类是为了让我的应用程序的其余部分变得更容易。我在运行时收到错误。我知道这些错误意味着什么,但不知道还能尝试什么。

您将在代码中看到我想要完成的任务:

我的班级:

import javax.swing.*;
public class CPTable extends JScrollPane
{
    private JTable table;
    CPTable(Object [] headers, Object [][] data)
    {
        table = new JTable(data, headers);
        this = new JScrollPane(table);//The line I can't figure out.
    }
}

我的错误:(一个明显的错误)

cannot assign a value to final variable this
    this = new JScrollPane(table);

incompatible types
found   : javax.swing.JScrollPane
required: CPTable

I have a very simple Java JTable question.
I am creating this class to make things easier in the rest of my application. I receive an error when running it. I know what the errors mean, but have no idea what else to try.

You'll see in the code what I am trying to accomplish:

My Class:

import javax.swing.*;
public class CPTable extends JScrollPane
{
    private JTable table;
    CPTable(Object [] headers, Object [][] data)
    {
        table = new JTable(data, headers);
        this = new JScrollPane(table);//The line I can't figure out.
    }
}

My errors: (an obvious one)

cannot assign a value to final variable this
    this = new JScrollPane(table);

and

incompatible types
found   : javax.swing.JScrollPane
required: CPTable

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不知在何时 2024-11-19 17:08:23

试试这个:

private CPTable(JTable table) {
    super(table);
    this.table = table;
}

public CPTable(Object[] headers, Object[][] data) {
    this(new JTable(data, headers));
}

您不能重新分配 this,但您可以使用 super (它必须是构造函数中的第一个语句)调用正确的超类构造函数。

this 语句称为“构造函数委托”——它链接到另一个构造函数,以便您可以将表传递给超类并将其分配给您的 领域。

Try this:

private CPTable(JTable table) {
    super(table);
    this.table = table;
}

public CPTable(Object[] headers, Object[][] data) {
    this(new JTable(data, headers));
}

You cannot reassign this, but you can cause the correct superclass constructor to be called by using super (which must be the first statement in your constructor).

The this statement is called "constructor delegation"---it chains through to the other constructor so that you can pass the table to the superclass as well as assign it to your table field.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文