我正在使用MS Access數據庫作爲後端。我遇到了問題。檢索並顯示在小程序中後,內容會自動居中對齊,看起來很尷尬。我很困惑我的代碼的哪部分發生了這種情況。所以,請幫助我診斷問題。JTable內容是中心對齊的
public void addTable8(String query8)
{
SimpleDateFormat formatter8 = new SimpleDateFormat("dd/MM/yyyy");
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn8=DriverManager.getConnection("jdbc:odbc:vasantham","","");
Statement st8=conn8.createStatement();
ResultSet rs8=st8.executeQuery(query8);
ResultSetMetaData md8=rs8.getMetaData();
int cols8=md8.getColumnCount();
model8=new DefaultTableModel()
{
public Class getColumnClass(int col)
{
Object o = getValueAt(0, col);
if(o == null)
return Object.class;
else
return o.getClass();
}
};
model8.addColumn("Purpose");
model8.addColumn("Name");
model8.addColumn("Composition");
model8.addColumn("Expiry");
model8.addColumn("Stock");
model8.addColumn("Cost");
model8.addColumn("Cost/Tab");
model8.addColumn("Type");
model8.addColumn("Supplier");
model8.addColumn("Supplier Number");
model8.addColumn("Rack");
table8=new JTable(model8);
table8.setOpaque(true);
table8.setFillsViewportHeight(true);
table8.setBackground(new Color(255,255,208));
table8.getTableHeader().setBackground(new Color(255,228,181));
String[] tabledata8=new String[cols8];
int i=0;
while(rs8.next())
{
for(i=0;i<cols8;i++)
{
if(i==3)
{
Date intr8=(rs8.getDate(i+1));
tabledata8[i]=formatter8.format(intr8);
}
else
tabledata8[i]=rs8.getObject(i+1).toString();
}
model8.addRow(tabledata8);
}
panel8.removeAll();
table8.setDefaultRenderer(String.class, new CustomRenderer());
table8.setRowSelectionAllowed(true);
table8.setColumnSelectionAllowed(true);
table8.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane scroll8 = new JScrollPane(table8);
panel8.setLayout(new BorderLayout());
panel8.add(scroll8,BorderLayout.CENTER);
frame8.add(panel8,BorderLayout.CENTER);
conn8.close();
}
catch(Exception e8)
{
e8.printStackTrace();
}
}
class CustomRenderer implements TableCellRenderer
{
public CustomRenderer()
{
label = new JLabel();
label.setHorizontalAlignment(JLabel.CENTER);
label.setOpaque(true);
targetRow = -1;
targetCol = -1;
}
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus,
int row, int column)
{
if(isSelected)
{
label.setBackground(table.getSelectionBackground());
label.setForeground(table.getSelectionForeground());
}
else
{
label.setBackground(table.getBackground());
label.setForeground(table.getForeground());
}
if(row == targetRow && column == targetCol)
{
label.setBackground(new Color(176,196,222));
label.setFont(table.getFont().deriveFont(Font.BOLD));
}
else
{
label.setBorder(null);
label.setFont(table.getFont());
}
label.setText((String)value);
return label;
}
public void setTargetCell(int row, int col)
{
targetRow = row;
targetCol = col;
}
}
旁註:做DB查詢的事件調度線程是不好的做法,可能會導致被阻塞的用戶界面。考慮在後臺線程上執行這些操作。請參閱[併發中的Swing](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html)教程以獲取更多信息 – Robin 2012-08-07 07:46:40