将JPanels添加到JFrame时遇到麻烦。我的JFrame有一个GridBagLayout,在其中我以水平方式添加了这些JPanels,我用两种情况进行了测试,第一种显示了55个JPanels,它们通过滚动条排成一行,第二个根本不起作用,它必须显示76个JPanels,但结果却很奇怪:
我不是在发布代码,因为我认为它与代码无关,也许这是使用Swing进行GUI编程的限制。我找不到有关此(限制)或我正在发生的同一问题的任何信息。
谢谢
好的,我处理了以下代码:
import javax.swing.*;
import java.awt.*;
public class TestingFrame extends JPanel {
public TestingFrame() {
this.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 0.0;
gbc.weighty = 0.0;
gbc.anchor = GridBagConstraints.LINE_START;
gbc.fill = GridBagConstraints.BOTH;
int numOfPanels = 10000;
for (int i = 0; i < numOfPanels; ++i) {
JPanel toAdd = new JPanel();
JButton tmp = new JButton("HELLO IT'S ME");
toAdd.add(tmp);
gbc.gridx = i;
this.add(toAdd, gbc);
}
}
public static void main(String[] args) {
JFrame frame = new JFrame();
TestingFrame view = new TestingFrame();
JScrollPane scrPane = new JScrollPane(view);
frame.add(scrPane);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
此代码重现了我之前告诉您的错误。请注意,由于我现在正在使用的JPanels组件的数量,需要更多的面板来重现该错误,它们比原始面板小(仅一个按钮)。