如何在 Java 的 JFrame 中按下鼠标时更改组件的颜色?
我正在使用 java.awt.graphics 库中的矩形在 java 中编码钢琴。当鼠标单击 JFrame 上的某个区域时,我使用鼠标监听器来播放每个按键的声音。
如何在单击时向面板添加形状,重新绘制,然后在用户释放鼠标时将键盘重新绘制回顶部?
I am coding a piano in java using rectangles from the java.awt.graphics library. I am using a mouselistener to play the sound of each individual key when the mouse clicks a certain area on the JFrame.
How would I add a shape to the panel upon clicking, repaint, then repaint the keyboard back over top when the user releases the mouse?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
考虑将 JLabels 添加到使用 GridLayout 的 JPanel。为每个 JLabel 提供一个 MouseListener,并在 mousePress/mouseRelease 上交换 ImageIcons,或者通过按下和释放来更改 JLabel 的背景。如果您选择后一种方法,您需要确保 JLabels opaque 属性设置为 true 以便显示背景颜色。
然后,对于黑键,您可以将上面的 JPanel 添加到 JLayeredPane 中,并在此之上添加另一个 JPanel,其中包含以相同方式运行的黑键。
另外,您需要注意在后台线程中“播放”任何音符,例如可以使用 SwingWorker 获得的音符,以免占用 Swing 事件线程并完全冻结您的程序。
Consider adding JLabels to a JPanel that uses GridLayout. Give each JLabel a MouseListener and either swap ImageIcons on mousePress/mouseRelease or change the JLabel's background with press and release. If you go the latter route, you'll want to make sure that the JLabels opaque property is set to true so that the background colors show.
Then for the black keys, you can add the above JPanel to a JLayeredPane and on top of this, add another JPanel that holds the black keys that function in the same way.
Also, you'll want to take care to "play" any notes in a background thread, such as can be obtained with a SwingWorker so as not to tie up the Swing event thread and completely freeze your program.
考虑解决方案: source
它可能不完全是您所追求的,但它可能会让您了解如何解决你的问题。我花了很长时间才弄清楚如何使用
JLayeredPane
而不设置空布局,但最终这是我能想到的最好的。此外,还假设了声音文件的一些命名约定。 :pConsider solution: source
It might not be exactly what you're after, but it might give you an idea of how to approach your problem. It took me a long time to figure out how to use
JLayeredPane
without setting a null layout, but in the end this was the best I could come up with. Also, assumed some naming conventions for your sound files. :p