Java 带有水平滚动条的 JTable
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2452694/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JTable with horizontal scrollbar
提问by Mr CooL
Is there any way to enable horizontal scroll-bar whenever necessary?
有什么方法可以在必要时启用水平滚动条?
The situation was as such: I've a JTable
, one of the cells, stored a long length of data. Hence, I need to have horizontal scroll-bar.
情况是这样的:我有一个JTable
,其中一个单元格存储了很长的数据。因此,我需要有水平滚动条。
Anyone has idea on this?
有人对此有想法吗?
采纳答案by Romain Linsolas
First, add your JTable
inside a JScrollPane
and set the policy for the existence of scrollbars:
首先,添加你的JTable
insideJScrollPane
并设置滚动条存在的策略:
new JScrollPane(myTable, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
Then, indicate that your JTable must not auto-resize the columns by setting the AUTO_RESIZE_OFF
mode:
然后,通过设置AUTO_RESIZE_OFF
模式指示您的 JTable 不得自动调整列的大小:
myJTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
回答by Nitesh Verma
Set the AutoResizeMode
to OFF
in the properties of the jTable
将AutoResizeMode
要OFF
在的特性jTable
回答by trashgod
For reference, here's a minimal exampleof the accepted approach. Moreover,
You can adjust the size of individual columns as shown in Setting and Changing Column Widths, as well as hereand here.
You can adjust the overall size of the enclosing scroll pane as shown in Implementing a Scrolling-Savvy Client, as well as hereand here.
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableModel;
/**
* @see https://stackoverflow.com/a/37318673/230513
*/
public class Test {
private void display() {
JFrame f = new JFrame("Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
TableModel model = new AbstractTableModel() {
private static final int N = 32;
@Override
public int getRowCount() {
return N;
}
@Override
public int getColumnCount() {
return N;
}
@Override
public Object getValueAt(int rowIndex, int colIndex) {
return "R" + rowIndex + ":C" + colIndex;
}
};
JTable table = new JTable(model) {
@Override
public Dimension getPreferredScrollableViewportSize() {
return new Dimension(320, 240);
}
};
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
f.add(new JScrollPane(table));
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Test()::display);
}
}
回答by A.Aleem11
For me it works:
对我来说它有效:
table.setAutoscrolls(true);
table.setAutoscrolls(true);