Adding a button anywhere in a JPanel

30,778

You can use different Panels with different LayoutMangers to arrange the GUI as you like.

Have a look here for some common LayoutManagers: http://docs.oracle.com/javase/tutorial/uiswing/layout/using.html

Otherwise you could use the null Layout (panel.setLayout(null)) and place all components by setting the position. But I would recommend you the LayoutMangers

Share:
30,778

Related videos on Youtube

Hairr
Author by

Hairr

Updated on July 09, 2020

Comments

  • Hairr
    Hairr almost 4 years

    Without using the Swing GUI on Eclipse, I've been struggling with adding a button to a JFrame anywhere in the frame (so no BorderLayout.CENTER). I can't get past:

    JPanel panel = new JPanel();
    JButton OKButton = new JButton("OK");
    OKButton.addActionListener(new MyAction());
    panel.add(OKButton,BorderLayout.CENTER);
    

    So would something like this be completely redesigned or is there something I'm missing?

    EDIT: By Anywhere (as I'm planning to add more than one button/label to a frame), I meant perhaps a coordinate on the frame. So other than dead center, (example) 75% from the left and 25% down.

    • Hovercraft Full Of Eels
      Hovercraft Full Of Eels over 11 years
      Your best bet is to read up on and use the layout managers as they will make your GUI creation much easier. You can find the tutorial here.
    • Andrew Thompson
      Andrew Thompson over 11 years
      "75% from the left and 25% down" GridBagLayout accepts weights. I think so does MigLayout & possibly other 3rd party layouts.