我想把FlowLayout
與可以說BorderLayout
內的5個標籤作爲北面板(BorderLayout.NORTH
),當我調整我的窗口/框架的大小時,我希望標籤不會消失,而是移動到新行。如何在調整大小時使FlowLayout重新定位組件。
我一直在閱讀有關min,max值和preferredLayoutSize方法。但他們似乎沒有幫助,我仍然感到困惑。
此外,我不想使用其他佈局,如包裝或其他東西。
我想把FlowLayout
與可以說BorderLayout
內的5個標籤作爲北面板(BorderLayout.NORTH
),當我調整我的窗口/框架的大小時,我希望標籤不會消失,而是移動到新行。如何在調整大小時使FlowLayout重新定位組件。
我一直在閱讀有關min,max值和preferredLayoutSize方法。但他們似乎沒有幫助,我仍然感到困惑。
此外,我不想使用其他佈局,如包裝或其他東西。
以下代碼完全符合您的要求。
程序有一個框架,其contentPane被設置爲BorderLayout
。它包含另一個面板flowPanel
,它有一個流佈局,並被添加到BorderLayout.NORTH
。
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class PanelFun extends JFrame {
final JPanel flowPanel;
public PanelFun() {
setPreferredSize(new Dimension(300,300));
getContentPane().setLayout(new BorderLayout());
flowPanel = new JPanel(new FlowLayout());
addLabels();
getContentPane().add(flowPanel, BorderLayout.NORTH);
addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
PanelFun.this.getContentPane().remove(flowPanel); //this statement is really optional.
PanelFun.this.getContentPane().add(flowPanel);
}
});
}
void addLabels(){
flowPanel.add(new JLabel("One"));
flowPanel.add(new JLabel("Two"));
flowPanel.add(new JLabel("Three"));
flowPanel.add(new JLabel("Four"));
flowPanel.add(new JLabel("Five"));
}
public static void main(String[] args) {
final PanelFun frame = new PanelFun();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.pack();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
frame.setVisible(true);
}
});
}
}
那麼,它是如何工作的?
於具有內flowPanel
重新調整部件時,幀大小,關鍵是這段代碼
PS:讓我知道如果你是新的Swing
和不理解的代碼的某些部分。
addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
PanelFun.this.getContentPane().remove(flowPanel);
PanelFun.this.getContentPane().add(flowPanel);
}
});
如果沒有這種碼flowPanel
不會重新調整它的部件,因爲它是不正常的行爲,當該含幀被重新調整到重新定位的組件。
但是,當將flowPanel
添加到面板時,它也會按照可用空間定位組件。所以,如果我們在每次調整幀大小時添加flowPanel
,則內部元素將被重新定位以使用可用空間。
更新:
由於camickr指出正確的,這種方法不會在情況下工作,你添加任何東西到中心(BorderLayout.CENTER
)
一個約FlowLayout
惱人的事情之一是,它不」當可用水平空間變小時,「包裝」它的內容。
相反,看看WrapLayout,這是FlowLayout
與包裝...
看起來像一個跨頁:http://www.coderanch.com/t/606655/GUI/java/Swing-FlowLayout- BorderLayout的。有趣的是你如何得到相同的答案。 – camickr 2013-03-07 04:35:00