MyFrame:
package com.itheima;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MyFrame extends JFrame {
JTextField text1, text2;
JButton button;
ButtonGroup buttonGroup;
JRadioButton radio1, radio2;
PoliceListen policeListen;
public MyFrame() {
init();
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
void init() {
setLayout(new FlowLayout());
text1 = new JTextField(16);
text2 = new JTextField(16);
button = new JButton("转换");
buttonGroup = new ButtonGroup();
radio1 = new JRadioButton("大写");
radio2 = new JRadioButton("小写");
radio1.setActionCommand("大写");
radio2.setActionCommand("小写");
add(text1);
buttonGroup.add(radio1);//设置命令字符串
buttonGroup.add(radio2);
add(button);
add(radio1);
add(radio2);
add(text2);
policeListen = new PoliceListen();
button.addActionListener(policeListen);
}
private class PoliceListen implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
String command = buttonGroup.getSelection().getActionCommand();//获取按钮组中被挑选的组件命令字符串
boolean upper = command.equals("大写");
String s = text1.getText();
if (upper) {
text2.setText(s.toUpperCase());
} else
text2.setText(s.toLowerCase());
}
}
}
Main:
package com.itheima;
public class Main {
public static void main(String[] args) {
MyFrame myFrame = new MyFrame();
myFrame.setBounds(100,100,240,160);
myFrame.setTitle("字符串大小写转换");
}
}