Skip to content

Instantly share code, notes, and snippets.

@zengxs
Created May 9, 2016 06:10
Show Gist options
  • Save zengxs/058cad61523e398947048dba49da4a22 to your computer and use it in GitHub Desktop.
Save zengxs/058cad61523e398947048dba49da4a22 to your computer and use it in GitHub Desktop.
第18章 图形界面 -> 习题4 编写程序,在文本框中输入英文字母,再根据“大写字母按钮”或“小写字母按钮”将输入的内容进行转换, 并将转换后的结果显示在标签上。
import javax.swing.*;
import java.awt.*;
public class CharacterCast {
private JFrame frame;
private JTextField textField;
private JButton lowerButton;
private JButton upperButton;
private JLabel label;
public CharacterCast() {
prepareGUI();
frame.setVisible(true);
}
private void prepareGUI() {
// 窗口
frame = new JFrame("CharacterCast");
frame.setBackground(Color.LIGHT_GRAY);
frame.setSize(400, 200);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setLayout(null);
// textfield
textField = new JTextField();
textField.setBounds(10, 24, 360, 21);
// button
lowerButton = new JButton("转为小写");
upperButton = new JButton("转为大写");
lowerButton.setBounds(10, 60, 120, 30);
upperButton.setBounds(250, 60, 120, 30);
lowerButton.addActionListener(e -> label.setText(textField.getText().toLowerCase()));
upperButton.addActionListener(e -> label.setText(textField.getText().toUpperCase()));
// label
label = new JLabel();
label.setBounds(10, 100, 360, 21);
// pack
frame.add(textField);
frame.add(lowerButton);
frame.add(upperButton);
frame.add(label);
}
public static void main(String[] args) {
CharacterCast characterCast = new CharacterCast();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment