简体   繁体   中英

Simple Swing example - method ordering results in no output

I'm a newbie to Swing. Yesterday I got stuck in this.

The code:-

JFrame f = new JFrame();
JButton b = new JButton("CLICK");
b.setBounds(130,100,100,40);
f.add(b);
f.setSize(400,500);//1st
f.setLayout(null);//2nd
f.setVisible(true);//3rd

When I run the above code, it displays an output of a button named "CLICK" placed inside a frame. But, if I reorder the last 3 methods like this:

f.setVisible(true);
f.setLayout(null);
f.setSize(400,500);

Then, the frame is displayed with no button inside it. why ?

The way to fix problems with not using a layout manager is to use a layout manager.

For example, this GUI uses layouts, margins and padding to achieve the same basic look as might be seen in the first GUI.

在此输入图像描述

import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;

public class ButtonGui {

    public static void main(String[] args) {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                JFrame f = new JFrame("Button GUI");
                JButton b = new JButton("CLICK");

                // adjust numbers to requirement
                b.setMargin(new Insets(12, 35, 12, 35));
                // since a button has a border, we need a panel to which
                // we can add a 2nd (empty) border.
                JPanel p = new JPanel(new GridLayout());
                // adjust numbers to requirement
                p.setBorder(new EmptyBorder(100, 130, 100, 130));
                p.add(b);
                f.add(p);
                f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                f.setLocationByPlatform(true);

                f.pack();
                f.setMinimumSize(f.getSize());

                f.setVisible(true);
            }
        };
        SwingUtilities.invokeLater(r);
    }
}

.setVisible(true) is always the last method call. you set the characteristics of your swing component, then use this method to tell it to display itself. HTH.

I was to suffering from same problem. try the code in the following manner..

f.setSize(800,800);
f.setLayout(null);
f.setVisible(true);

used in eclipse.works fine!!!

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