我添加了滚动条,但它不会在框架上上下滚动,也看不到我创建的上部标签。请给我任何建议,这样我就可以在框架中上下滚动了。我还有一个问题,当我的框架大小固定时,我想创建许多标签和文本字段,我必须向下滚动,所以在这种情况下,我必须增加其帧大小或不
public static void main(String[] args)
{
JFrame frame = new JFrame("jframe");
JLabel[] labels=new JLabel[50];
for (int i=0;i<labels.length;i++)
{
labels[i]=new JLabel("Column" + i);
}
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints cst = new GridBagConstraints();
JScrollBar vbar=new JScrollBar(JScrollBar.VERTICAL, 30, 40, 0, 500);
for(int i =0 ; i<50 ;i++)
{
cst.fill = GridBagConstraints.HORIZONTAL;
cst.gridx = 0;
cst.gridy = i;//
cst.gridwidth = 2;
panel.add(labels[i],cst);
}
frame.getContentPane().add(vbar, BorderLayout.EAST);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1300,700);
frame.getContentPane().add(panel);
frame.setVisible(true);
}
为什么不使用JScrollPane并将面板放在上面?看看:https://docs.oracle.com/javase/tutorial/uiswing/components/scrollpane.html
public static void main(String[] args)
{
JFrame frame = new JFrame("jframe");
JLabel[] labels = new JLabel[50];
for(int i = 0; i < labels.length; i++)
{
labels[i] = new JLabel("Column" + i);
}
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints cst = new GridBagConstraints();
// JScrollBar vbar = new JScrollBar(JScrollBar.VERTICAL,30,40,0,500);
for(int i = 0; i < 50; i++)
{
cst.fill = GridBagConstraints.HORIZONTAL;
cst.gridx = 0;
cst.gridy = i;//
cst.gridwidth = 2;
panel.add(labels[i],cst);
}
JScrollPane scrollPane = new JScrollPane(panel);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
frame.getContentPane().add(scrollPane,BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1300,700);
frame.setVisible(true);
}