[英]Change font style of JTextField when JCheckbox is ticked and JButton is clicked
I don't get the result I want in this code, which is when I click on the checkbox then the JTextField's text should be bold, but It doesn't happen. 我在这段代码中没有得到想要的结果,这是当我单击复选框时,JTextField的文本应为粗体,但不会发生。 Help me please.
请帮帮我。
public class GUI extends JFrame{
//CheckBoxs
private JCheckBox box1;
private JCheckBox box2;
//Buttons
private JButton button1;
private JButton button2;
//Text
private JTextField fnam;
private JTextField snam;
public GUI(){
//basic
super("Program");
setLayout(new FlowLayout());
//add
box1 = new JCheckBox("Button 1 Activate");
box2 = new JCheckBox("Button 2 Activate");
add(box1);
add(box2);
button1 = new JButton("Select First Name");
button2 = new JButton("Select Second Name");
add(button1);
add(button2);
fnam = new JTextField("Mena Farid",10);
snam = new JTextField("Malak Mamdoh",12);
fnam.setEditable(false);
snam.setEditable(false);
fnam.setFont(new Font("Serif",Font.PLAIN,10));
snam.setFont(new Font("Serif",Font.PLAIN,12));
add(fnam);
add(snam);
//ActionListener and Events
Handler Handle = new Handler();
Handler2 Handle2 = new Handler2();
box1.addItemListener(
new ItemListener(){
public void itemStateChanged(ItemEvent e){
if(box1.isSelected())
button1.addItemListener(Handle);
}
}
);
box2.addItemListener(
new ItemListener(){
public void itemStateChanged(ItemEvent e){
if(box2.isSelected())
button2.addItemListener(Handle2);
}
}
);
}
private class Handler implements ItemListener{
public void itemStateChanged(ItemEvent f){
Font font = null;
font = new Font("Serif",Font.BOLD,10);
fnam.setFont(font);
}
}
private class Handler2 implements ItemListener{
public void itemStateChanged(ItemEvent f){
Font font2 = null;
font2 = new Font("Serif",Font.BOLD,12);
snam.setFont(font2);
}
}
}
The problem is The JTextField format is supposed to be turned into bold after I tick the checkbox and click the button but It doesn't happen. 问题是,在我勾选复选框并单击按钮之后,应该将JTextField格式变成粗体,但是不会发生。
@LuxxMiner ow.. Thanks you fixed my problem . @LuxxMiner ow ..谢谢您解决了我的问题。 I have been using ItemListener for button instead of ActionListener all the time and that was the problem.
我一直在使用ItemListener作为按钮而不是ActionListener,这就是问题所在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.