即使在調整窗口大小(如果可能)的情況下,我想保留一個使用絕對佈局創建的面板。我遇到了幾個建議here和[這裏] [2]但沒有骰子!以下是我的示例代碼,任何想法或建議?我沒有像JLable那樣集中單個組件的問題,但是我想要將一個面板與許多組件集中在一起!調整窗口大小時的中心面板
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.BorderFactory;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.border.Border;
import javax.swing.JLabel;
public class TestPanel extends JFrame {
private JLabel lblSetupTitle;
private Border compoundBorder, outlineColorBorder, outlineBorder;
private JTextArea txtrManageData;
private JPanel childPanel;
public TestPanel()
{
setBackground(Color.white);
outlineColorBorder = BorderFactory.createLineBorder(Color.gray);
outlineBorder = BorderFactory.createEmptyBorder(20, 20, 20, 20);
compoundBorder = BorderFactory.createCompoundBorder(outlineColorBorder, outlineBorder);
lblSetupTitle = new JLabel("Setup");
lblSetupTitle.setBounds(443, 288, 44, 23);
txtrManageData = new JTextArea("Text Area Text");
txtrManageData.setBounds(393, 322, 142, 61);
childPanel = new JPanel();
childPanel.setLocation(89, 38);
childPanel.setSize(921, 452);
childPanel.setBorder(compoundBorder);
setupGUIElements();
setupPanel();
}
private void setupGUIElements()
{
txtrManageData.setBackground(null);
txtrManageData.setLineWrap(true);
txtrManageData.setWrapStyleWord(true);
}
private void setupPanel()
{
getContentPane().setLayout(new GridBagLayout()); // set layout of parent panel to GridBagLayout
childPanel.setLayout(null); // set layout of child panel to AbsoluteLayout
childPanel.add(lblSetupTitle);
childPanel.add(txtrManageData);
getContentPane().add(childPanel, new GridBagConstraints());
this.setSize(1020, 500);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
TestPanel ex = new TestPanel();
ex.setVisible(true);
}
});
}
}
編輯:在這樣
不要使用空'LayoutManager'。 – alex2410 2014-11-06 09:22:48
使用絕對佈局我們你的爆發錯誤,BorderLayout或GrudBagLayout將免費做到這一點。這正是我們擁有佈局管理器的許多原因之一,來處理這些冗長乏味的重複性任務...... – MadProgrammer 2014-11-06 09:22:50
哦..它會幫助佈局,如果'txtrManageData = new JTextArea(「Text Area Text 「);'而不是'txtrManageData = new JTextArea(」Text Area Text「,3,20);' – 2014-11-06 09:29:55