在"JTextFields"中,有没有办法让用户选择使文本字段可编辑。默认大小写为不可编辑。查看详细信息。



当用户按下按钮(我创建的)时,它会使TextField可编辑。首先,我在构造函数中使用if条件作为:
if(button.isSelected()) TextField.isEditable(true); else TextField.isEditable(false);
但是,这给了我一个错误。然后,我在一个参数为ActionEvent的方法中使用相同的语句(允许用户决定是否要使文本可编辑),这是ActionListener实现的另一个方法。但这也带来了错误
在对按钮应用操作之前,给出代码和输出:代码如下所示
输出

package Radio_Button;
import java.awt.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Radio_Buttons extends JPanel{
private JRadioButton bold;
private JRadioButton italic;
private JRadioButton both;
private JRadioButton plain;
private ButtonGroup group;
private JTextField TextField;
private JButton button;
public Radio_Buttons(){
//Declare all radio buttons
plain = new JRadioButton("Plain",false);
bold = new JRadioButton("Bold", false);
italic = new JRadioButton("Italic", false);
both = new JRadioButton("Bold+Italic", false);
//Declare Text Field
TextField = new JTextField("The quick brown fox jumps over the lazy dog.",40);
TextField.setFont(new Font("Chiller", Font.PLAIN, 30));
//For button
button = new JButton("Push to edit");


//Add in panel
add(bold);
add(italic);
add(both);
add(plain);
add(TextField);
add(button);
//Make a family of radiobuttons so they can understand each others. 
group = new ButtonGroup();
group.add(bold);
group.add(italic);
group.add(both);
group.add(plain);

RadioListener listener = new RadioListener();
bold.addActionListener(listener);
italic.addActionListener(listener);
plain.addActionListener(listener);
both.addActionListener(listener);
setBackground(Color.yellow);
setPreferredSize(new Dimension(800,500));
}
private class RadioListener implements ActionListener{
public void actionPerformed(ActionEvent event){
int source = 0;
if (bold.isSelected()) {source =Font.BOLD; }
else if (italic.isSelected()) {source = Font.ITALIC; }
else if (both.isSelected()){source = Font.BOLD+Font.ITALIC; }
else {source = Font.PLAIN; }
TextField.setFont(new Font("Chiller", source, 30));
}
}
public static void main (String [] args){
JFrame frame = new JFrame("Quote Options");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Radio_Buttons panel = new Radio_Buttons();
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}
  1. 第一件事。花一些时间来理解有意义的"变量"名称和命名约定。例如,像TextField这样的变量名是无编号

  2. 在您的示例中,默认情况下TextField本身处于启用状态。用"可编辑"初始化为false,如下所示:

    TextField.setEditable(false);

  3. 将监听器添加到您的按钮并更改Textflied的可编辑性,如下所示

button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
TextField.setEditable(true);
}
});

最新更新