矩形 Java Swing 单选按钮?
我想在 Java Swing 应用程序中创建一组按钮,就像在绘图程序中的典型工具选项板中一样。也就是说,一组小方形按钮,每个按钮都包含一个图标,只有其中一个按钮被按下,当您按下另一个按钮时,第一个按钮将被取消选择。我想到了很多解决方案,但没有一个看起来很简单/优雅。
这听起来像是 JRadioButton 的工作,但如果您向其中添加一个 Icon,您仍然会得到小圆圈,这相当浪费空间。我想一个选择是为 JRadioButton 找到替代的外观或绘画代码。
另一种替代方法可能是将 JButton 添加到 ButtonGroup,可能将 JToggleButton.ToggleButtonModel 设置为模型,但这没有达到预期的效果,因为标准 JButton 的绘制代码在选择时不会使其保持按下状态。可能可以修改 JButton 代码来执行此操作。就像让它以与“按下”相同的方式绘画“选择”。
第三种选择是使用普通的 JButton,并添加一个通用的鼠标侦听器来保持它们按下或不按下,并在按钮之间传达更改。
有人可以建议实现目标的最佳方法吗?我错过的一个简单方法是最好的,但是关于这三种替代方案中哪一种最好的建议以及如何开始的指导也很有用。
I'd like to create a set of buttons in a Java Swing application like you get in a typical tool palette in a paint program. That is, a set of small square buttons, each containing an icon, only one of which is pressed down, and when you press another button, the first is deselected. I've thought of a number of solutions and none of them seem very easy/elegant.
This sounds like a job for JRadioButton, but if you add an Icon to that, you still get the small circle, which is fairly space inefficient. I guess an option would be finding an alternative Look and Feel or painting code for JRadioButton.
Another alternative might be to add JButton to a ButtonGroup, maybe setting a JToggleButton.ToggleButtonModel as the model, but that doesn't have the desired effect, as the painting code for a standard JButton does not keep it depressed when selected. Possibly the JButton code could be modified to do this. Like making it painting "selected" the same way as "pressed".
A third alternative would be to use normal JButton's, and add a common mouse listener that keeps them pressed or not, and communicates the changes between the buttons.
Can anyone advise on the best way to achieve the aim please? A simple method I've missed would be best, but advice on which of these three alternatives would be best and pointers on how to get started would be useful too.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
ButtonGroup
中的普通JToggleButton
怎么样?它不是抽象的,您可以使用Icon
实例化一个图标,并且在选择时它会保持按下状态。What about a plain
JToggleButton
in aButtonGroup
? It is not abstract, you can instantiate one with anIcon
, and it stays depressed while selected.请参阅 SwingSet2 演示:
http://java.sun.com/products/plugin /1.4/demos/jfc/SwingSet2/SwingSet2.html
单击工具栏上的第二个图标(带有复选框和单选按钮的图标),然后选择“Radio”按钮”。然后单击右侧面板上“显示选项”下的“绘制边框”。
演示的源代码位于您的 JDK 安装目录下,因此例如在我的 PC 上,它位于 \jdk1.6.0_01\demo\jfc\SwingSet2\src 下
See the SwingSet2 demo:
http://java.sun.com/products/plugin/1.4/demos/jfc/SwingSet2/SwingSet2.html
Click the second icon on the toolbar (the one twith the check box and radio button) then tab "Radio buttons". Then click on "Paint Border" on the right panel, under "Display Options".
Source code of the demo is under your JDK install dir, so for example on my PC it's under \jdk1.6.0_01\demo\jfc\SwingSet2\src