2017-08-26 102 views
3

点击我试图点击时让我的JButton停止其背景变化时被突出显示。我一直在阅读和测试其他questions的答案,如such,但没有人帮助过我。我对Java非常陌生,所以具体的细节会很有帮助,下面是我的代码和演示的内容。另外,如果这很重要,我正在运行Ubuntu。停止按钮在摆动

注意:如果我将鼠标悬停并悬停在上面,它也会触发背景更改。

import javax.swing.*; 
import java.awt.*; 

public class RaisedButton extends JButton{ 

    private String  text  =  ""; 
    private String  type  =  "default"; 


    public RaisedButton(String text, String type) { 
     this.text = text; 
     this.type = type; 
     __init__(); 
    } 

    private void foundations() { 
     NotoFont noto = new NotoFont(true); 
     this.setText(this.text.toUpperCase()); 
     this.setRolloverEnabled(false); 
     this.setFocusPainted(false); 
     this.setBorderPainted(false); 
     this.setFont(noto.get()); 
     this.setPreferredSize(new Dimension(108 + this.text.length() * 4, 37)); 
    } 

    private void default_type() { 
     this.foundations(); 
     this.setBackground(Color.decode("#FFFFFFF")); 
     this.setForeground(Color.decode("#000000")); 
    } 

    private void primary_type() { 
     this.foundations(); 
     this.setBackground(Color.decode("#00BCD4")); 
     this.setForeground(Color.decode("#FFFFFF")); 
    } 

    private void secondary_type() { 
     this.foundations(); 
     this.setBackground(Color.decode("#FF4081")); 
     this.setForeground(Color.decode("#FFFFFF")); 
    } 

    private void disabled_type() { 
     this.foundations(); 
     this.setBackground(Color.decode("#E5E5E5")); 
     this.setForeground(Color.decode("#B2A4A4")); 
    } 

    private void __init__() { 
     switch(this.type.toLowerCase()) { 
      case "default": 
       default_type(); 
       break; 
      case "primary": 
       primary_type(); 
       break; 
      case "secondary": 
       secondary_type(); 
       break; 
      case "disabled": 
       disabled_type(); 
       break; 
     } 
    } 
} 

示范什么发生的......

Demonstration

谢谢!

+1

你尝试设置自定义[按钮 - 模型(https://stackoverflow.com/a/22547218/3992939)? – c0der

+0

谢谢!我试过了,这次它似乎有效。我以前的尝试一定是做错了。 – tjkso

回答

0

在你foundations()方法,要么改变

this.setRolloverEnabled(true); 

将其设置为false为:

this.setRolloverEnabled(false); 

或删除分配给从JavaDoc,以退回到默认值false

详细setRolloverEnabled

+0

更改了它,但问题仍在发生。 – tjkso

+1

根据JavaDoc:“一些外观也许不实现翻转效果;它们将忽略此属性。” – c0der

1

尽量把这个在RaisedButton构造:通过添加 setModel(new FixedStateButtonModel());foundations()

setUI(new BasicButtonUI()); 
+0

试过了。它工作正常。 +1 – c0der