java jtable添加jbutton不显示_将Jbutton添加到JTable中

小编典典

将按钮添加到 JTable

JTable table = new JTable(new JTableModel());

JScrollPane scrollPane = new JScrollPane(table);

table.setFillsViewportHeight(true);

TableCellRenderer buttonRenderer = new JTableButtonRenderer();

table.getColumn("Button1").setCellRenderer(buttonRenderer);

table.getColumn("Button2").setCellRenderer(buttonRenderer);

Sample JTableModel,这是管理列和行,设置组件

public static class JTableModel extends AbstractTableModel {

private static final long serialVersionUID = 1L;

private static final String[] COLUMN_NAMES = new String[] {"Id", "Stuff", "Button1", "Button2"};

private static final Class>[] COLUMN_TYPES = new Class>[] {Integer.class, String.class, JButton.class, JButton.class};

@Override public int getColumnCount() {

return COLUMN_NAMES.length;

}

@Override public int getRowCount() {

return 4;

}

@Override public String getColumnName(int columnIndex) {

return COLUMN_NAMES[columnIndex];

}

@Override public Class> getColumnClass(int columnIndex) {

return COLUMN_TYPES[columnIndex];

}

@Override public Object getValueAt(final int rowIndex, final int columnIndex) {

/*Adding components*/

switch (columnIndex) {

case 0: return rowIndex;

case 1: return "Text for "+rowIndex;

case 2: // fall through

/*Adding button and creating click listener*/

case 3: final JButton button = new JButton(COLUMN_NAMES[columnIndex]);

button.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent arg0) {

JOptionPane.showMessageDialog(JOptionPane.getFrameForComponent(button),

"Button clicked for row "+rowIndex);

}

});

return button;

default: return "Error";

}

}

}

Sample Button click listener,它管理在组件上单击鼠标的时间

private static class JTableButtonMouseListener extends MouseAdapter {

private final JTable table;

public JTableButtonMouseListener(JTable table) {

this.table = table;

}

public void mouseClicked(MouseEvent e) {

int column = table.getColumnModel().getColumnIndexAtX(e.getX()); // get the coloum of the button

int row = e.getY()/table.getRowHeight(); //get the row of the button

/*Checking the row or column is valid or not*/

if (row < table.getRowCount() && row >= 0 && column < table.getColumnCount() && column >= 0) {

Object value = table.getValueAt(row, column);

if (value instanceof JButton) {

/*perform a click event*/

((JButton)value).doClick();

}

}

}

}

示例JTable单元格渲染器,管理单元格组件

private static class JTableButtonRenderer implements TableCellRenderer {

@Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {

JButton button = (JButton)value;

return button;

}

}

2020-10-25

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值