问题描述
在一个 JTable
单元中是否可以有多个对象,就像这样,我在第一行的每个单元格中都有两个 JLabels
?
Is it possible to have multiple objects inside one JTable
cell looking like this where I have two JLabels
in each cell on the first row?
在此示例中,我遇到的问题是我无法将任何侦听器添加到任何 JLabels
( Icons
).我的猜测是我需要更改 CellRenderer
以外的其他内容?
The problem I am having in this example is that I can't add any listeners to any JLabels
(Icons
). My guess is that I need to change something else then the CellRenderer
?
public class JTableIcons extends JPanel {
private DefaultTableModel model;
private JTable table;
public JTableIcons() {
initModel();
initTable();
this.setLayout(new BorderLayout());
this.add(table, BorderLayout.CENTER);
}
class MyRenderer implements TableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
JPanel panel = new JPanel();
if (row == 0) {
JLabel lblCol = new JLabel("Column:" + column);
Icon icon = UIManager.getIcon("OptionPane.errorIcon");
JLabel lblIcon = new JLabel();
lblIcon.setIcon(icon);
panel.add(lblIcon);
panel.add(lblCol);
} else {
JLabel lbl = new JLabel("(" + row + "," + column + ")");
panel.add(lbl);
}
panel.setOpaque(false);
return panel;
}
}
private void initTable() {
table = new JTable(model);
table.setDefaultRenderer(Object.class, new MyRenderer());
table.setShowGrid(true);
table.setGridColor(Color.gray);
table.setRowHeight(80);
}
private void initModel() {
String[] cols = { "", "", "" };
Object[][] rows = { { "", "", "" }, { "", "", "" }, { "", "", "" }, { "", "", "" } };
model = new DefaultTableModel(rows, cols);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new JTableIcons());
f.setVisible(true);
f.setSize(new Dimension(500, 350));
f.setLocationRelativeTo(null);
}
});
}
}
推荐答案
不要使用两个组件,只有一个可以使用.此渲染器://stackoverflow.com/a/2834484/230513>示例实现了 Icon
接口,以利用文本和图标的灵活相对位置.必要时,将多个组件添加到合适的轻量级 Container
中,例如 JPanel
.
Don't use two components, when one will do. The renderer in this example implements the Icon
interface to leverage the flexible relative positioning of the text and icon. When necessary, add multiple components to a suitable lightweight Container
, e.g. JPanel
.
对于交互性,请使用自定义 TableCellEditor
.此示例管理面板中的单选按钮.
For interactivity, use a custom TableCellEditor
. This example manages radio buttons in a panel.
这篇关于单个JTable单元中的多个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!