0
package swingtraining;

import static java.awt.Color.BLACK;
import static java.awt.Color.RED;
import java.awt.EventQueue;
import static java.awt.Font.BOLD;
import java.awt.Point;
import java.awt.Rectangle;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;



public class JFrameWithAButton extends JFrame {

public JFrameWithAButton(){

    setSize(400,400);
    setTitle("Swing is hard");
    setLocationRelativeTo(null);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setVisible(true);

    }

    public static void main(String args[]){

    JPanel Jp1 = new JPanel();

    Jp1.setOpaque(true);

    Jp1.setBackground(RED);

    JButton Jbt = new JButton();

    Jbt.setLayout(null);  
    Jbt.setSize(200,200);

    Jbt.setBounds(new Rectangle(new Point(200, 200)));
    Jbt.setText("Hello!");

    EventQueue.invokeLater(new Runnable(){

        public void run(){

            JFrameWithAButton ex = new JFrameWithAButton();
            ex.setVisible(true); 
            ex.add(Jp1);
            Jp1.add(Jbt);
            }
      });
 }

}

Sorry if the code's a bit mom's spaghetti-esque, but I just can't crack this cookie >.> Even with layout set to null it doesn't move. Any suggestions of how I get this JButton to not only move to the middle of the window but also grow 200 by 200 pixels?

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
Codster
  • 25
  • 6
  • You should start with [Laying Out Components Within a Container](http://docs.oracle.com/javase/tutorial/uiswing/layout/index.html) and then you should 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 26 '16 at 06:54

2 Answers2

2

Any suggestions of how I get this JButton to not only move to the middle of the window but also grow 200 by 200 pixels?

I can think of a few, none of which use null layouts

GridBagConstraints

GridBagConstraints

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

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

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.ipadx = 200;
            gbc.ipady = 200;

            add(new JButton("Hello"), gbc);
        }

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

    }

}

JButton#setMargin

JButton margins

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

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

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();

            JButton btn = new JButton("Hello");
            btn.setMargin(new Insets(100, 100, 100, 100));
            add(btn);
        }

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

    }

}

EmptyBorder

EmptyBorder

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;

public class Test {

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

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
            setLayout(new BorderLayout());
            setBorder(new EmptyBorder(50, 50, 50, 50));
            JButton btn = new JButton("Hello");
            add(btn);
        }

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

    }

}

You could use combination of them, maybe using an EmptyBorder and GridBagConstraints to further constrain the layout.

The great benefit of these examples, is, for the most part, if the font size changes or the rendering requirements for the fonts change, the layout is capable of compensating

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

And because it's always a fun read, Why is it frowned upon to use a null layout in SWING?

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

if you wanna define any component size manually you have to set the mother component's layout: null so you have to set Jframe layout null to define Jpanel size and location then you have to set JPanel layout null to define Jbutton size and location in it

final JPanel Jp1 = new JPanel();
    Jp1.setOpaque(true);
    Jp1.setBackground(RED);
    Jp1.setLayout(null);
    final JButton Jbt = new JButton();
    // Jbt.setLayout(null); not needed!
    Jbt.setBounds(10, 10, 100, 40);
    // Jbt.setBounds(new Rectangle(new Point(200, 200))); not in this style
    Jbt.setText("Hello!");
    Jp1.add(Jbt);
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            JFrameWithAButton ex = new JFrameWithAButton();
            ex.setVisible(true);
            ex.add(Jp1);
        }
    });
  • don't forget to define size and location both when you are adding a component in a null layout Jpanel or Jframe and ...
reza
  • 1,746
  • 6
  • 16
  • 32
  • [Why is it frowned upon to use a null layout in SWING?](http://stackoverflow.com/questions/6592468/why-is-it-frowned-upon-to-use-a-null-layout-in-swing) – MadProgrammer Mar 26 '16 at 07:00
  • Please stop giving out such dreadful advice until you figure out ***why*** it is dreadful advice. – Andrew Thompson Mar 26 '16 at 07:15