我在 CardLayout 中没有发现任何性能问题。即使你有 1000 个子组件,它仍然感觉非常快。通过使用上一个/下一个或使用显示,它运行得非常快。
尝试发布重现您的问题的SSCCE,然后我们可以帮助您。下面是一些开始:
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class TestCardLayout {
protected void initUI() {
JFrame frame = new JFrame("test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final CardLayout layout = new CardLayout();
final JPanel panel = new JPanel(layout);
for (int i = 0; i < 1000; i++) {
panel.add(new JLabel("Label " + i), getLabelConstraint(i));
}
JButton next = new JButton("Next");
next.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
layout.next(panel);
}
});
JButton previous = new JButton("Previous");
previous.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
layout.previous(panel);
}
});
final JButton choose = new JButton("Choose");
choose.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String value = JOptionPane.showInputDialog(choose, "Enter a number between 0 and 999");
try {
int i = Integer.valueOf(value);
if (i > -1 && i < 1000) {
layout.show(panel, getLabelConstraint(i));
}
} catch (NumberFormatException e1) {
e1.printStackTrace();
}
}
});
JPanel buttonPanel = new JPanel();
buttonPanel.add(previous);
buttonPanel.add(next);
buttonPanel.add(choose);
frame.add(buttonPanel, BorderLayout.SOUTH);
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private String getLabelConstraint(int i) {
return "ComponentConstraint" + i;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new TestCardLayout().initUI();
}
});
}
}