2013-10-17 160 views
0

如何達到outerPanel的全寬度?Swing全尺寸JPanel

private JPanel createLabelPanel() { 

     final JToolTip tt = new JToolTip(); 
     //tt.setSize(new Dimension(100,200)); 
     final CompoundBorder cb = new CompoundBorder(tt.getBorder(), BorderFactory.createEmptyBorder(2, 2, 2, 2)); 
     final JPanel innerPanel = new JPanel(); 
     innerPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK)); 

     innerPanel.setBorder(cb); 
     innerPanel.setBackground(tt.getBackground()); 
     innerPanel.add(displayLabel); 
     innerPanel.setBorder(BorderFactory.createLineBorder(Color.GREEN)); 

     final JScrollPane tooltipscrool = new JScrollPane(innerPanel); 
     //tooltipscrool.setMinimumSize(new Dimension(200,100)); 
     tooltipscrool.setPreferredSize(new Dimension(100,120)); 
     tooltipscrool.setBorder(BorderFactory.createLineBorder(Color.BLACK)); 

     final JPanel outerPanel = new JPanel(); 
     outerPanel.add(tooltipscrool); 
     outerPanel.setBorder(BorderFactory.createLineBorder(Color.GREEN)); 
     //outerPanel.set 
     return outerPanel; 
    } 

讓我:

enter image description here

,我的目標是擁有innerPanel的全寬(綠色的)。

回答

1

JPanel默認使用FlowLayout,這傾向於使用每個組件的首選大小來定義它們的大小。

改用BorderLayout,例如...

final JPanel outerPanel = new JPanel(new BorderLayout()); 

看看How to layout components within a container更多細節

你也應該避免使用setPreferredSize如果可能的話,請Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?更多細節

+0

我沒有意識到JPanel默認使用FlowLayout,謝謝!我不能點擊UP:/ –

+0

不用擔心,你應該可以很快點擊綠色點擊,如果你滿意答案;) – MadProgrammer

+0

像程序員一樣,但不容易進入.. –