简体   繁体   中英

Why can't I resize or relocate my JButton on my JPanel?

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?

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

GridBag约束

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页边距

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

空边界

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?

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 ...

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