package learning_swing;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
public class homework7 {
static int number[]=new int[5];
public static void main(String[] args) {
JFrame jf= new JFrame();
jf.setLayout(new GridLayout(1,2));
JPanel jp1 = new JPanel();
jp1.setLayout(new GridLayout(8,1));
JTextField a[]=new JTextField[5];
for(int i=0;i<5;i++) {
int j=i+1;
a[i]=new JTextField("请输入第"+j+"个数字");
number[i]=0;
jp1.add(a[i]);
}
JRadioButton b[]=new JRadioButton[3];
b[0]=new JRadioButton("原始数据");
b[1]=new JRadioButton("冒泡排序(从小到大)");
b[2]=new JRadioButton("选择排序(从大到小)");
ButtonGroup bu= new ButtonGroup();bu.add(b[0]);bu.add(b[1]);bu.add(b[2]);
for(int i=0;i<3;i++) jp1.add(b[i]);
JTextArea jt1=new JTextArea(300,100);
JScrollPane js=new JScrollPane(jt1);
b[0].addActionListener(new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
String s="";
for(int i=0;i<5;i++) {
number[i]=Integer.parseInt(a[i].getText());
s+=number[i]+"\n";
}
jt1.setText(s);
}
});
b[1].addActionListener(new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
for(int i=0;i<5;i++) {
number[i]=Integer.parseInt(a[i].getText());
}
for(int i=0;i<5;i++) {
for(int j=0;j+1<5-i;j++) {
if(number[j]>number[j+1]) {
int t=number[j];
number[j]=number[j+1];
number[j+1]=t;
}
}
}
String s="";
for(int i=0;i<5;i++) s+=number[i]+"\n";
jt1.setText(s);
}
});
b[2].addActionListener(new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
for(int i=0;i<5;i++) {
number[i]=Integer.parseInt(a[i].getText());
}
for(int i=0;i<5;i++) {
int val=number[i];
int index=i;
for(int j=i;j<5;j++) {
if(number[j]>val) {
val=number[j];
index=j;
}
}
int t=number[index];
number[index]=number[i];
number[i]=t;
}
String s="";
for(int i=0;i<5;i++) s+=number[i]+"\n";
jt1.setText(s);
}
});
jf.add(jp1);jf.add(js);
jf.setBounds(500,250,400,400);
jf.setVisible(true);
jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
|