[英]Swing - remove extra space from JScrollPane so that it only fits the table rows
I am a newbie to swing. I have created a table from an array list of objects.我是 swing 的新手。我从对象数组列表创建了一个表。 I want to know how I can remove the access white space from bellow the table- that is adjust the size of the JScrollPane so that it fits the table without leaving any extra space.
我想知道如何从表格下方删除访问空白区域 - 即调整 JScrollPane 的大小,使其适合表格而不留下任何额外空间。
Here's my code这是我的代码
import javax.swing.table.AbstractTableModel;
import java.util.ArrayList;
public class PersonTableModel extends AbstractTableModel{
private String[] columnNames = {"Name","Date of Birth","Type"};
private ArrayList<Person> list;
public PersonTableModel(ArrayList<Person> personList){
this.list = personList;
}
@Override
public int getRowCount() {
return list.size();
}
@Override
public int getColumnCount() {
return columnNames.length;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
Object temp = null;
if (columnIndex == 0) {
temp = list.get(rowIndex).getName();
}
else if (columnIndex == 1) {
temp = list.get(rowIndex).getDOB().getDate();
}
else if (columnIndex == 2) {
if(list.get(rowIndex) instanceof Teacher)
temp = "Teacher";
else
temp = "Student";
}
return temp;
}
public String getColumnName(int col) {
return columnNames[col];
}
}
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import java.awt.*;
import java.util.ArrayList;
public class PersonTable extends JFrame{
JTable myTable;
PersonTableModel tableModel;
ArrayList<Person> list;
// contructor
public PersonTable(ArrayList<Person> list){
this.list = list;
tableModel = new PersonTableModel(list);
myTable = new JTable(tableModel);
setBounds(10,10,600,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JScrollPane scrollPane = new JScrollPane(myTable);
JPanel panel = new JPanel();
panel.add(scrollPane);
add(panel,BorderLayout.CENTER);
}
}
Thanks in advance.提前致谢。
After setting the model of the table you can use:设置表的 model 后,您可以使用:
myTable.setPreferredScrollableViewportSize(myTable.getPreferredSize());
Also, instead of using setBounds(...) you would need to add:此外,您需要添加以下内容,而不是使用 setBounds(...)
pack()
at the bottom of the constructor, so the frame can be sized properly.在构造函数的底部,因此可以适当调整框架的大小。
Note, this works for tables with limited rows.请注意,这适用于行数有限的表。 For a large table you may want to limit the number of rows displayed before scrolling is required.
对于大表,您可能希望在需要滚动之前限制显示的行数。 In this case you can override the
getPreferredScrollableViewportSize()
method as demonstrated in:在这种情况下,您可以覆盖
getPreferredScrollableViewportSize()
方法,如下所示:
JTable inside JScrollPane inside JPanel with GridBagLayout, doesn't look as it should JTable 在带有 GridBagLayout 的 JPanel 中的 JScrollPane 中,看起来不应该
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.