1. 程式人生 > 其它 >【Java】【元件及其事件處理】字串大小寫轉換

【Java】【元件及其事件處理】字串大小寫轉換

技術標籤:# Java題解

在這裡插入圖片描述
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("字串大小寫轉換");

    }
}

在這裡插入圖片描述