我想展示线性搜索在视觉上的运作方式。 我已经创建了ADT类和整数。我还有一个带有按钮的框架,当我点击fillButton时,它会生成一个随机整数数组,显示在一组按钮上。 当我点击findButton时,它会查找输入的具体数字。当我在遍历数组时,我想使相应的按钮改变颜色。
我创建了一个类似的程序,它迭代了一组按钮,并在它经过时改变了颜色。我曾经使用过Thread.sleep(),它只是主类。这次我有两节课,我不知道如何去做。我不知道如何在ADT类和GUI类之间建立连接。我之前使用过EventObjects和自定义EventListener,但这仅仅是为了存储对象。任何指向正确方向的帮助都表示赞赏。谢谢。
这是ADT课程的一部分
public class ADT {
private int[] a;
private int nElems;
private int SIZE = 60;
public ADT(){
a = new int[SIZE];
nElems=0;
}
public void initialPlacement(int index, int value,int initialCount){
a[index] = value;
nElems = initialCount;
}
public int linearSearch(int searchKey){
int index = 0;
for(int i = 0; i < nElems; i++){
if(getVal(i) == searchKey){
index = i;
break;
}
else{
index = -1;
}
}
return index;
}
这是GUI类的一部分
public NumberFrame(){///CONSTRUCTOR===========================
arr = new ADT();
//CREATE COMPONENTS
for(int i = 0; i < 60; i++){
listButtons[i] = new JButton(String.valueOf("_"));
}
for(int i = 0; i < 60; i++){
listLabels[i] = new JLabel(String.valueOf("["+i+"]"));
}
for(int i = 0; i < 60; i++){
listMiniPanels[i] = new JPanel();
listMiniPanels[i].add(listLabels[i]);
listMiniPanels[i].add(listButtons[i]);
}
fillButton.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
boolean sort = true;
if(linearRadio.isSelected()){
System.out.println("linear is checked");
fill(!sort);//fills half the array and array of buttons with random numbers, unsorted
}else if(binaryRadio.isSelected()){
System.out.println("binary is checked");
fill(sort);//fills half the array with random numbers and sorts it
}else{
JOptionPane.showMessageDialog(null, "Please check a sorting method");
}
}
})
findButton.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
int index= 0;
if(numberField.getText().equals("")){
System.out.print("Arr size = " + arr.size());
JOptionPane.showMessageDialog(null, "You did not enter a number");
}else {
try {
int searchKey = Integer.parseInt(numberField.getText());
if(linearRadio.isSelected()){
index = arr.linearSearch(searchKey);
listButtons[index].setBackground(Color.GREEN);
if(index > -1)
JOptionPane.showMessageDialog(null, "Found number " +searchKey + " @ index [" + index + "]");
else
JOptionPane.showMessageDialog(null, "No such number");
}else{
index = arr.binarySearch(searchKey);
if(index > -1)
JOptionPane.showMessageDialog(null, "Found number " + searchKey+ " @ index [" + index + "]");
else
JOptionPane.showMessageDialog(null, "No such number!");
}
} catch (NumberFormatException nfe) {
System.out.println("Arr size = " + arr.size());
JOptionPane.showMessageDialog(null, "Not an integer, pleas try again!");
}
}
}
});
}//=======CONSTRUCTOR END=============================