[問題] 在外部類裡使用main裡的AWT物件
想請問一下
我在將awt的物件在main method裡宣告和設定(frame.button.label.textarea...)
但因為main method一定要是static function
所以想請問一下各位要如何在外部類別裡使用main method裡的物件呢?
我想將main method裡的textarea在public void printPass裡使用
但我如果將txa.append(""+sortArray);加入到public void printPass裡
compile時就會出現錯誤...
想請問,我要如何才能讓txa.append(""+sortArray);
在public void printPass裡正常使用呢?
謝謝~~~~~~~~~~~~~~
以下是我簡略後的程式碼
import java.awt.*;
...
class InsertionSort {
private int[] data;
private static Random generator = new Random();
/*===Create array of given size and fill with random integers===*/
public InsertionSort(int size) {
data = new int[size];
//input random integers that range 10-99
for(int i = 0; i < size; i++) {
data[i] = 10 + generator.nextInt(90);
}
}
//InsertionSort 建構元
public void sort() {
int insert; //temporary variable to hold element to insert
//loop over data.length - 1 elements
for(int next = 1; next < data.length; next++) {
//儲存現在元素的值
insert = data[next];
//初始化位置放元素
int moveItem = next;
//search for place to put current element
while(moveItem > 0 && data[moveItem - 1] > insert) {
//shift element right one slot
data[moveItem] = data[moveItem -1];
moveItem--;
}
data[moveItem] = insert; //place inserted element
printPass(next, moveItem); //output pass of algorithm
}
}
/*================print a pass of the algorith===============*/
public void printPass(int pass, int index) {
System.out.print(String.format("after pass %2d: ", pass));
for(int i = 0; i < index; i++) {
System.out.print(data[i] + " ");
}
System.out.print(data[index] + "* ");
...
}
/*=======method to output values in array=======*/
public String toString() {
StringBuffer temporary = new StringBuffer();
for(int element : data) {
temporary.append(element + " ");
}
temporary.append("\n");
return temporary.toString();
}
}
public class teach_proj_sort extends Frame implements ActionListener {
static teach_proj_sort frm = new teach_proj_sort();
static Label lab = new Label();
static Button btn = new Button("Exit");
static TextArea txa;
public static void main(String args[]) {
InsertionSort sortArray = new InsertionSort(10);
/*=====================設定Frame=================================*/
frm.setLayout(null);
...
frm.add(lab);
frm.setResizable(false);
lab.setText("Sorting");
...
btn.setBounds(170,300,100,40);
frm.add(btn);
btn.addActionListener(frm);
txa = new TextArea(""+sortArray, 8, 14, TextArea.SCROLLBARS_VERTICAL_ONLY);
sortArray.sort(); //sort array
txa.setBounds(30,60,440,220);
frm.add(txa);
txa.append(""+sortArray);//show the array that has been sorted
txa.setEditable(false);
frm.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0); }});
}
...
}
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 163.14.69.24
討論串 (同標題文章)
java 近期熱門文章
PTT數位生活區 即時熱門文章