我想以特定方式处理插入到 JTable 单元格中的文本。事实上,现在如果我写入一个单元格,文本将全部在同一行,而我想在两行中看到它。
也许我会用图形描述更清楚。看,我想要第二个:
我的表代码在这里:
public class TablePanel extends JPanel
{
private JTable table;
public Tabella()
{
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
table = new JTable(new MyTableModel());
table.setFillsViewportHeight(true);
table.setPreferredScrollableViewportSize(new Dimension(500, 100));
JScrollPane jps = new JScrollPane(table);
add(jps);
add(new JScrollPane(table));
table.setCellSelectionEnabled(true);
table.setRowHeight(30);
TableColumn tcol;
for (int i=0; i<table.getColumnCount(); i++)
{
tcol = table.getColumnModel().getColumn(i);
tcol.setCellRenderer(new CustomTableCellRenderer());
}
table.addMouseListener(
new MouseAdapter(){
public void mouseClicked(MouseEvent e) {
int row = table.rowAtPoint(new Point(e.getX(), e.getY()));
int col = table.columnAtPoint(new Point(e.getX(), e.getY()));
if (col>0) {
if (e.getClickCount() > 1) {
if (row == 5 | row == 6)
{
JOptionPane.showMessageDialog(null, "Impossible to set lesson.");
return;
}
else {
table.getColumnName(col);
String day = table.getColumnName(col);
String hour = (String) table.getValueAt(row, 0);
InsertLesson cell = new InsertLesson(day, hour);
cel.setVisible(true);
}
}
}
}
}
);
}
private class MyTableModel extends AbstractTableModel {
private String[] columns = {"","Monday","Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
private String[][] data = {{"8:30 - 9:30","","","","","",""},
{"9:30 - 10:30","","","","","",""},
{"10:30 - 11:30","","","","","",""},
{"11:30 - 12:30","","","","","",""},
{"12:30 - 13:30","","","","","",""},
{"13:30 - 14:30","","","","","",""},
{"14:30 - 15:30","","","","","",""},
{"15:30 - 16:30","","","","","",""},
{"16:30 - 17:30","","","","","",""}};
public int getColumnCount() {
return columns.length;
}
public int getRowCount() {
return data.length;
}
public String getColumnName(int col) {
return columns[col];
}
public Object getValueAt(int row, int col) {
return data[row][col];
}
}
public class CustomTableCellRenderer extends DefaultTableCellRenderer{
public Component getTableCellRendererComponent (JTable table,
Object obj, boolean isSelected, boolean hasFocus, int row, int column) {
Component cell = super.getTableCellRendererComponent(
table, obj, isSelected, hasFocus, row, column);
if (isSelected) {
cell.setBackground(Color.lightGray);
}
else {
if (row % 2 == 0) {
cell.setBackground(new Color (245,245,250));
}
else {
cell.setBackground(new Color(250,250,240));
}
}
return cell;
}
}
}
感谢 Kiheru 用户,我们找到了解决方案:我们必须:
1) 将插入单元格的字符串的格式居中;
2)将单元格本身的“空间”居中;
我们可以通过以下方式执行这些操作:
1)在必须插入单元格的字符串中插入html居中文本代码(自动识别html代码);
2)使用命令将单元格本身居中setHorizontalAlignment(JLabel.CENTER);
。
这个问题可能对每个有这个问题的人都有用。