0

I know that there are already very similar questions to my question on stackoverflow, but neither one of them answers my question. I want to put my JButton on a specific location on my JFrame in JAVA. Here is my Code:

public class DetectMotion extends JFrame {

private JLabel label = null;

public DetectMotionExample() {

    JPanel pnlButton = new JPanel();
    label = new JLabel(nothing);
    JButton btn = new JButton("Close");

    pnlButton.setLayout(new BorderLayout());

    setTitle("Motion Detector");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLayout(new FlowLayout());

    btn.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e) {
            if (e.getActionCommand().equals("Close")) {
                //TO-DO
            }
        }
    });

    WebcamPanel panel = new WebcamPanel(webcam);

    add(panel);
    pnlButton.add(btn,BorderLayout.SOUTH);
    pnlButton.add(label,BorderLayout.NORTH);
    add(pnlButton);

    pack();
    setVisible(true);
}

}

I have a panel on my JFrame (webcamPanel) and a JPanel called pnlButton that includes the JButton (btn) and JLabel (label).

Now, how can I specifically change the location of my button instead of just using BorderLayout.NORTH?

Thanks!

Salehest6990
  • 23
  • 1
  • 3
  • Where were you plaining to put it? – MadProgrammer Mar 05 '15 at 00:13
  • By specific location, I mean pixel coordinations, let's say I want to put my button at (400,400). – Salehest6990 Mar 05 '15 at 00:18
  • The next question would be why? You can use other layout managers to get place the button in different locations, you can use compound layouts (components within components within component using different layouts) to produce very complex results... – MadProgrammer Mar 05 '15 at 00:30
  • *"neither one of them answers my question."* Good. Java GUIs have to work on different OS', screen size, screen resolution etc. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). – Andrew Thompson Mar 05 '15 at 01:57

3 Answers3

2

Make use of appropriate layout managers to achieve your goals...

Layout

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class DetectMotion extends JFrame {

    private JLabel label = null;

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                DetectMotion frame = new DetectMotion();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public DetectMotion() {

        JPanel pnlButton = new JPanel();
        label = new JLabel("nothing");
        JButton btn = new JButton("Close");

        pnlButton.setLayout(new GridBagLayout());

        setTitle("Motion Detector");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        btn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (e.getActionCommand().equals("Close")) {
                    //TO-DO
                }
            }
        });

        JPanel panel = new JPanel() {

            @Override
            public Dimension getPreferredSize() {
                return new Dimension(200, 200);
            }

        };
        panel.setBackground(Color.RED);

        add(panel);

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        gbc.weighty = 1;

        pnlButton.add(label, gbc);

        gbc.weighty = 0;
        pnlButton.add(btn, gbc);
        add(pnlButton, BorderLayout.EAST);

        pack();
        setVisible(true);
    }

}

Layout

package javaapplication647;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class DetectMotion extends JFrame {

    private JLabel label = null;

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                DetectMotion frame = new DetectMotion();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public DetectMotion() {

        JPanel pnlButton = new JPanel();
        label = new JLabel("nothing");
        JButton btn = new JButton("Close");

        pnlButton.setLayout(new FlowLayout(FlowLayout.RIGHT));

        setTitle("Motion Detector");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        btn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (e.getActionCommand().equals("Close")) {
                    //TO-DO
                }
            }
        });

        JPanel panel = new JPanel() {

            @Override
            public Dimension getPreferredSize() {
                return new Dimension(200, 200);
            }

        };
        panel.setBackground(Color.RED);

        add(panel);
        pnlButton.add(label);
        pnlButton.add(btn);
        add(pnlButton, BorderLayout.SOUTH);

        pack();
        setVisible(true);
    }

}

Take a look at Laying Out Components Within a Container for more ideas

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
-1

If you want to put the item into a specific coordinate you have to use null Layout:

Example:

public void newClass(){

  public newClass(){

    JPanel panel = new JPanel();
    JButton button = new JButton("button1");


   panel.setLayout(null);
   button.setBounds(x,y,X,Y);
   panel.add(button);
}

public static void main(String[] args){
      newClass();
 }

}

Doing Without a Layout Manager (Absolute Positioning)

crAlexander
  • 376
  • 1
  • 2
  • 12
  • 2
    Avoid using `null` layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify – MadProgrammer Mar 05 '15 at 00:29
  • @MadProgrammer You mean i have problems for example if i make an app for tablet and the same for pc?That's other thing the null layout it's not so good but again it can do the work with some extra code... – crAlexander Mar 05 '15 at 00:34
  • 1
    Any time you run your code on a different system (even with the same OS), there are differences in how the output might be rendered, due to difference in hard, software, fonts, settings. The layout manager takes care of most of these issues automatically. Tablet and PC layout requirements are a world apart and I wouldn't be trying to generate a single view for both either, but's a different issue...If you code for Android or iOS, you will find that they also have there own layout managers to deal with the inconsistencies between hardware... – MadProgrammer Mar 05 '15 at 00:45
  • I want to have a button on a specific point on the background image. (In the pages of a book) I am hoping to get the image size, do some ratio calculations and set the button on the calculated position. I am thinking of using null layout for it. What do you guys think? Is this the right approach? – WVrock Sep 22 '19 at 11:23
-1

Your best bet is to use a Java Drag-and-Drop GUI builder like NetBeans. Particularly if you're interested in very specific positioning, nothing really beats a GUI builder.

jdb1015
  • 127
  • 6
  • 1
    *"Your best bet"* - That's very subjective, personally, the best bet is to understand how to use the available layout managers to there full power before relying on other tools, which generally just screw it up if you don't understand how the API actually works... – MadProgrammer Mar 05 '15 at 00:46