一个简单的java swing程序hello world,只有一个button
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);//设置可见,不然的话看不到 } }
有没有觉得有点奇怪,整个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.
效果如下:
嗯,有点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); } }
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。