在 Java Swing 中,有人可以告诉我在将我的 JTable 放入 JScrollPane 之后使用 setPreferredScrollableViewportSize() 与在 JTable 实例上调用 setFillsViewportHeight(true) 之间的区别吗?我想知道哪个是好的做法。Herbert Schildt 建议使用 setPreferredScrollableViewportSize(),而 Horstmann 和 Cornell 建议使用 setFillsViewportHeight()。这是我在玩弄什么的简短示例。
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class TableDemo {
JTable jtabEmail;
String[] headings = {"From", "Address", "Subject", "Size"};
Object[][] data = {
{ "Wendy", "Wendy@HerbSchildt.com",
"Hello Herb", new Integer(287) },
{ "Alex", "Alex@HerbSchildt.com",
"Check this out!", new Integer(308) },
{ "Hale", "Hale@HerbSchildt.com",
"Found a bug", new Integer(887) },
{ "Todd", "Todd@HerbSchildt.com",
"Did you see this?", new Integer(223) },
{ "Steve", "Steve@HerbSchildt.com",
"I'm back", new Integer(357) },
{ "Ken", "Ken@HerbSchildt.com",
"Arrival time change", new Integer(512) }
};
JLabel jl;
public TableDemo() {
JFrame jfrm = new JFrame("Table Demo");
jfrm.setSize(500, 160);
jfrm.getContentPane().setLayout(new FlowLayout());
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jl = new JLabel("");
jtabEmail = new JTable(data, headings);
jtabEmail.setFillsViewportHeight(true);
JScrollPane jsp = new JScrollPane(jtabEmail);
//jtabEmail.setPreferredScrollableViewportSize(new Dimension(450, 80));
jtabEmail.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
StringBuilder sb = new StringBuilder("Selected Rows: ");
int[] rowsArray = jtabEmail.getSelectedRows();
for (int i = 0; i < rowsArray.length; i++) {
sb.append((rowsArray[i]+1) + " ");
}
jl.setText(sb.toString());
}
});
jfrm.getContentPane().add(jsp);
jfrm.getContentPane().add(jl);
//jfrm.pack();
jfrm.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new TableDemo();
}
});
}
}