使用null布局的JFrame非常小 [英] JFrame very small using null layout

查看:348
本文介绍了使用null布局的JFrame非常小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我正在编写一个简单的程序来显示一个框架。
但是当我输入setLayout(null)时,框架变得非常小;
但是如果我忽略这个命令,按钮总是在顶部中心
有人可以指出我的错误吗?

Hi I am writing a simple program to display a frame. However the frame turns out real small when I type setLayout(null); But if i ignore this command, the button is always at the top center Can some one point out my error?

import java.io.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;

class theframe {

    private static void create() {
        JFrame frame = new JFrame("FrameDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Insets insets = frame.getInsets();
        frame.setSize(500 + insets.left + insets.right, 350 + insets.top + insets.bottom);
        add(frame.getContentPane()); //my function add
        frame.pack();
        frame.setVisible(true);
    }

    public static void add(Container pane) {
        pane.setLayout(null);
        Insets insets = pane.getInsets();

        JPanel p1 = new JPanel();
        p1.setPreferredSize(new Dimension(500, 350));

        JButton b1 = new JButton("one");
        Dimension size = b1.getPreferredSize();
        b1.setBounds(25 + insets.left, 5 + insets.top, size.width, size.height);

        pane.add(p1);
        p1.add(b1);
    }

    public static void main(String Args[]) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                create();
            }
        });
    }
}


推荐答案

你用绝对定位( null 布局)调用 pack()方法,你应该使用LayoutManager而不是使用将布局设置为 null

You're calling pack() method with absolute positioning (null layout), you should use LayoutManager instead of using setting the layout to null.

只需删除此行:

pane.setLayout(null);

注意:接受我的建议并了解自己 LayoutManagers ,因为如果你拒绝学习,你可能会去 null 布局,是的,它更容易,但强烈建议不要使用它。

NOTE: take my advice and learn yourself LayoutManagers, because if you refuse to learn, you'll probably go to null layout, yes,it is easier but highly recommended to not use it.

你必须知道的一些基本事项:

Some basic things you must know:


  1. <的默认布局code> JFrame 是 BorderLayout ,您只能在五个位置放置您的组件,如链接所示。

  2. FlowLayout 是每个JPanel的默认布局管理器。它只是在一行中放置组件,如果它的容器不够宽则开始一个新行。

  1. The default layout of JFrame is BorderLayout, which there only five locations you can put your components in as shown in the link.
  2. FlowLayout is the default layout manager for every JPanel. It simply lays out components in a single row, starting a new row if its container is not sufficiently wide.

毕竟,阅读更多关于 LayoutManagers 开始使用swing之前,相信我它会使你的工作非常容易,只需尝试一下,这太棒了。

After all, read more about LayoutManagers before starting using swing, belive me it makes your work very easier, just try it, it's amazing.

这篇关于使用null布局的JFrame非常小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆