关于JRadioButton的ActionEvent事件&&相似代码提取公共方法

简单的点击复选框可以把复选框的内容上传到text框中,根据选中的状态选择是否显示
都选中的状态:
把yellow取消选中状态:
思路是选中时让text框得到所选的复选框的值添加到text中,还要得到text中已有的。

取消选中状态时使text中此时的内容为一个字符串,然后从中删除所选的值,用replaceAll("  "+ss, "")方法,两个参数,意思是用后者替换前者,即用“”替换“要删除的字符”,相当于删除!
整体代码如下:
package base.swing;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import org.omg.CORBA.PRIVATE_MEMBER;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class JRadiobuttonDemo extends JFrame {
 private JPanel contentPane;
 private JTextField textField;
 
 
 
 /**
  * Launch the application.
  */
 public static void main(String[] args) {
  EventQueue.invokeLater(new Runnable() {
   public void run() {
    try {
     JRadiobuttonDemo frame = new JRadiobuttonDemo();
     frame.setVisible(true);
    } catch (Exception e) {
     e.printStackTrace();
    }
   }
  });
 }
 /**
  * Create the frame.
  */
 public JRadiobuttonDemo() {
  
  
  
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  setBounds(100, 100, 450, 300);
  contentPane = new JPanel();
  contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
  setContentPane(contentPane);
  contentPane.setLayout(null);
  
  
  
  JRadioButton rdbtnRed = new JRadioButton("red");
  
  sss(rdbtnRed);
  rdbtnRed.setBounds(64, 133, 55, 23);
  contentPane.add(rdbtnRed);
  
  JRadioButton rdbtnYellow = new JRadioButton("yellow");
  sss(rdbtnYellow);
  rdbtnYellow.setBounds(139, 133, 80, 23);
  contentPane.add(rdbtnYellow);
  
  JRadioButton rdbtnBlue = new JRadioButton("blue");
  sss(rdbtnBlue);
  rdbtnBlue.setBounds(241, 133, 55, 23);
  contentPane.add(rdbtnBlue);
  
  textField = new JTextField();
  textField.setBounds(100, 46, 136, 23);
  contentPane.add(textField);
  textField.setColumns(10);
 }
 /**
  * @param rdbtnRed
  */
 private void sss(JRadioButton rdbtnRed) {
  String ss =rdbtnRed.getText();
  
  rdbtnRed.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e) {
    if(rdbtnRed.isSelected()==true) {
     textField.setText(textField.getText()+"  "+ss);
    }else if (rdbtnRed.isSelected()==false) {
     String s = textField.getText();
     String s1 = "";
     s1=s.replaceAll("  "+ss, "");
     textField.setText(s1);
    }
   }
  });
 }
}
因为中间的相当一部分的代码重复,于是便把他们提取了出来,方法是用eclipse中的功能
1.选择所要提取方法的代码块

2.右键 refactor→extract method→添加名字和访问权限→OK


猜你喜欢

转载自blog.csdn.net/m943917709/article/details/79986560