我正在用java语言设计排序算法模拟器。当我设计我面临交换按钮问题时。实际上他们根本没有移动或改变现在的位置。
这是我的代码:
import javax.swing.JButton;
import javax.swing.JOptionPane;
public class mainGUI extends javax.swing.JFrame implements Runnable{
Thread a;
JButton[] num_array;
int []arr;
int Swap;
public mainGUI() {
initComponents();
a = new Thread(this);
}
private void sortBtnActionPerformed(java.awt.event.ActionEvent evt) {
arr = new int[6];
if (num1.getText().isEmpty()){
JOptionPane.showMessageDialog(null, "Can't leave this field empty");
num1.grabFocus();
}
else if(num2.getText().isEmpty())
{
JOptionPane.showMessageDialog(null, "Can't leave this field empty");
num2.grabFocus();
}
else if(num3.getText().isEmpty())
{
JOptionPane.showMessageDialog(null, "Can't leave this field empty");
num3.grabFocus();
}
else if(num4.getText().isEmpty())
{
JOptionPane.showMessageDialog(null, "Can't leave this field empty");
num4.grabFocus();
}
else if(num5.getText().isEmpty())
{
JOptionPane.showMessageDialog(null, "Can't leave this field empty");
num5.grabFocus();
}
else if (num6.getText().isEmpty())
{
JOptionPane.showMessageDialog(null,"Can't leave this field empty");
num6.grabFocus();
}
else
{
arr[0] = Integer.parseInt(num1.getText());
arr[1] = Integer.parseInt(num2.getText());
arr[2] = Integer.parseInt(num3.getText());
arr[3] = Integer.parseInt(num4.getText());
arr[4] = Integer.parseInt(num5.getText());
arr[5] = Integer.parseInt(num6.getText());
numB1.setText(num1.getText());
numB2.setText(num2.getText());
numB3.setText(num3.getText());
numB4.setText(num4.getText());
numB5.setText(num5.getText());
numB6.setText(num6.getText());
num_array = new JButton[]{numB1,numB2,numB3,numB4,numB5,numB6};
Swap = 1;
a.start();
}
}
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new mainGUI().setVisible(true);
}
});
}
@Override
public void run() {
if (Swap == 1)
{
int i,j,key;
for(i = 1;i<arr.length;i++)
{
key = arr[1];
j = 1;
while (j>0 && arr[j -1] > key)
{
arr[j] = arr[j - 1];
j--;
try {
swap2(j,j + 1);
keyprinting(key);
} catch (Exception e) {
JOptionPane.showConfirmDialog(null,"Error Occured !.Please Try again.!");
}
}
arr[j] = key;
}
}
//a.start(); //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
private void swap2(int n1, int n2) throws InterruptedException{
for(int i = 0;i<20;i++)
{
num_array[n1].setLocation(num_array[n1].getLocation().x,num_array[n1].getLocation().y);
num_array[n2].setLocation(num_array[n2].getLocation().x,num_array[n2].getLocation().y);
}
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
private void keyprinting(int key) {
System.out.println(key);
}
}