更改 JScrollPane 内 JTable 的首选大小时,即使为垂直和水平滚动条设置了 AS_NEEDED
策略,JScrollPane 也不会相应地更新其滚动条。如何让滚动 Pane 更新其滚动条?
下面的代码将显示 JTable 的首选大小发生变化,但 JScrollPane 不会添加滚动条。
这是我的 SSCCE...尽管“正确”部分存在问题:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.table.*;
public class jTableResizeWidthInScrollPane {
public static void main( String[] args ) {
JFrame frame = new JFrame();
JScrollPane scrollPane = new JScrollPane();
JTable table = new JTable();
final TimesTableModel timesTableModel = new TimesTableModel();
JTextField textField = new JTextField();
textField.addActionListener(new ActionListener() {
public void actionPerformed( ActionEvent ae ) {
timesTableModel.setMaxNumber(Integer.parseInt(textField.getText()));
SwingUtilities.invokeLater( new Runnable() {
public void run() {
table.revalidate();
System.out.println(
"preferred width: "+
table.getPreferredSize().getWidth()
);
}
});
}
});
table.setModel(timesTableModel);
scrollPane.setViewportView(table);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
frame.setLayout(new BorderLayout());
frame.add(textField,BorderLayout.NORTH);
frame.add(table,BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
public static class TimesTableModel extends AbstractTableModel {
private int max = 10;
public int getRowCount() {
return max;
}
public int getColumnCount() {
return max;
}
public void setMaxNumber( int max ) {
this.max = max;
fireTableStructureChanged();
}
public Object getValueAt(int row, int col) {
return (row+1)*(col+1);
}
@Override
public String getColumnName(int col) {
return String.valueOf(col);
}
}
}
最佳答案
两件事
- 当您应该添加
JScrollPane
时,您将JTable
添加到框架 - 您应该尝试在
JTable
上使用setAutoResizeModel
并将其设置为类似AUTO_RESIZE_OFF
类似...
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
frame.add(scrollPane, BorderLayout.CENTER);
关于java - 当客户的首选尺寸发生变化时,如何让 JScrollPane 滚动条出现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31093875/