Java swing layout of two components

+--------------------------------------------+ | +-------+ +----------+| | | +---+ | | +-----+ || | | | A | | | | B | || | | +---+ | | +-----+ || | +-------+ +----------+| +--------------------------------------------+ ^ | | Center 

Background: I have

  • a JButton ("A") of size 50x25 inside a JPanel (FlowLayout.CENTER)
  • JLabel ("B") 100x25 in size, inside JPanel (FlowLayout.RIGHT)
  • two JPanels are in a JPanel

Desired result: I want

  • JButton "A" should always be centered horizontally,
  • JLabel "B" must always be level.

The thing I tried: This did not work for me

  • BorderLayout does not work for me because JButton "A" is shifted to the left:
  • I would prefer not to put an invisible WEST component to cancel the shift

     +--------------------------------------------+ | +-------+ +----------+| | | +---+ | | +-----+ || | | | A | | | | B | || | | +---+ | | +-----+ || | +-------+ +----------+| +--------------------------------------------+ ^ ^ | | | | | Center | Shifted Left 
  • GridLayout will not work because I do not want to extend "A" and "B"

Rate any suggestions!

ps

JButton / JLabels are inside their own JPanels, because without Jpanel BorderLayout.CENTER extends JButton over the entire width of the main panel (right up to the left edge of JLabel). JPanels not needed / critical to pose a problem

Conclusion

  • I went with the answer "Hovercraft Full Of Eels" posted below. Thank you
+6
source share
1 answer

You must nest JPanels and use a combination of layouts. Placing panels containing JButtons in another JPanel that uses GridLayout (1, 0) (1 row, variable number of columns) can work, and placing this JPanel in the BorderLayout.NORTH position of BorderLayout-using JPanel can work.

for instance

 import java.awt.*; import javax.swing.*; public class Foo003 { private static void createAndShowGui() { JButton btnA = new JButton("A"); JButton btnB = new JButton("B"); btnA.setPreferredSize(new Dimension(50, 25)); btnB.setPreferredSize(new Dimension(100, 25)); JPanel btnAPanel = new JPanel(); // uses default FlowLayout.CENTER JPanel btnBPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); btnAPanel.add(btnA); btnBPanel.add(btnB); JPanel topPanel = new JPanel(new GridLayout(1, 0)); topPanel.add(new JLabel("")); // empty placeholder label topPanel.add(btnAPanel); topPanel.add(btnBPanel); JPanel mainPanel = new JPanel(new BorderLayout()); mainPanel.add(topPanel, BorderLayout.NORTH); mainPanel.setPreferredSize(new Dimension(400, 300)); JFrame frame = new JFrame("Foo003"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(mainPanel); frame.pack(); frame.setLocationByPlatform(true); frame.setVisible(true); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGui(); } }); } } 
+5
source

Source: https://habr.com/ru/post/899804/


All Articles