使用布局管理器时,您的代码对我来说似乎并不那么滞后。请对此进行测试:
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import javax.swing.*;
public class Foo2 {
protected static final int PREF_W = 400;
protected static final int PREF_H = 400;
public static void main(String[] args) {
final JScrollPane scrollPane_1 = new JScrollPane() {
@Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
};
final JPanel panel = new JPanel();
panel.setLayout(new GridLayout(0, 1));
scrollPane_1.setViewportView(panel);
for (int i = 0; i < 1015; i++) {
JPanel innerPanel = new JPanel();
innerPanel.setLayout(new BoxLayout(innerPanel, BoxLayout.LINE_AXIS));
JLabel length = new JLabel("foo");
length.setFont(new Font("Tahoma", Font.BOLD, 11));
length.setEnabled(false);
innerPanel.add(length);
innerPanel.add(Box.createHorizontalGlue());
JComboBox<String> combo = new JComboBox<String>();
combo.setPrototypeDisplayValue(" ");
combo.setModel(new DefaultComboBoxModel<String>(new String[] { "=", "!=" }));
combo.setMaximumSize(combo.getPreferredSize());
innerPanel.add(combo);
JTextField text = new JTextField(10);
JPanel textWrapper = new JPanel();
textWrapper.add(text);
innerPanel.add(textWrapper);
panel.add(innerPanel);
}
JFrame frame = new JFrame();
frame.add(scrollPane_1);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
编辑
用 JTable 代替怎么样?
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class Foo3 {
protected static final int PREF_W = 400;
protected static final int PREF_H = 400;
public static void main(String[] args) {
final JScrollPane scrollPane_1 = new JScrollPane() {
@Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
};
String[] columnNames = {"Foo", "Bar", "Baz"};
String[][] data = new String[1015][3];
for (int i = 0; i < data.length; i++) {
data[i] = new String[]{"foo", "==", ""};
}
DefaultTableModel model = new DefaultTableModel(data, columnNames){
@Override
public boolean isCellEditable(int row, int column) {
return (column != 0);
}
};
JTable table = new JTable(model);
table.getColumnModel().getColumn(1).setCellEditor(new DefaultCellEditor(
new JComboBox<String>(new String[]{"==", "!="})));
final JPanel panel = new JPanel();
panel.setLayout(new GridLayout(0, 1));
scrollPane_1.setViewportView(table);
JFrame frame = new JFrame();
frame.add(scrollPane_1);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}