问题是我有多个面板在那个mainpane停留在centre.using一个for循环我添加了1000个按钮到主面板。我添加了一个主窗格的滚动窗格。但我无法滚动。我尝试了来自stackoverflow的很多帖子的解决方案,但我无法解决请帮帮我
public class Products extends Applet {
private static final long serialVersionUID = -5897268039244126279L;
JPanel mainpane=new JPanel();
JPanel toppane=new JPanel();
JPanel leftpane=new JPanel()
{
public void paintComponent(Graphics g)
{
g.drawImage(img.getI![enter image description here][1]mage(),0,0,200,500,null);
}
}
;
JPanel total=new JPanel();
JPanel rightpane=new JPanel();
ImageIcon img=new ImageIcon(getClass().getResource("biskate.jpg"));
private void initialise() {
total.setPreferredSize(new Dimension(1366,650));
leftpane.setPreferredSize(new Dimension(200,500));
rightpane.setPreferredSize(new Dimension(266,500));
mainpane.setPreferredSize(new Dimension(900,500));
mainpane.setLayout(new FlowLayout());
toppane.setPreferredSize(new Dimension(1366,150));
total.setLayout(new BorderLayout());
leftpane.setBackground(Color.WHITE);
mainpane.setBackground(Color.BLUE);
toppane.setBackground(Color.WHITE);
rightpane.setBackground(Color.magenta);
total.add(leftpane,BorderLayout.WEST);
total.add(rightpane,BorderLayout.EAST);
JScrollPane scroll=new JScrollPane(mainpane,ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
// scroll.setPreferredSize(new Dimension(600,600));
//scroll.getViewport().add(mainpane);
total.add(scroll,BorderLayout.CENTER);
total.add(toppane,BorderLayout.NORTH);
add(total);
}
JCheckBox arr[];
BufferedImage image;
JLabel look=new JLabel(img);
public void init()
{
this.setSize(1366,650);
initialise();
arr=new JCheckBox[6];
String []s={"Rs. 2000 and Below","Rs. 2001 - Rs. 5000","Rs. 5001 - Rs. 10000","Rs. 10001 - Rs. 18000",
"Rs. 18001 - Rs. 25000","Rs. 25001 - Rs. 35000"};
leftpane.add(new JLabel("Choose price range"));
for(int i=0;i<6;i++)
{
arr[i]=new JCheckBox(s[i]);
arr[i].setBackground(Color.YELLOW);
leftpane.add(arr[i]);
}
addgrid();
}
private void addgrid()
{
for(int i=0;i<1000;i++)
{
mainpane.add(new JButton("holy"+" "+i));
}
}
答案 0 :(得分:2)
//leftpane.setPreferredSize(new Dimension(200,500));
//rightpane.setPreferredSize(new Dimension(266,500));
//mainpane.setPreferredSize(new Dimension(900,500));
//mainpane.setLayout(new FlowLayout());
//toppane.setPreferredSize(new Dimension(1366,150));
不要在任何组件上使用setPreferredSize()。面板的布局管理器确定面板的首选大小。然后,滚动条将在需要时自动显示。
此外,FlowLayout是面板的默认布局,因此您无需再次手动设置布局。