100分求JTable解决方案
我想在表格中加入一个控件,比如说进度条.图片,按钮.但是表格中只显示这个进度条的相关属性,并不把这些控件显示出来,请较高手.代码方式表述.
------解决方案--------------------怎么没人呀,偶给你顶上去。。。
------解决方案--------------------需要实现接口TableCellRenderer,即提供一个单元格绘制器,用于绘制如JButton
然后table.setDefaultRenderer()设置绘制器
给你一个很简单的例子
package csdn;
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
//实现TableCellRenderer,绘制JButton
class JTableButtonRenderer extends JButton implements TableCellRenderer {
private TableCellRenderer defaultRenderer;
public JTableButtonRenderer(TableCellRenderer renderer) {
defaultRenderer = renderer;
}
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected,
boolean hasFocus,
int row, int column)
{
if (isSelected) {
this.setBorder(BorderFactory.createLineBorder(Color.BLUE));
}
else {
this.setBorder(null);
}
return this;
}
}
class JTableButtonModel extends AbstractTableModel {
private Object[][] rows = {{new JButton( "test ")}};
private String[] columns = { "test "};
public String getColumnName(int column) {
return columns[column];
}
public int getRowCount() {
return rows.length;
}
public int getColumnCount() {
return columns.length;
}
public Object getValueAt(int row, int column) {
return rows[row][column];
}
public boolean isCellEditable(int row, int column) {
return false;
}
public Class getColumnClass(int column) {
return getValueAt(0, column).getClass();
}
}
public final class TableTest extends JFrame {
private JTable table;
public TableTest() {
TableCellRenderer defaultRenderer;
table = new JTable(new JTableButtonModel());
defaultRenderer = table.getDefaultRenderer(JButton.class);
table.setDefaultRenderer(JButton.class, new JTableButtonRenderer(defaultRenderer)); //设置绘制器
table.setPreferredScrollableViewportSize(new Dimension(400, 200));
this.setContentPane(table);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(300, 300);
}
public static void main(String[] args) {
JFrame frame = new TableTest();
frame.setVisible(true);
}
}
------解决方案--------------------表格重绘时,才能看得到
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;
public class MainFrame extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel jContentPane = null;
private JScrollPane jScrollPane = null;
private JTable jTable = null;
private JProgressBar pbar;
private JProgressBar jProgressBar = null;
/**
* This is the default constructor
*/
public MainFrame() {
super();
pbar = new JProgressBar();
initialize();
setVisible(true);
}
/**
* This method initializes this
*
* @return void
*/
private void initialize() {
this.setSize(489, 253);