0

Okay I want to place my button in a certain place on the screen. Is there any way to place it at an exact pixel location? Right now it places it to the far right of my screen. I have an image that I would want it to go over too.

import java.awt.AWTException;
import java.awt.FlowLayout;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.image.BufferedImage;
import java.awt.image.DataBuffer;
import java.awt.image.DataBufferInt;
import java.awt.image.WritableRaster;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

public class UnfollowGUI extends JFrame{

private JLabel label;
private JButton button;

private ImageIcon bgi;
private JLabel bgl;

public static Rectangle gameSquare;

public static boolean rock = true;
public static boolean runningMine = true;
public static int stray = 0;
public static int strayCount = 0;


public static void main(String[] args) {
    UnfollowGUI gui = new UnfollowGUI ();
    gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // when click x close program
    //gui.setSize(886, 266);
    gui.pack();
    gui.setVisible(true);
    gui.setTitle("Solid Cloud Inc - Twitter Unfolower");
}

public UnfollowGUI(){

    setLayout(new FlowLayout());

    bgi = new ImageIcon(getClass().getResource("tu.png"));
    bgl = new JLabel (bgi);
    add(bgl);

    ImageIcon start = new ImageIcon(getClass().getResource("start.png"));
    button = new JButton (start);
    button.setBorder(BorderFactory.createEmptyBorder());
    button.setContentAreaFilled(false);

    add(button);

    label = new JLabel ("");
    add(label);

    Events e = new Events();
    button.addActionListener(e);
}

public class Events implements ActionListener {


    public void actionPerformed(ActionEvent e) {

        if (e.getSource() == button) {
           label.setText("Searching");
           try {
            Unfollow();
        } catch (InterruptedException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        }
}

}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Luke Worthing
  • 101
  • 1
  • 4
  • 12

3 Answers3

3

Java GUIs might have to work on a number of platforms, on different screen resolutions & using different PLAFs. As such they are not conducive to exact placement of components.

To organize the components for a robust GUI, instead use layout managers (or combinations of them), along with layout padding & borders for white space.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
3

Yet another way to achieve what you describe can be done this way (there are many alternatives, but in the end, it all depends on how you want your components to be relatively positionned to each other and what happens when the size of the parent container changes):

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.net.MalformedURLException;
import java.net.URL;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class TestLoginGridBagLayout {

    protected void initUI() throws MalformedURLException {
        JFrame frame = new JFrame("Background image");
        frame.getContentPane().setBackground(Color.BLACK);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JLabel background = new JLabel(new ImageIcon(new URL("http://images2.layoutsparks.com/1/161318/city-lights-bridge-decoration.jpg")));
        background.setVerticalAlignment(JLabel.BOTTOM);
        background.setHorizontalAlignment(JLabel.LEFT);
        background.setLayout(new BorderLayout());
        frame.add(background);
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
        buttonPanel.setOpaque(false);
        buttonPanel.add(new JButton("Some button in the bottom left"));
        background.add(buttonPanel, BorderLayout.SOUTH);
        frame.pack();
        frame.setVisible(true);
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    new TestLoginGridBagLayout().initUI();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
            }
        });
    }

}
Guillaume Polet
  • 47,259
  • 4
  • 83
  • 117
0

You can place things in the exact place you want by not using a Layout Manager. This is called absolute positioning, and you can read a tutorial on it here: http://docs.oracle.com/javase/tutorial/uiswing/layout/none.html

Here's a snippet of code from inside that tutorial:

pane.setLayout(null);

JButton b1 = new JButton("one");
JButton b2 = new JButton("two");
JButton b3 = new JButton("three");

pane.add(b1);
pane.add(b2);
pane.add(b3);

Insets insets = pane.getInsets();
Dimension size = b1.getPreferredSize();
b1.setBounds(25 + insets.left, 5 + insets.top,
             size.width, size.height);
size = b2.getPreferredSize();
b2.setBounds(55 + insets.left, 40 + insets.top,
             size.width, size.height);
size = b3.getPreferredSize();
b3.setBounds(150 + insets.left, 15 + insets.top,
             size.width + 50, size.height + 20);

...//In the main method:
Insets insets = frame.getInsets();
frame.setSize(300 + insets.left + insets.right,
              125 + insets.top + insets.bottom);

That ends up looking like this:

enter image description here

Daniel Kaplan
  • 62,768
  • 50
  • 234
  • 356
  • but if u don't use a gui editor like mattise is highly discouraged not using layout manager :) – nachokk Jun 10 '13 at 17:06
  • @nachokk I don't know any other way to put a button at the exact pixels you want. – Daniel Kaplan Jun 10 '13 at 17:07
  • me neither but have to be careful a lot of magic numbers, if u dont have a gui editor is not useful. :) – nachokk Jun 10 '13 at 18:03
  • 1
    -1: advising using null Layout is always a bad advice (with a GUI editor or not). There are many techniques to put a component at an exact place (although this requirement is extremely rare). Most of the time, requirements are "I want this component next to this one", "I want a component to stretch below this one", etc... You have relative constraints rather than absolute ones. One of the main reason for that is that you don't know in advance the size of each component (different L&F, different screen resolutions, different DPI, etc...). All this is properly handled by LayoutManager's. – Guillaume Polet Jun 10 '13 at 19:07
  • @GuillaumePolet If this isn't answering his question, what is? If it is answering his question, but you don't recommend doing it, I don't see why that deserves a -1, because it's still answering his question. **The tutorial I linked to** says "Although it is possible to do without a layout manager, you should use a layout manager if at all possible". It's not like I'm saying, "You should do this in general". I'm just satisfying the requirements he gave. – Daniel Kaplan Jun 10 '13 at 19:25
  • 1
    IMOHO, an answer is valid if it fulfills the user requirement and if it is a good practice/approach. In this situation, it is easily doable with a LayoutManager (you can do it with an empty border, you could implement a custom LayoutManager that performs absolute positionning, `MigLayout` also supports this, ...) and advising to not use one is sending the OP down a very bad road. – Guillaume Polet Jun 10 '13 at 20:17
  • @GuillaumePolet Then write an answer to help the guy. – Daniel Kaplan Jun 10 '13 at 20:21
  • Okay I just want the button to be on the bottom left on top of an image. Does that change anything? – Luke Worthing Jun 10 '13 at 20:29