在Java中创建自定义JButton [英] Creating a custom JButton in Java

查看:651
本文介绍了在Java中创建自定义JButton的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法用你自己的按钮图形创建一个 JButton ,而不仅仅是按钮内的图像?

Is there a way to create a JButton with your own button graphic and not just with an image inside the button?

如果没有,是否有其他方法可以在java中创建自定义 JButton

If not, is there another way to create a custom JButton in java?

推荐答案

当我第一次学习Java时,我们不得不制作Yahtzee而且我认为创建自定义Swing组件和容器会很酷,而不是只绘制一个的JPanel 。当然,扩展 Swing 组件的好处是能够添加对键盘快捷键和其他辅助功能的支持,而这些功能只能通过 paint()方法打印漂亮的图片。然而,这可能不是最好的方式,但它可能是一个很好的起点。

When I was first learning Java we had to make Yahtzee and I thought it would be cool to create custom Swing components and containers instead of just drawing everything on one JPanel. The benefit of extending Swing components, of course, is to have the ability to add support for keyboard shortcuts and other accessibility features that you can't do just by having a paint() method print a pretty picture. It may not be done the best way however, but it may be a good starting point for you.

编辑8/6 - 如果从图像中看不出来,每个Die都是一个可以点击的按钮。这将把它移到下面的 DiceContainer 。查看源代码,您可以看到每个Die按钮都是根据其值动态绘制的。

Edit 8/6 - If it wasn't apparent from the images, each Die is a button you can click. This will move it to the DiceContainer below. Looking at the source code you can see that each Die button is drawn dynamically, based on its value.



< br>



这里是基本步骤:


  1. 创建一个扩展 JComponent
  2. 的类
  3. 在构造函数中调用父构造函数 super()

  4. 确保类实现 MouseListener

  5. 将它放在构造函数中:

  1. Create a class that extends JComponent
  2. Call parent constructor super() in your constructors
  3. Make sure you class implements MouseListener
  4. Put this in the constructor:

enableInputMethods(true);   
addMouseListener(this);


  • 覆盖这些方法:

  • Override these methods:

    public Dimension getPreferredSize()  
    public Dimension getMinimumSize()  
    public Dimension getMaximumSize()
    


  • 覆盖此方法:

  • Override this method:

    public void paintComponent(Graphics g)
    


  • 您必须使用的空间量绘制按钮时,由 getPreferredSize()定义,假设 getMinimumSize() getMaximumSize( )返回相同的值。我没有对此进行太多实验,但是,根据您用于GUI的布局,您的按钮可能看起来完全不同。

    The amount of space you have to work with when drawing your button is defined by getPreferredSize(), assuming getMinimumSize() and getMaximumSize() return the same value. I haven't experimented too much with this but, depending on the layout you use for your GUI your button could look completely different.

    最后,源代码。万一我错过了什么。

    And finally, the source code. In case I missed anything.

    这篇关于在Java中创建自定义JButton的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆