0

我想创建具有自定义外观的按钮。我已经将不同的图像设置为正常、鼠标悬停、鼠标单击、按钮禁用等按钮的背景。我创建了自己的类,扩展了 javax.swing.JButton 并覆盖了paintComponent 方法。我如何更改所有上述给定状态的按钮背景。

4

4 回答 4

4

In addition to Steve De Caux's answer, you can:

  1. Add a MouseListener which changes an enum variable, let's call it state on your extended JButton
  2. In your overridden paintComponent take into consideration the current state and paint different backgrounds. Like

    if (!getModel().isEnabled()) {
    } else if (state == ButtonState.MOUSE_OVER) {
    } else if (state == ButtonState.MOUSE_CLICKED) {   
    }
    
于 2009-12-12T08:21:44.473 回答
3

JButton has a series of simple set methods for rollover, pressed, selected, disabled and disabled selected states - for example

button.setPressedIcon(new ImageIcon("images/button-down.png")

the other methods are :

button.setRolloverIcon()
button.setSelectedIcon()
button.setRolloverSelectedIcon()
button.setDisabledIcon()
button.setDisabledSelectedIcon()

...have fun !

By the way, O'Reilly has a fun book called Swing Hacks with lots of little goodies for playing with swing : Swing Hacks

于 2009-12-12T08:20:20.993 回答
2

You could create a custom button UI delegate. This blog entry: http://blog.elevenworks.com/?p=4 has an example for a custom tabbed pane, but the principle is the same. Extend BasicButtonUI, implement the custom rendering your want for the button, and then call setUI() on the button.

This will probably take longer to implement than using the existing button API methods to change the appearance, but it gives you a lot more control.

于 2009-12-12T08:29:26.250 回答
0
ImageIcon icon = new ImageIcon("images/icon.gif");
JButton button = new JButton(icon);
于 2009-12-12T07:44:31.273 回答