Java Swing:如何将 JLabel 的文本绑定到 JTable 的选定行中的列?

发布于 2024-08-12 01:40:37 字数 227 浏览 3 评论 0原文

我正在使用 Netbeans,并试图找到一种让 IDE 为我自动生成代码的方法。我记得之前将 JLabel 的文本绑定到 JTable 的选定行中的列,但在这种情况下,JTable 的值来自实体管理器,而且非常简单。我想知道即使 JTable 没有绑定到数据库是否有办法做到这一点。

另外,还有什么办法可以做到这一点呢?我正在考虑实现一个 ListSelectionListener,每当生成事件时,只需更新标签的文本即可。

I am using Netbeans and am trying to find a way for the IDE to auto-generate the code for me. I remember binding a JLabel's text to a column in the selected row of the JTable before, but in that case, the JTable's values were from an entity manager, and it was very easy. I was wondering if there is a way to do it even if the JTable is not tied to a database.

Also, how else could one do it? I was thinking of implementing a ListSelectionListener, and whenever an event got generated, just update the text of the label.

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

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

发布评论

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

评论(1

终陌 2024-08-19 01:40:37

我认为你的第二个解决方案是最好的方法,像这样:

public class LabelSyncer implements ListSelectionListener {

    private JLabel toSync;
    private int columnIndex;

    public LabelSyncer(JLabel toSync, int columnIndex) {

    }

    public void valueChanged(ListSelectionEvent e) {
        JTable table = (JTable) e.getSource();
        int row = table.getSelectedRow();
        toSync.setText(table.getModel().getValueAt(row, columnIndex).toString());
    }
}

然后

table.getSelectionModel().addListSelectionListener(new LabelSyncer(label, columnIndex));

像这样。可能是一个更通用的解决方案,但这应该可行。

I think your second solution is best way to do it, something like this:

public class LabelSyncer implements ListSelectionListener {

    private JLabel toSync;
    private int columnIndex;

    public LabelSyncer(JLabel toSync, int columnIndex) {

    }

    public void valueChanged(ListSelectionEvent e) {
        JTable table = (JTable) e.getSource();
        int row = table.getSelectedRow();
        toSync.setText(table.getModel().getValueAt(row, columnIndex).toString());
    }
}

and then

table.getSelectionModel().addListSelectionListener(new LabelSyncer(label, columnIndex));

Something like this. Probably a more generic solution, but this should work.

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