一個簡單的java swing程序hello world,只有一個buttonjava
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:3d
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.code
效果以下:server
嗯,有點hello world的樣子了,可是你有沒有點擊過左上角的x按鈕?blog
點了以後,這個東西是"消失"了,可是在後臺還在運行着,因此...圖片
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
須要這樣設置它的默認關閉操做.源碼
另外一個修改就是對它居中顯示,要否則的話老是啓動的時候在左上角.it
很簡單,一行就能夠了.io
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
完整代碼:class
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); } }