码迷,mamicode.com
首页 > 编程语言 > 详细

java swing hello world

时间:2019-12-05 15:59:22      阅读:94      评论:0      收藏:0      [点我收藏+]

标签:etl   def   new   tle   null   消失   alt   default   需要   

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);
    }
}

java swing hello world

标签:etl   def   new   tle   null   消失   alt   default   需要   

原文地址:https://blog.51cto.com/13996197/2456174

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!