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

查看:30
本文介绍了在 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.



以下是基本步骤:

  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天全站免登陆