我在自定义 JTable 的行标题中放置行有一些问题。
我用这段代码创建了这个 JTable:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Panel;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.util.ArrayList;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ScrollPaneConstants;
import javax.swing.border.BevelBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;
public class Form {
public static void main(String[] args) {
JFrame frame = new JFrame();
List<String> visibleColumns = new ArrayList<String>();
// THIS COLUMN NEED TO BE IN 2 LINES
visibleColumns.add("Cod Type\nGroup");
visibleColumns.add("Name");
DefaultTableModel tableModel = new DefaultTableModel(visibleColumns.toArray(),5);
JTable table = new JTable(tableModel);
Panel panel = new Panel();
panel.setBounds(5, 5, 352, 232);
panel.setLayout(new BorderLayout());
panel.add(table, BorderLayout.CENTER);
panel.add(table.getTableHeader(), BorderLayout.NORTH);
// Set Row Header
JScrollPane scroll = new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
// Set Column Header
JPanel columnHeader = new JPanel() {
@Override
public Dimension getPreferredSize() {
JScrollBar sb = new JScrollBar(JScrollBar.VERTICAL);
return new Dimension(sb.getPreferredSize().width, 10);
}
};
scroll.setRowHeaderView(columnHeader);
// Set 3D effects to scroll pane
JPanel left = new JPanel();
left.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
scroll.setCorner(ScrollPaneConstants.UPPER_LEFT_CORNER, left);
JPanel right = new JPanel();
right.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
scroll.setCorner(ScrollPaneConstants.UPPER_RIGHT_CORNER, right);
panel.add(scroll, BorderLayout.CENTER);
//Setting column size
TableColumnModel tcm = table.getColumnModel();
tcm.getColumn(0).setMaxWidth(Integer.MAX_VALUE);
tcm.getColumn(0).setWidth(73);
tcm.getColumn(0).setPreferredWidth(73);
tcm.getColumn(1).setMaxWidth(Integer.MAX_VALUE);
tcm.getColumn(1).setWidth(222);
tcm.getColumn(1).setPreferredWidth(222);
frame.add(panel);
frame.setSize(350, 180);
frame.setVisible(true);
}
}
但我需要文本"Cod Type\nGroup"
创建一个新的行行标题,如下图:
ps:注意文字居中。
谢谢