hy,我正在尝试向窗格添加多个jbuttons并想要滚动它们。 所以我所做的是首先添加按钮到jpanel比jpanel到jscrollpane而不是jscrollpane到另一个jpanel等等。 但我得到的问题是按钮显示但没有滚动条滚动窗格并看到所有按钮。
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class ICFTWindow extends JFrame
{
JPanel mainPanel,userlistPanel,chatPanel,userlistPanel2;
JButton checkButton,button2,button3,button4,button5,button6;
JScrollPane scrollpane;
JScrollBar scrollbar;
ICFTWindow()
{
mainPanel = new JPanel();
mainPanel.setLayout(null);
userlistPanel = new JPanel(new FlowLayout());
userlistPanel.setBounds(0,0,160,270);
userlistPanel2 = new JPanel();
userlistPanel2.setBounds(0,0,100,270);
userlistPanel2.setLayout(new BorderLayout());
scrollpane = new JScrollPane(userlistPanel);
checkButton = new JButton();
checkButton.setPreferredSize(new Dimension(90, 50));
button2 = new JButton();
button2.setPreferredSize(new Dimension(90, 50));
button3 = new JButton();
button3.setPreferredSize(new Dimension(90, 50));
button4 = new JButton();
button4.setPreferredSize(new Dimension(90, 50));
button5 = new JButton();
button5.setPreferredSize(new Dimension(90, 50));
button6 = new JButton();
button6.setPreferredSize(new Dimension(90, 50));
userlistPanel.setBorder(BorderFactory.createLineBorder(Color.black));
scrollpane.add(userlistPanel);
mainPanel.add(userlistPanel);
userlistPanel.add(button2);
userlistPanel.validate();
userlistPanel.add(checkButton);
userlistPanel.validate();
userlistPanel.add(button3);
userlistPanel.validate();
userlistPanel.add(button4);
userlistPanel.validate();
userlistPanel.add(button5);
userlistPanel.validate();
userlistPanel.add(button6);
userlistPanel.validate();
userlistPanel.validate();
userlistPanel2.add(scrollpane);
mainPanel.add(userlistPanel2);
add(mainPanel);
setSize(500,300);
setVisible(true);
}
public static void main(String args[])
{
new ICFTWindow();
}
}
答案 0 :(得分:0)
删除这两行:
scrollpane.add(userlistPanel);
mainPanel.add(userlistPanel);
您不需要将JPanel
(您想要滚动条)添加到JScrollPane
。将它发送到滚动窗格的构造函数就足够了。
之后,您必须将滚动窗格添加到顶级组件,它还将添加其中包含的面板并在其上放置滚动条。有关如何使用滚动窗格的详细信息,请参阅here。