java swing編程入門代碼編寫(java編程入門)_java

來源:互聯網
上載者:User

Swing編程基本流程

第一步: 取得主表單

複製代碼 代碼如下:

JFrame jf = new JFrame("Demo1");

第二步:獲得主表單的容器

複製代碼 代碼如下:

Container c = jf.getContentPane();

第三步:設定容器布局

複製代碼 代碼如下:

c.setLayout(new FlowLayout(FlowLayout.LEFT,20,20));

第四步:添加組件及設定組件屬性

複製代碼 代碼如下:

JLabel label1 = new JLabel("Hello World!");
JLabel label2 = new JLabel("Bye World!");
label1.setBackground(Color.BLUE);
label1.setOpaque(true);

第五步:設定表單內容,關閉主表單,退出程式

複製代碼 代碼如下:

jf.setSize(200, 100); //設定主表單大小
jf.setVisible(true);

jf.setResizable(false);

jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//設定表單關閉時,退出程式

另:
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);也可使用以下代碼代替

jf.addWindowListener(new WindowAdapter() {

@Override
     public void windowClosing(WindowEvent e) {
                super.windowClosing(e);
                System.exit(0);
            }
});



3.個人的一點學習心得:

*學習Swing,做出簡單的小軟體,並不困難,想要做的好看,就需要對布局有較深的研究!

*使用Swing的一個用處:Swing雖然已經有些過時了,但可以做些小工具,輔助工作等,也可以自娛自樂。個人對電腦圖形介面挺感興趣。

*Swing組件使用一些設計模式,是挺值得研究一下,對編程挺要用處!

*學習東西貴在堅持,很多工具包都是類似的,對一種有所精深,其他亦能觸類旁通!

4.附一個在Youtobe視頻中學習到的一個Swing程式:

複製代碼 代碼如下:

package com.ting723.www;

 

import java.awt.Container;

import java.awt.GridLayout;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

 

import javax.swing.ImageIcon;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JPanel;

 

public class Demo10XOGame extends JFrame{

 

JPanel jp = new JPanel();

 

public Demo10XOGame() {

 Container c = this.getContentPane();

 c.add(jp);

 jp.setLayout(new GridLayout(3, 3));

 for (int i = 0; i < 9; i++) {

 XOButton jb = new XOButton();

 jp.add(jb);

 }

 

 this.setSize(500, 500);

 this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

 this.setLocationRelativeTo(null);

 this.setVisible(true);

}

 

public static void main(String[] args) {

 

 new Demo10XOGame();

}

 

 

}



複製代碼 代碼如下:

class XOButton extends JButton implements ActionListener {

private ImageIcon X, O;

byte value = 0;

public XOButton() {

 X = new ImageIcon(this.getClass().getResource("x.png"));

 O = new ImageIcon(this.getClass().getResource("o.png"));

 this.addActionListener(this);

 

}

 

@Override

public void actionPerformed(ActionEvent e) {

 

 value++;

 value %= 3;

 switch (value) {

 case 0:

 setIcon(null);

 break;

 case 1:

 setIcon(X);

 break;

 case 2:

 setIcon(O);

 }

}

}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.