问题描述
我想创建一个带有复选框和一个或两个可选文本字段的单元格。
I like to create a cell with a checkbox and one or two optional textfields.
如果单击复选框,文本字段将变为可见。我试图制作一张ASCII图片,它应该是这样的:
If I click on the checkbox the textfields get visible. I tried to make an ASCII picture how it should look like:
[ ]
[X] [some string]
[X] [value1] [value2]
我知道如何创建自定义渲染器但我不知道如何返回多个元素。如果我有一个复选框的渲染器我只返回JCheckBox:
I know how to create a custom renderer but I am not sure how to return multiple elements. If I have a renderer for a checkbox I return only the JCheckBox:
class BooleanRenderer extends JCheckBox implements TableCellRenderer, UIResource
{
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
// doing some stuff...
return this;
}
}
推荐答案
@ Thomas et al。对于区分模型和视图是正确的。您的模型包含布尔状态和一些相应的文本;您的视图是可以切换的 JCheckBox
和可以更改的文本。你需要一个渲染器来显示模型的当前状态和一个允许更改状态的编辑器。
@Thomas et al. are correct about distinguishing between the model and the view. Your model includes a boolean state and some corresponding text; your view is a JCheckBox
that can be toggled and text that can be changed. You'll need both a renderer to display the current state of the model and an editor to allow changes to the state.
在这个,类值
包含所选状态和基础数据,一个 Double
值。实现 TableModel
的 DataModel
管理列表< Value>
。请注意,编辑器和渲染器都使用公共 java.text.DecimalFormat
。相关课程可能很有用。
In this example, the class Value
holds the selected state and the underlying data, a Double
value. The DataModel
, which implements TableModel
, manages a List<Value>
. Note that both the editor and renderer use a common java.text.DecimalFormat
. The related class java.text.MessageFormat
may be useful in composing your check box's text.
这篇关于JTable在一个单元格中包含多个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!