日期:2014-05-20  浏览次数:20720 次

为什么JTable的行标题不显示
package com.jtable;

import java.awt.BorderLayout;

public class JTableDemo1 extends JFrame {

private JPanel contentPane;
private JTable table;
private JTextField textField;

/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
JTableDemo1 frame = new JTableDemo1();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

/**
* Create the frame.
*/
public JTableDemo1() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);

table = new JTable();
table.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
Object o=table.getValueAt(table.getSelectedRow(), table.getSelectedColumn());
//String str = (String)o;

textField.setText(o.toString());
}
});
table.setModel(new DefaultTableModel(
new Object[][] {
{new Integer(61), new Integer(62), new Integer(63)},
{new Integer(64), new Integer(65), new Integer(66)},
{new Integer(67), new Integer(68), new Integer(69)},
{new Integer(70), new Integer(71), new Integer(72)},
{new Integer(73), new Integer(74), new Integer(75)},
{new Integer(76), new Integer(77), new Integer(78)},
{new Integer(79), new Integer(80), new Integer(81)},
{new Integer(82), new Integer(83), new Integer(84)},
},
new String[] {
"语文", "数学", "英语"
}
));
table.setBounds(47, 22, 321, 129);
contentPane.add(table);

JLabel lblNewLabel = new JLabel("\u5F53\u524D\u70B9\u51FB\u7684\u5185\u5BB9\u4E3A");
lblNewLabel.setBounds(47, 200, 139, 15);
contentPane.add(lblNewLabel);

JScrollBar scrollBar = new JScrollBar();
scrollBar.setBounds(351, 22, 17, 48);
contentPane.add(scrollBar);

textField = new JTextField();
textField.setBounds(242, 197, 66, 21);
contentPane.add(textField);
textField.setColumns(10);
}
}

------解决方案--------------------
注释以下一行
//contentPane.setLayout(null);

修改以下一行
table.setModel(new DefaultTableModel(new Object[][] {
{ new Integer(61), new Integer(62), new Integer(63) },
{ new Integer(64), new Integer(65), new Integer(66) },
{ new Integer(67), new Integer(68), new Integer(69) },
{ new Integer(70), new Integer(71), new Integer(72) },
{ new Integer(73), new Integer(74), new Integer(75) },
{ new Integer(76), new Integer(77), new Integer(78) },
{ new Integer(79), new Integer(80), new Integer(81) },
{ new Integer(82), new Integer(83), new Integer(84) }, },
new String[] { "语文", "数学", "英语" }));
table.setBounds(47, 22, 321, 129);
contentPane.add(new JScrollPane(table));//~~~~~~~~~~~~~~~~~~~~