package day7yue12;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
public class ArrayMinValue2 extends JFrame {
private JPanel panel;
private JLabel label;
private JLabel label_1;
private JTextField textField;
public static void main(String[] args) {
ArrayMinValue2 a = new ArrayMinValue2();
a.setVisible(true);
}
public ArrayMinValue2() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setBounds(100, 100, 450, 149);
panel = new JPanel();
panel.setBorder(new EmptyBorder(5, 5, 5, 5));
this.setContentPane(panel);
this.setTitle("获取文本中最小值");
panel.setLayout(null);
textField = new JTextField();
textField.setBounds(6, 36, 414, 30);
panel.add(textField);
textField.setColumns(10);
JButton button = new JButton("点击");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// 匿名内部类可以直接使用成员方法,记住啦,背下来
do_button_actionPerformed();
}
});
button.setBounds(16, 76, 90, 30);
panel.add(button);
label = new JLabel("最小值:");
label.setBounds(116, 82, 304, 18);
panel.add(label);
label_1 = new JLabel("请在文本框中输入多个整数,以空格分开,比如:3 23 90 7");
label_1.setBounds(6, 6, 422, 18);
panel.add(label_1);
}
private void do_button_actionPerformed() {
String arrayStr = textField.getText().trim();
if (arrayStr.equals("")) {
JOptionPane.showMessageDialog(null, "请输入字符串");
return;
}
// 过滤非法输入
for (int i = 0; i < arrayStr.length(); i++) {
char charAt = arrayStr.charAt(i);
if (!Character.isDigit(charAt) && charAt != ' ') {
JOptionPane.showMessageDialog(null, "输入包含非法字符");
textField.setText("");
return;
}
}
String[] numStrs = arrayStr.split(" {1,}");
int[] numArray = new int[numStrs.length];
for (int i = 0; i < numArray.length; i++) {
numArray[i] = Integer.valueOf(numStrs[i]).intValue();
}
int min = numArray[0];
for (int i = 1; i < numArray.length; i++) {
if (numArray[i] < min) {
min = numArray[i];
}
}
label.setText("最小值:" + min);
}
}