我正在尝试将JTable
放入JScrollPane
。 JScrollPane
位于JPanel
内,JTabbedPane
。
以下是代码:
JScrollPane scrollPane = new JScrollPane();
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
JPanel pnlMaxMinAvg1 = new JPanel();
scrollPane.setViewportView(pnlMaxMinAvg1);
tabbedPane.addTab("MaxMinAvg1", null, pnlMaxMinAvg1, null);
pnlMaxMinAvg1.setLayout(new BorderLayout(0,0));
table = new JTable();
table.setModel(new DefaultTableModel(
new Object[][] {{"V_L1_N_RMS_AVG", null}
},
new String[] {
"Variable", "Value"
}
));
table.setBounds(178, 11, 200,300);
scrollPane.add(table);
运行此时,不会显示table
。如果我设置:
pnlMaxMinAvg1.add(table);
然后table
可见。
为什么?
答案 0 :(得分:1)
当您将JPanel
,pnlMaxMinAvg1
视为scrollPane
的视口视图时,它是空的。将table
添加到pnlMaxMinAvg1
会使滚动窗格显示一些非空内容。此外,避免setBounds()
并让布局完成工作。在下面的示例中,滚动窗格的视图显式设置为表格,就像在片段中一样,但您可以在滚动窗格的构造函数中指定它。
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
/**
* @see https://stackoverflow.com/q/46669145/230513
*/
public class TableTest {
private void display() {
JFrame f = new JFrame("TableTest");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTable table = new JTable();
table.setModel(new DefaultTableModel(
new Object[][]{{"V_L1_N_RMS_AVG", null}},
new String[]{"Variable", "Value"}
));
JScrollPane jsp = new JScrollPane();
jsp.setViewportView(table);
JTabbedPane jtp = new JTabbedPane();
jtp.add("TableTest", jsp);
f.add(jtp);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new TableTest()::display);
}
}
在此版本中,我添加了N
行数据并覆盖了Scrollable
方法getPreferredScrollableViewportSize()
,如图here所示。调整封闭窗口的大小以查看它如何影响滚动条。
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
/**
* @see https://stackoverflow.com/q/46669145/230513
*/
public class TableTest {
private static final int N = 16;
private void display() {
JFrame f = new JFrame("TableTest");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DefaultTableModel model = new DefaultTableModel(
null, new String[]{"Variable", "Value"}
);
JTable table = new JTable(model) {
@Override
public Dimension getPreferredScrollableViewportSize() {
return new Dimension(256, getRowHeight() * N / 2);
}
};
for (int i = 0; i < N; i++) {
model.addRow(new Object[]{"V_L1_N_RMS_AVG" + i, String.valueOf(i)});
}
JScrollPane jsp = new JScrollPane();
jsp.setViewportView(table);
JTabbedPane jtp = new JTabbedPane();
jtp.add("TableTest", jsp);
f.add(jtp);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new TableTest()::display);
}
}