在設計GUI的程式時
首要的工作就是排版
JAVA有許多的排版樣式
在此我們使用的是 GridBagLayout
特點是排版的樣式就像是棋盤格子一樣
首先我們要先對排版樣式做一些設定
於程式開始時宣告框架
private JFrame frame;
並在建構子的地方建立框架
frame = new JFrame();
主程式的部分設定框架的屬性
frame.setSize(600, 160);
frame.setLayout(new GridBagLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
接下來我們要加入元件到視窗中
假設我們要加入的是Label
那麼我們可以這樣寫
JLabel n0 = new JLabel(name[0]);
GridBagConstraints c0 = new GridBagConstraints();
c0.gridx = 0;
c0.gridy = 0;
c0.gridwidth = 1;
c0.gridheight = 1;
c0.weightx = 0;
c0.weighty = 0;
c0.fill = GridBagConstraints.NONE;
c0.anchor = GridBagConstraints.WEST;
frame.add(n0, c0);
這裡我們分成三個部份看
首先是宣告Label物件
於是我們寫
JLabel n0 = new JLabel(name[0]);
第二部分是定義排版規則
GridBagConstraints c0 = new GridBagConstraints();
c0.gridx = 0;
c0.gridy = 0;
c0.gridwidth = 1;
c0.gridheight = 1;
c0.weightx = 0;
c0.weighty = 0;
c0.fill = GridBagConstraints.NONE;
c0.anchor = GridBagConstraints.WEST;
最後一部分是將物件加入框架中
frame.add(n0, c0);
第一個參數欄位是要加入的元件, 第二個欄位是他的排版規則
排版規則可以重複使用
例如如果要批次的加入按鈕的話
可以這樣寫
for (int i = 0; i < 7; i++) {
JButton n5 = new JButton(name[i + 3]);
GridBagConstraints c5 = new GridBagConstraints();
c5.gridx = i;
c5.gridy = 2;
c5.gridwidth = 1;
c5.gridheight = 1;
c5.weightx = 0;
c5.weighty = 0;
c5.fill = GridBagConstraints.BOTH;
c5.anchor = GridBagConstraints.CENTER;
frame.add(n5, c5);
}
這樣子就可以重複使用c5 這個規則了
Note 到這邊
謝謝大家
2013年1月17日 星期四
2013年1月3日 星期四
如何利用Getter 來取得Array的第m個位置的值
寫過C++的朋友
可能會覺得我這個問題問得很智障
不知所云
要取得Array第m的值
不就用 temp = Array[m]; 這樣就好了嗎
我要說的是
在JAVA, 很注重於資料的存取
private 的資料是封裝在Class裡面
一般人是無法隨意存取的
我們必須有良好的使用習慣, 利用set() 或者是 get() 這類的function 來拿資料
如果要取得Array 的第 m 個值的話
可以用下列語法
-------------------------------------------------
假設我們的get function 長這樣
可能會覺得我這個問題問得很智障
不知所云
要取得Array第m的值
不就用 temp = Array[m]; 這樣就好了嗎
我要說的是
在JAVA, 很注重於資料的存取
private 的資料是封裝在Class裡面
一般人是無法隨意存取的
我們必須有良好的使用習慣, 利用set() 或者是 get() 這類的function 來拿資料
如果要取得Array 的第 m 個值的話
可以用下列語法
-------------------------------------------------
假設我們的get function 長這樣
public
char
[] getArray() {
return
cArray;
}
他會回傳一個 char型態的array
於是
我們可以這樣寫
cs[i] = getArray()[m];
這行的意思就代表
cs[i] = cArray[m];
That's all
謝謝大家
巧用建構子(Constructor)
物件生成的時候
會先呼叫建構子來設定屬性
如果沒有撰寫建構子的話
Compiler 會執行預設建構子(Default Constructor)
預設建構子是不會做任何的事情的
建構子大概長得像下面這樣
會先呼叫建構子來設定屬性
如果沒有撰寫建構子的話
Compiler 會執行預設建構子(Default Constructor)
預設建構子是不會做任何的事情的
建構子大概長得像下面這樣
public
Encrypt() {}
如果有參數的話會像這樣
public
Encrypt(
int
a,
int
b,
int
n,
char
c,
int
dif) {
this
.a = a;
this
.b = b;
this
.n = n;
this
.c = c;
this
.diff = dif;
setArray();
}
然而本篇提到的妙用
是指利用this()也可以當作
呼叫運算子
像是下面這樣
public
Encrypt(
int
a,
int
b) {
this
(a, b,
26
,
'a'
,
97
);
}
等同是呼叫
public
Encrypt(
int
a,
int
b,
int
n = 26,
char
c = 'a',
int
dif = 97) {
this
.a = a;
this
.b = b;
this
.n = n;
this
.c = c;
this
.diff = dif;
setArray();
}
蠻酷炫的!!
訂閱:
文章 (Atom)