简体   繁体   中英

How to assign the location of button?

How can we create a button on the frame that is in North and in center horizontally? (ie not occupy all the width)?

BorderLayout expands components in the NORTH location to fill the width of the container. Therefore you need to place it in another container that respects the preferred size of the component, the JButton in this case. You can use the default FlowLayout in JPanel :

JPanel northPanel = new JPanel(); 
JButton button = new JButton("OK");
frame.add(northPanel, BorderLayout.NORTH);

try solution like this:

public class MyFrame extends JFrame{
    public MyFrame(){
      super();
      JPanel contentPane = new JPanel(new BorderLayout());
      JButton myButton = new JButton("MyButton");
      JPanel myPanel = new JPanel(new FlowLayout.Center));
      myPanel.add(myButton);
      contentPane.add(myPanel,BorderLayout.CENTER); 
      setContentPanel(contentPane);
    }

}

when you wrap button in jpanel it saves it width, and center layout place it in the center

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM