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) {
// TODO Auto-generated method stub
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) {
// TODO Auto-generated method stub
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) {
// TODO Auto-generated method stub
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) {
// TODO Auto-generated method stub
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);
}
}
中国地质大学北京信息管理与信息系统——Java程序设计第二次上机part6在界面排序数组并输出,实验2.3
最新推荐文章于 2024-11-04 20:33:37 发布