Ale*_*lex 3 java user-interface swing jcomponent mouselistener
我正在做一个我需要一些自定义摆动组件的项目.到目前为止,我已经制作了一个带有一系列图像的新按钮(Java Metal外观根本不适合我的UI).我已经MouseListener在这个新组件上实现了,这就是我的问题出现的地方.我的小部件在悬停时更改图像,单击等,除了我MouseListener将鼠标进入整个GridLayout容器而不是图像中.所以我有一个大约200*100的图像,周围的容器大约是400*200,mouseEntered当它进入那个GridLayout部分(甚至是它的空白部分)而不是在图像上方时会触发该方法.我怎样才能使它只在我将鼠标悬停在图像上时触发?我试过设置大小和边界和其他属性无济于事.
编辑:这是我的问题的演示.正如您所看到的(有些颜色非常相似),右下角按钮只需输入其中的部分即可突出显示GridlLayout.我只想在实际拍摄图像时突出显示,而不是GridLayout部分.

我不会添加MouseListener方法,因为它们只涉及切换显示的图像.
public customWidget()
{
this.setLayout(new FlowLayout());
try {
imageDef=ImageIO.read(new File("/home/x101/Desktop/buttonDef.png"));
imageClick=ImageIO.read(new File("/home/x101/Desktop/buttonClick.png"));
imageHover=ImageIO.read(new File("/home/x101/Desktop/buttonHover.png"));
current=imageDef;
} catch (IOException e)
{
e.printStackTrace();
}
this.addMouseListener(this);
}
protected void paintComponent(Graphics g)
{
super.paintComponents(g);
g.drawImage(current, 0, 0, current.getWidth(), current.getHeight(), null);
}
Run Code Online (Sandbox Code Playgroud)
编辑:添加代码部分
作为替代方案,请考虑按钮API,其中包括setRolloverIcon()"当光标经过按钮时按钮显示指定图标" 的方法.
附录:例如,
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class ButtonIconTest {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
private static void createAndShowGui() {
String base = "http://download.oracle.com/"
+ "javase/tutorial/uiswing/examples/components/"
+ "RadioButtonDemoProject/src/components/images/";
ImageIcon dog = null;
ImageIcon pig = null;
try {
dog = new ImageIcon(new URL(base + "Dog.gif"));
pig = new ImageIcon(new URL(base + "Pig.gif"));
} catch (MalformedURLException ex) {
ex.printStackTrace(System.err);
return;
}
JFrame frame = new JFrame("Rollover Test");
JPanel panel = new JPanel();
panel.add(new JLabel(dog));
panel.add(new JLabel(pig));
JButton button = new JButton(dog);
button.setRolloverIcon(pig);
panel.add(button);
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1801 次 |
| 最近记录: |