简体   繁体   English

在Java的JFrame中按下鼠标时,如何更改组件的颜色?

[英]How can I change colors of components when the mouse is pressed in a JFrame in Java?

I am coding a piano in java using rectangles from the java.awt.graphics library. 我正在使用java.awt.graphics库中的矩形在Java中编码钢琴。 I am using a mouselistener to play the sound of each individual key when the mouse clicks a certain area on the JFrame. 当鼠标单击JFrame上的某个区域时,我正在使用Mouselistener播放每个按键的声音。

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? 当用户释放鼠标时,如何在单击,重新粉刷然后在顶部重新粉刷键盘时向面板添加形状?

Consider adding JLabels to a JPanel that uses GridLayout. 考虑将JLabel添加到使用GridLayout的JPanel中。 Give each JLabel a MouseListener and either swap ImageIcons on mousePress/mouseRelease or change the JLabel's background with press and release. 给每个JLabel一个MouseListener,或者在mousePress / mouseRelease上交换ImageIcons,或者通过按下并释放来更改JLabel的背景。 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. 如果选择后一种方法,则需要确保将JLabels opaque属性设置为true,以便显示背景颜色。

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. 然后,对于黑键,可以将上面的JPanel添加到JLayeredPane中,并在其顶部添加另一个JPanel,其中包含具有相同功能的黑键。

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. 另外,您还需要注意在后台线程中“播放”任何音符(例如可以通过SwingWorker获得的音符),以免占用Swing事件线程并完全冻结程序。

Consider 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. 我花了很长时间才弄清楚如何使用JLayeredPane 而不设置null布局,但是最后这是我能想到的最好的方法。 Also, assumed some naming conventions for your sound files. 另外,假设您的声音文件有一些命名约定。 :p :p

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM