[英]How do I align components in Java Swing?
我正在用Java構建一個簡單的初學者應用程序,我需要你的幫助來調整組件。 我要做的是將組件(JLabel“名稱”)對齊到面板的左側。 我已經嘗試過“新的FlowLayout(FlowLayout.LEFT)”,但它沒有用,所以我要求你幫助我。 這是下面的框架和源代碼的圖片。
public class firstClass extends JFrame implements ActionListener {
private JFrame frame1;
private JFrame frame2;
private JPanel mainPanelFirst;
private JPanel secondPanel;
private JButton newWindowButton;
private int mulitplyPanels;
private JLabel leftLabel;
private JLabel rightLabel;
private JComboBox leftCB;
private JComboBox rightCB;
第一窗口:
public JFrame createMainUI(){
frame1 = new JFrame("Main frame");
frame1.setSize(600,600);
frame1.setResizable(false);
frame1.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame1.setVisible(true);
mainPanelFirst = new JPanel();
mainPanelFirst.setLayout(new FlowLayout());
frame1.add(mainPanelFirst);
newWindowButton = new JButton("Open new window");
newWindowButton.addActionListener(this);
mainPanelFirst.add(newWindowButton);
return frame1;
}
第二個窗口(包括我想要對齊的標簽):
public JFrame createSecondUI() {
frame2 = new JFrame("Second frame");
frame2.setSize(600, 600);
frame2.setResizable(false);
frame2.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame2.setVisible(true);
secondPanel = new JPanel();
secondPanel.setLayout(new FlowLayout());
secondPanel.setBackground(Color.gray);
frame2.add(secondPanel);
JPanel topPanel = new JPanel();
topPanel.setLayout(new FlowLayout(70,400,20));
topPanel.setBackground(Color.WHITE);
secondPanel.add(topPanel);
leftLabel = new JLabel("Name:");
topPanel.add(leftLabel);
return frame2;
}
@Override
public void actionPerformed(ActionEvent e) {
createSecondUI();
}
}
謝謝您的幫助 :)
警告也讀這個: 我應該避免在Java Swing中使用set(Preferred | Maximum | Minimum)Size方法嗎?
由於JFrame 不可調整大小 ,因此請為topPanel指定一個定義的大小:
JPanel topPanel = new JPanel();
topPanel.setPreferredSize(new Dimension(600,100));
topPanel.setLayout(new FlowLayout(FlowLayout.LEFT,400,20));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.