JTable内容居中显示

要让JTable的内容居中显示方法如下:

JTable tabledata = new JTable();

DefaultTableCellRenderer tcr = new DefaultTableCellRenderer();// 设置table内容居中
 // tcr.setHorizontalAlignment(JLabel.CENTER);
  tcr.setHorizontalAlignment(SwingConstants.CENTER);// 这句和上句作用一样
  tabledata.setDefaultRenderer(Object.class, tcr);

参考:

import java.awt.Component;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;

public class MyJTable extends JTable {
  private MyCellRenderer renderer;

  public MyJTable(MyCellRenderer renderer) {
    super(8, 6);
    this.renderer = renderer;
  }

  public TableCellRenderer getCellRenderer(int row, int column) {
    return renderer;
  }

  public static void main(String[] args) {
    MyJTable t = new MyJTable(new MyCellRenderer());
    JScrollPane pane1 = new JScrollPane(t);//
    JFrame frame = new JFrame("JTableDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setContentPane(pane1);
    frame.pack();
    frame.setVisible(true);

  }
}

class MyCellRenderer extends DefaultTableCellRenderer {

  public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
      boolean hasFocus, int row, int column) {
    super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
    setHorizontalAlignment(SwingConstants.CENTER);
    return this;
  }
}

http://topic.csdn.net/u/20080208/18/031fccb4-ea5b-4bc5-a57d-40958a0106b9.html


你可能感兴趣的:(java)