简体   繁体   English

为什么不能在JPanel上调整JButton的大小或位置?

[英]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. 抱歉,如果代码有点像妈妈的意大利面,但我无法破解此cookie>。>即使将布局设置为null,它也不会移动。 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? 关于如何使此JButton不仅移动到窗口中间,还可以200乘200像素的任何建议?

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? 关于如何使此JButton不仅移动到窗口中间,还可以200乘200像素的任何建议?

I can think of a few, none of which use null layouts 我可以想到一些,没有一个使用null布局

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. 您可以使用它们的组合,也许使用EmptyBorderGridBagConstraints进一步约束布局。

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. 避免使用null布局,像素完美布局是现代ui设计中的一种幻觉。 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 Swing旨在与布局经理为核心一起工作,舍弃这些问题不会导致问题和问题的终结,您将花费越来越多的时间来尝试纠正

And because it's always a fun read, Why is it frowned upon to use a null layout in SWING? 并且由于它总是很有趣的阅读, 为什么在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 如果要手动定义任何组件大小,则必须设置母组件的布局:null,因此必须将Jframe布局设置为null来定义Jpanel的大小和位置,然后必须将JPanel布局设置为null来定义其中的Jbutton大小和位置。

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 ... 当您以空布局Jpanel或Jframe添加组件时,不要忘了定义大小和位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM