[英]setFont() issue
我有两个按钮可以编辑文本中的字体。 粗体按钮和斜体按钮分别起作用,但不能正常工作。 我怎样才能使按钮工作于蜂鸣器? (粗体+斜体)
final JToggleButton boldbuttonpage1 = new JToggleButton("");
boldbuttonpage1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(boldbuttonpage1.isSelected()){
textpage1.setFont(new Font("Arial", Font.BOLD, 12));
}
else textpage1.setFont(new Font("Arial", Font.PLAIN, 12));
}
});
boldbuttonpage1.setBounds(21, 32, 27, 23);
gtapage1.add(boldbuttonpage1);
final JToggleButton italicbuttonpage1 = new JToggleButton("");
italicbuttonpage1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(italicbuttonpage1.isSelected()){
textpage1.setFont(new Font("Arial", Font.ITALIC, 12));
}
else textpage1.setFont(new Font("Arial", Font.PLAIN, 12));
}
});
italicbuttonpage1.setBounds(21, 93, 27, 23);
gtapage1.add(italicbuttonpage1);
当您通过按一下按钮设置字体时,将覆盖先前的字体,从而消除了先前按下按钮时可能产生的任何影响。 就我自己而言,我会让两个ActionListener(或ItemListener)都调用相同的方法,该方法检查两个按钮的状态并相应地将字体设置为按钮值。
另外,根据我的评论,摆脱Eclipse标签,而在问题中添加Swing标签,这样就不会误导任何人。 Eclipse只是您用作IDE的工具,与您的问题无关。
顺便说一句,您不应设置组件的边界或使用空布局,而应使用适当的布局管理器。
编辑
你问:
一种检查按钮状态的方法? 您能详细说明一下吗?
您已经知道如何通过isSelected()
方法调用来检查按钮的状态。 好吧,不要同时按下一个按钮就只检查一个按钮,而是要同时检查两个按钮。 实际上,您可以为两个按钮提供相同的ActionListener:
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
// check selected states of both button one and two and set font accordingly
// you can use if (foo && bar) {...}
// else if (foo) {...}
// else if (bar) {...}
// else {.. default...}
}
};
button1.addActionListener(actionListener);
button2.addActionListener(actionListener);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.