Java 可编辑 JTable 教程

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/85046/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 08:07:28  来源:igfitidea点击:

Editable JTable Tutorial

javaswingjtable

提问by Arthur Thomas

Are there any good books or website that go over creating a JTable? I want to make one column editable. I would like to actually put a inherited JCheckBoxcomponent (that we created here) into one of the table columns instead of just having the table put JCheckBoxin based on it being an editable booleanfield.

有没有什么好书或网站可以创建一个JTable?我想让一列可编辑。我想实际上将一个继承的JCheckBox组件(我们在此处创建)放入其中一个表列中,而不是仅仅JCheckBox根据它是一个可编辑的boolean字段将表放入。

I have the JFC Swing Tutorial Second Editionbook but I just would like to know if there are other examples I could look at and learn how to deal with the tables better. The book seems to just take the java 'trail' online and put it in the book.

我有JFC Swing 教程第二版,但我只是想知道是否还有其他示例可以查看并学习如何更好地处理表格。这本书似乎只是将java'trail'放到网上并放在书中。

I am re-reading the stuff though, just curious if anyone has found something that might help out more.

不过,我正在重新阅读这些内容,只是好奇是否有人找到了可能有帮助的内容。

采纳答案by morsch

To make a column editable you have to override the isCellEditablemethod in the TableModel. Creating a TableModelis fairly easy if you inherit AbstractTableModeland I'd recommend it for all but the most simple JTables.

为了使一列可编辑你必须重载isCellEditable的方法TableModelTableModel如果您继承AbstractTableModel,创建 a相当容易,我建议除最简单的JTables 之外的所有对象都使用它。

However, adapting the TableModelis only part of what you need to do. To actually get a custom component in the JTable, you need to set a custom cell renderer. To use an interactive custom component, you need to set a custom cell editor. In some cases, it's enough to use slightly modificated versions of the default classes for this.

然而,适应TableModel只是你需要做的一部分。要在 中实际获得自定义组件JTable,您需要设置自定义单元格渲染器。要使用交互式自定义组件,您需要设置自定义单元格编辑器。在某些情况下,为此使用默认类的稍微修改版本就足够了。

Editors

编辑

If you already have got a custom component is easily done using delegation: Create a new class implementing TableCellEditor, and return a newinstance of the component in the getCellEditorComponentmethod. The paramaters to this method include the current value as well as the cell coordinates, a link back to the table and wether or not the cell is selected.

如果您已经有一个自定义组件,可以使用委托轻松完成:创建一个实现 的新类TableCellEditor,并在方法中返回该组件的实例getCellEditorComponent。此方法的参数包括当前值以及单元格坐标、返回表格的链接以及单元格是否被选中。

The TableCellEditoralso has a method that is called when the user commits a change to the cell contents (where you can validate user input and adjust the model) or cancels an edit. Be sure to call the stopEditing()method on your editor if you ever programmatically abort editing, otherwise the editor component will remain on screen -- this once took me like 2 hours to debug.

TableCellEditor还有一个方法,当用户提交对单元格内容的更改(您可以在其中验证用户输入并调整模型)或取消编辑时调用该方法。stopEditing()如果您曾经以编程方式中止编辑,请务必在编辑器上调用该方法,否则编辑器组件将保留在屏幕上——这曾经花了我 2 个小时来调试。

Note that within a JTableeditors and onlyeditors receive events! Displaying a button can be done using a renderer. But to get a functioning button, you need to implement an editor with the correct EventListenersregistered. Registering a listener on a renderer does nothing.

请注意,在JTable编辑器中,只有编辑器才能接收事件!可以使用渲染器来显示按钮。但是要获得一个功能正常的按钮,您需要实现一个具有正确EventListeners注册的编辑器。在渲染器上注册监听器什么都不做。

Renderers

渲染器

Implementing a renderer is not strictly necessary for what you describe in your question, but you typically end up doing it anyway, if only for minor modifications. Renderers, unlike editors, are speed critical. The getTableCellRendererComponentof a renderer is called once for every cell in the table!The component returned by a renderer is only used to paint the cell, not for interaction, and thus can be "reused" for the next cell. In other words, you should adjust the component (e.g. using setText(...)or setFont(...)if it is a TextComponent) in the renderer, you should notinstantiate a new one -- that's an easy way to cripple the performance.

对于您在问题中描述的内容,实现渲染器并不是绝对必要的,但您通常最终还是会这样做,即使只是进行微小的修改。与编辑器不同,渲染器对速度至关重要。getTableCellRendererComponent渲染器被称为一次对表中的每一个细胞!渲染器返回的组件仅用于绘制单元格,而不用于交互,因此可以“重用”用于下一个单元格。换句话说,你应该调整组件(例如,使用setText(...)或者setFont(...)如果它是一个TextComponent)的渲染,你应该实例化一个新的-这是削弱性能的简单方法。

Caveats

注意事项

Note that for renderers and editors to work, you need to tell the JTablewhen to use a certain renderer/editor. There are basically two ways to do this. You can set the default cell renderer/editor for a certain typeusing the respective JTablemethods. For this way to work, your TableModelneeds to return exactly this type in the getColumnClass(...)method! The default table model will notdo this for you, it always returns Object.class. I'm sure that one has stumped a lot of people.

请注意,要使渲染器和编辑器工作,您需要告诉JTable何时使用某个渲染器/编辑器。基本上有两种方法可以做到这一点。您可以使用相应的方法为特定类型设置默认单元格渲染器/编辑器JTable。要以这种方式工作,您TableModel需要在getColumnClass(...)方法中准确返回这种类型!默认表模型不会为您执行此操作,它始终返回Object.class. 我敢肯定,这已经难倒了很多人。

The other way to set the editor/renderer is by explicitly setting it on the column itself, that is, by getting the TableColumnvia the getTableColumn(...)method of the JTable. This is a lot more elaborate, however, it's also the only way to have two different renderers/editors for a single class. E.g. your model might have two columns of class String which are rendered in entirely different ways, maybe once using a JLabel/DefaultRendererand the other using a JButtonto access a more elaborate editor.

另一种方法来设置编辑器/渲染是显式地设置该列本身,就是通过获得TableColumn通过getTableColumn(...)的方法JTable。这要复杂得多,但是,它也是为单个类拥有两个不同渲染器/编辑器的唯一方法。例如,您的模型可能有两列 String 类,它们以完全不同的方式呈现,可能一次使用 a JLabel/DefaultRenderer,另一列使用 aJButton来访问更复杂的编辑器。

JTablewith its custom renderers and editors is extremelyversatile, but it is also a lot to take in, and there are a lot of things to do wrong. Good luck!

JTable它的自定义渲染器和编辑器非常通用,但它也有很多东西需要做,并且有很多事情要做错。祝你好运!

How to Use Tablesin The Swing Tutorialis mandatory reading for anyone customising JTables. In particular, read and reread Concepts: Editors and Renderersbecause it typically takes a while for it to "click". The examples on custom renderers and editors are also very worthwhile.

如何使用表的秋千教程是任何定制JTable中强制阅读。特别是,阅读和重读概念:编辑器和渲染器,因为它通常需要一段时间才能“点击”。关于自定义渲染器和编辑器的示例也非常值得。

回答by Arthur Thomas

The class you want to look into extending to create your own behavior is DefaultTableModel. That will allow you to define your own behavior. A decent tutorial can be found on sun's site.

您想要扩展以创建您自己的行为的类是 DefaultTableModel。这将允许您定义自己的行为。可以在 sun 的网站上找到一个不错的教程。

回答by James A Wilson

This tutorial from the java lobbyis easy to follow. The online Swing trail for JTablethat you reference indicates that it has been updated. Did you scan through the whole thing for possible better (isn't newer always better) information?

这个来自java 大厅的教程很容易理解。您引用的JTable的在线Swing 跟踪表明它已更新。您是否浏览了整个内容以获得更好的(不是新的总是更好的)信息吗?

回答by Richard Walton

Some useful classes are:

一些有用的类是:

Package javax.swing.table:

Package javax.swing.table

TableModel- Interface for a tablemodelAbstractTableModel- Nice class to extend for creating your own table with custom data structures DefaultTableModel- Default table model which can deal with arrays[]and Vectors

TableModel- 接口tablemodelAbstractTableModel- 用于扩展创建您自己的具有自定义数据结构的表的不错类 DefaultTableModel- 默认表模型可以处理arrays[]Vectors

To disable editing on any cell you need to override the isCellEditable(int row, int col)method

要禁用对任何单元格的编辑,您需要覆盖该isCellEditable(int row, int col)方法

回答by ShawnD

If you are trying to use a simple JTablewith 1 column editable and you know the column location you could always use default table model and overload the isCellEditablecall.

如果您尝试使用JTable带有 1 列可编辑的简单表,并且您知道列位置,则可以始终使用默认表模型并重载isCellEditable调用。

something like this :

像这样:

myTable.setModel(new DefaultTableModel(){
@Override
public boolean isCellEditable(int row, int column) {
    if (column == x) {
        return true;
    } else
        return false;
}
});

And for the check box create a renderer class

并为复选框创建一个渲染器类

MyCheckBoxRenderer extends JCheckBox implements TableCellRenderer

回答by Maxwell Cheng

in your table Model, you should override "isCellEditable" and "setValueAt" functions, like below.
Column 4 is the column for editable cells.
Then when you double click the cell and type something,
setValueAt() will be called and save the value to the tableModel's DO,field col4.

在您的表模型中,您应该覆盖“isCellEditable”和“setValueAt”函数,如下所示。
第 4 列是可编辑单元格的列。
然后,当您双击单元格并键入内容时,
将调用 setValueAt() 并将值保存到 tableModel 的 DO,字段 col4。

public ArrayList<XXXDO> tbmData = new ArrayList<XXXDO>(); //arraylist for data in table

@Override
public boolean isCellEditable(int row, int col) {
    if (col == 4) {
        return true;
    } else {
        return false;
    }
}

@Override
public void setValueAt(Object value, int row, int col) {
    if ((row >= 0) && (row < this.tbmData.size()) && (col >= 0) && (col < this.colNm.length)) {
        if (col == 4) {
            tbmData.get(row).col4= (String) value;
        }
        fireTableCellUpdated(row, col);
    } else {
    }
}