1.概述

一个简单的java swing程序hello world,只有一个button

2.源码

import javax.swing.*;public class server{ public static void main(String[] args) { JFrame jFrame = new JFrame("title"); JButton button = new JButton("Test button"); jFrame.add(button);//把button添加到JFrame中 jFrame.setSize(300,300);//设置JFrame大小 jFrame.setVisible(true);//设置可见,不然的话看不到 }}

3.第一次修改

有没有觉得有点奇怪,整个button占满了窗口?
没错,少了一个JPanel:

import javax.swing.*;public class server{ public static void main(String[] args) { JFrame jFrame = new JFrame("title"); JPanel jPanel = new JPanel(); JButton button = new JButton("Test button"); jPanel.add(button); jFrame.setContentPane(jPanel); jFrame.setSize(300,300); jFrame.setVisible(true); }}

添加一个JPanel,把Button添加到JPanel中,然后设置JFrame的contenPane.
效果如下:

4.第二次修改

嗯,有点hello world的样子了,但是你有没有点击过左上角的x按钮?

点了之后,这个东西是"消失"了,但是在后台还在运行着,所以...

jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

需要这样设置它的默认关闭操作.

另一个修改就是对它居中显示,要不然的话总是启动的时候在左上角.

很简单,一行就可以了.

jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

完整代码:

import javax.swing.*;public class server{ public static void main(String[] args) { JFrame jFrame = new JFrame("title"); JPanel jPanel = new JPanel(); JButton button = new JButton("Test button"); jPanel.add(button); jFrame.setContentPane(jPanel); jFrame.setSize(300,300); jFrame.setLocationRelativeTo(null); jFrame.setVisible(true); jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }}