簡體   English   中英

如何將一個元素與 JPanel 的右側對齊,而將另一個元素對齊到 JPanel 的左側?

[英]How can I align one element to the right and another to the left side of my JPanel?

我創建了一個JPanel並在其中添加了兩個JButtons 我將面板布局設置為FlowLayout 我希望一個JButton位於JFrame的左側,另一個JButton位於右側。

我試過了,但它拋出了IllegalArgumentException

        JPanel mainPanel = new JPanel(new FlowLayout());

        JButton login = new JButton("Login");
        JButton register = new JButton("Register");

        mainPanel.add(register, FlowLayout.RIGHT);
        mainPanel.add(login, FlowLayout.LEFT);

我可以使用FlowLayout做到這一點嗎? 哪種布局可以使它起作用?

mainPanel.add(register, FlowLayout.RIGHT);
mainPanel.add(login, FlowLayout.LEFT);

這不是那些 FlowLayout 變量的使用方式。 它們用作布局管理器的屬性,而不是作為 add(...) 方法的約束。 閱讀FlowLayout API 了解更多信息。

我希望一個 JButton 位於 JFrame 的左側,另一個 JButton 位於右側。 我可以使用 FlowLayout 做到這一點嗎?

不。

哪種布局可以使它起作用?

您可以使用帶有以下內容的面板:

  1. BorderLayout - 向 BorderLayout 添加一個按鈕。LINE_START,向BorderLayout.LINE_START添加一個按鈕BorderLayout.LINE_END
  2. BoxLayout - 在兩個按鈕之間添加一個Box.createHorizontalGlue()

閱讀有關布局管理器的 Swing 教程中的部分,以獲取有關上述每個布局管理器的更多信息和示例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM