[英]JButton should change background when pressed works ONLY when pressed and mouse not over button
我正在学习整个Java的基于事件的编程,除了在Java中创建和修改GUI之外,我遇到的最简单的第一件事就是在悬停,按下按钮时更改按钮的背景颜色。 ,启用等。
目前,我有关于该按钮的这段代码:
public class SampleForm extends JFrame implements ActionListener, ChangeListener{
private JPanel rootPanel;
private JButton fooButton;
private JButton barButton;
public SampleForm() {
super("Window");
setContentPane(rootPanel);
pack();
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(400, 400);
setVisible(true);
fooButton.addActionListener(this);
barButton.addActionListener(this);
fooButton.addChangeListener(this);
barButton.addChangeListener(this);
}
public void stateChanged(ChangeEvent e) {
AbstractButton abs = (AbstractButton) e.getSource();
ButtonModel model = abs.getModel();
if (e.getSource() == barButton)
if (model.isPressed()) {
barButton.setBackground(new Color(255, 255, 255));
} else if (model.isRollover()){
barButton.setBackground(new Color(174, 20, 70));
} else if (!model.isEnabled()) {
barButton.setBackground(new Color(0, 0, 0));
} else {
barButton.setBackground(new Color(60, 63, 65));
}
}
public void actionPerformed(ActionEvent event){
if (event.getSource() == fooButton){
barButton.setEnabled(true);
} else {
barButton.setEnabled(false);
}
}
我已经在IntelliJ中制作了表单,因此它可以处理添加到面板中的整个元素,这意味着表单可以完美呈现。 当我单击fooButton时,barButton被启用,并获得深灰色。 当我将鼠标悬停在它上面时,它会变成红色(到目前为止效果很好)。
但是,当我按下按钮时,按钮应该变成白色,但是变成默认的高亮度,青色并保持这种状态。 如果我一直按住按钮,但是将鼠标移离按钮(鼠标没有悬停在按钮上),则按钮会变成白色,就像按下时一样。
我尝试了许多属性并试图查明罪魁祸首,但是很明显,我缺少了一些东西。 我制作了一个.gif,向您展示我的意思:
请原谅我不稳定的鼠标在开头和结尾处摇晃:D
先感谢您!
将颜色更改为红色,您将发现问题不在于您的想法,而在于外观和感觉。 JButton的背景颜色不是您所想的。
问题是Swing使用MVC模型,绘画不是由JButton而是由其关联的ButtonUI进行的。 这个ButtonUI(实际上是它的子类)取决于外观,因此该按钮的绘制应符合当前的外观。
尝试这个:
class MyUI extends javax.swing.plaf.basic.BasicButtonUI {
protected void paintText(Graphics g, AbstractButton b, Rectangle textRect, String text) {
super.paintText(g,b,textRect,text);
}
}
public class SampleForm extends JFrame implements ActionListener, ChangeListener{
public SampleForm() {
super("Window");
fooButton = new JButton("jkljkl");
fooButton.addActionListener(this);
fooButton.addChangeListener(this);
fooButton.addMouseListener(this);
fooButton.setUI(new MyUI());
您将看到按钮将按照您喜欢的方式运行。
问题是“单击”按钮实际上是在按下并释放它。 因此,以下语句确定单击后按钮的外观:
} else {
barButton.setBackground(new Color(60, 63, 65));
}
希望有一个解决方法!
private boolean isClicked;
public SampleForm() {
super("Window");
isClicked = false;
setContentPane(rootPanel);
pack();
// insert the rest of the constructor body here
}
public void stateChanged(ChangeEvent e) {
AbstractButton abs = (AbstractButton) e.getSource();
ButtonModel model = abs.getModel();
if(e.getSource() == barButton)
if(model.isPressed() && !isClicked) {
barButton.setBackground(new Color(255, 255, 255));
isClicked = true;
} // insert the rest of the chained if-else statements here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.