Java JFrame method pack()
I have a frame with 4 JPanels and 1 JScrollPane, the 4 panels are in border layout north, east, south, west and the scrollpane in the center.
I have been 开发者_JAVA技巧trying to get the pack method for a frame functioning but when run you just get the title bar of the window.
Any Ideas?
JFrame conFrame;
JPanel panel1;
JPanel panel2;
JPanel panel3;
JPanel panel4;
JScrollPane listPane;
JList list;
Object namesAr[];
...
...
...
namesAr= namesA.toArray();
list = new JList(namesAr);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setLayoutOrientation(JList.HORIZONTAL_WRAP);
list.setVisibleRowCount(-3);
list.addListSelectionListener(this);
listPane = new JScrollPane(list);
panel1 = new JPanel();
panel2 = new JPanel();
panel3 = new JPanel();
panel4 = new JPanel();
conFrame.setLayout(new BorderLayout());
panel1.setPreferredSize(new Dimension(100, 100));
panel2.setPreferredSize(new Dimension(100, 100));
panel3.setPreferredSize(new Dimension(100, 100));
panel4.setPreferredSize(new Dimension(100, 100));
panel1.setBackground(Color.red);
panel2.setBackground(Color.red);
panel3.setBackground(Color.red);
panel4.setBackground(Color.red);
conFrame.pack();
conFrame.add(panel1, BorderLayout.NORTH);
conFrame.add(panel2, BorderLayout.EAST);
conFrame.add(panel3, BorderLayout.SOUTH);
conFrame.add(panel4, BorderLayout.WEST);
conFrame.add(listPane, BorderLayout.CENTER);
conFrame.setVisible(true);
You need to add the panels to the frame "before" you do the pack() otherwise there is nothing to pack.
Also, the default layout for a frame is the BorderLayout.
精彩评论