jtable 加入按钮等,一个实例

package com;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Polygon;

import javax.swing.DefaultCellEditor;
import javax.swing.DefaultListCellRenderer;
import javax.swing.Icon;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListCellRenderer;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;

public class EditableColorColumn {

public static void main(String args[]) {

Color choices[] = { Color.red, Color.orange, Color.yellow, Color.green,
Color.blue, Color.magenta };
ComboTableCellRenderer renderer = new ComboTableCellRenderer();
JComboBox comboBox = new JComboBox(choices);
comboBox.setRenderer(renderer);
TableCellEditor editor = new DefaultCellEditor(comboBox);

JFrame frame = new JFrame("Editable Color Table");
TableModel model = new ColorTableModel();
JTable table = new JTable(model);

TableColumn column = table.getColumnModel().getColumn(3);
column.setCellRenderer(renderer);
column.setCellEditor(editor);

JScrollPane scrollPane = new JScrollPane(table);
frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
frame.setSize(400, 150);
frame.setVisible(true);
}
}

class ComboTableCellRenderer implements ListCellRenderer, TableCellRenderer {
DefaultListCellRenderer listRenderer = new DefaultListCellRenderer();

DefaultTableCellRenderer tableRenderer = new DefaultTableCellRenderer();

private void configureRenderer(JLabel renderer, Object value) {
if ((value != null) && (value instanceof Color)) {
renderer.setIcon(new DiamondIcon((Color) value));
renderer.setText("");
} else {
renderer.setIcon(null);
renderer.setText((String) value);
}
}

public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
listRenderer = (DefaultListCellRenderer) listRenderer
.getListCellRendererComponent(list, value, index, isSelected,
cellHasFocus);
configureRenderer(listRenderer, value);
return listRenderer;
}

public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
tableRenderer = (DefaultTableCellRenderer) tableRenderer
.getTableCellRendererComponent(table, value, isSelected,
hasFocus, row, column);
configureRenderer(tableRenderer, value);
return tableRenderer;
}
}

class ColorTableModel extends AbstractTableModel {

Object rowData[][] = { { "1", "ichi - \u4E00", Boolean.TRUE, Color.red },
{ "2", "ni - \u4E8C", Boolean.TRUE, Color.blue },
{ "3", "san - \u4E09", Boolean.FALSE, Color.green },
{ "4", "shi - \u56DB", Boolean.TRUE, Color.magenta },
{ "5", "go - \u4E94", Boolean.FALSE, Color.pink }, };

String columnNames[] = { "English", "Japanese", "Boolean", "Color" };

public int getColumnCount() {
return columnNames.length;
}

public String getColumnName(int column) {
return columnNames[column];
}

public int getRowCount() {
return rowData.length;
}

public Object getValueAt(int row, int column) {
return rowData[row][column];
}

public Class getColumnClass(int column) {
return (getValueAt(0, column).getClass());
}

public void setValueAt(Object value, int row, int column) {
rowData[row][column] = value;
}

public boolean isCellEditable(int row, int column) {
return (column != 0);
}
}

class DiamondIcon implements Icon {
private Color color;

private boolean selected;

private int width;

private int height;

private Polygon poly;

private static final int DEFAULT_WIDTH = 10;

private static final int DEFAULT_HEIGHT = 10;

public DiamondIcon(Color color) {
this(color, true, DEFAULT_WIDTH, DEFAULT_HEIGHT);
}

public DiamondIcon(Color color, boolean selected) {
this(color, selected, DEFAULT_WIDTH, DEFAULT_HEIGHT);
}

public DiamondIcon(Color color, boolean selected, int width, int height) {
this.color = color;
this.selected = selected;
this.width = width;
this.height = height;
initPolygon();
}

private void initPolygon() {
poly = new Polygon();
int halfWidth = width / 2;
int halfHeight = height / 2;
poly.addPoint(0, halfHeight);
poly.addPoint(halfWidth, 0);
poly.addPoint(width, halfHeight);
poly.addPoint(halfWidth, height);
}

public int getIconHeight() {
return height;
}

public int getIconWidth() {
return width;
}

public void paintIcon(Component c, Graphics g, int x, int y) {
g.setColor(color);
g.translate(x, y);
if (selected) {
g.fillPolygon(poly);
} else {
g.drawPolygon(poly);
}
g.translate(-x, -y);
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用 AbstractTableModel 构建Table 在表格中添加JButton按钮,之前在网上找了2天没有找到好用的程序,最终终于找到一个好用的例子。 不要使,我退你们分。。 sing the Swing JTable class can quickly become a sticky business when you want to customize it to your specific needs. First you must become familiar with how the JTable class is organized. Individual cells are rendered by TableCellRenderer implementations. The table contents are represented by an implementation of the TableModel interface. By default, JTable uses DefaultTableCellRenderer to draw its cells. DefaultTableCellRenderer recognizes a few primitive types, rendering them as strings, and can even display Boolean types as checkboxes. But it defaults to displaying the value returned by toString() for types it does not specifically handle. You have to provide your own TableCellRenderer implementation if you want to display buttons in a JTable. The TableCellRenderer interface contains only one method, getTableCellRendererComponent(...), which returns a java.awt.Component that knows how to draw the contents of a specific cell. Usually, getTableCellRendererComponent() will return the same component for every cell of a column, to avoid the unnecessary use of extra memory. But when the contents of a cell is itself a component, it is all right to return that component as the renderer. Therefore, the first step towards having JButtons display correctly in a JTable is to create a TableCellRenderer implementation that returns the JButton contained in the cell being rendered. In the accompanying code listing, JTableButtonRenderer demonstrates how to do this. Even after creating a custom TableCellRenderer, you're still not done. The TableModel associated with a given JTable does not only keep track of the contents of each cell, but it also keeps track of the class of data stored in each column. DefaultTableModel is designed to work with DefaultTableCellRenderer and will return java.lang.String.class for columns containing data types that it does not specifically handle. The exact method that does this is getColumnClass(int column). Your second step is to create a TableModel implementation that returns JButton.class for cells that contain JButtons. JTableButtonModel shows one way to do this. It just returns the result of getClass() for each piece of cell data. At this point, you're almost done, but not quite. What's the use of putting a JButton in a JTable if you can't press the darn thing? By default, JTable will not forward mouse events to components contained in its cells. If you want to be able to press the buttons you add to JTable, you have to create your own MouseListener that forwards events to the JButton cells. JTableButtonMouseListener demonstrates how you could do this.
您可以通过添加 ActionListener 来监听 JTable 上的按钮。首先,您需要创建一个 JButton,并将其添加到 JTable 中的每一行。然后,为每个按钮添加 ActionListener,并在监听器中处理按钮点击事件。 下面是一个简单的示例代码,演示如何在 JTable 上监听按钮点击事件: ```java import javax.swing.*; import javax.swing.event.*; import java.awt.*; import java.awt.event.*; public class TableButtonListener { public static void main(String[] args) { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 创建表格模型 DefaultTableModel model = new DefaultTableModel(new Object[]{"Name", "Button"}, 0); // 向模型中添加数据 model.addRow(new Object[]{"John", new JButton("Button 1")}); model.addRow(new Object[]{"Jane", new JButton("Button 2")}); // 创建 JTable JTable table = new JTable(model); // 获取按钮列的单元格渲染器 TableColumn buttonColumn = table.getColumn("Button"); buttonColumn.setCellRenderer(new TableCellRenderer() { @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { return (Component) value; } }); // 获取按钮列的单元格编辑器 buttonColumn.setCellEditor(new DefaultCellEditor(new JCheckBox()) { @Override public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { return (Component) value; } }); // 添加按钮点击事件监听器 table.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { int row = table.rowAtPoint(e.getPoint()); int column = table.columnAtPoint(e.getPoint()); // 检查点击的是否是按钮列 if (column == table.getColumn("Button").getModelIndex()) { // 处理按钮点击事件 JButton button = (JButton) table.getValueAt(row, column); System.out.println("Button clicked: " + button.getText()); } } }); frame.add(new JScrollPane(table)); frame.pack(); frame.setVisible(true); } } ``` 在这个示例中,我们创建了一个包含两列的表格模型,其中一列是按钮。我们设置了单元格渲染器和编辑器,以便在表格中显示按钮。然后,我们通过添加鼠标点击事件监听器来处理按钮的点击事件。 当您点击按钮时,程序会打印出相应按钮的文本内容。您可以在监听器中根据需要执行其他操作。 希望这可以帮助到您!如果您有任何其他问题,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值