如何使标签在单击时移动?
我正在为大学做一个面向对象的编程项目,就我而言,我所需要做的就是能够让一维游戏角色在每次用户单击下一个按钮时向前移动一步。我正在使用 Netbeans 并创建了一个 JLabel 来用作角色,并且我们制作了按钮,但我不知道在实际发生事件时从哪里开始。
有人可以帮我吗?
I'm doing a object orientated programming project for college and for my part all I need to do is to be able to make a 1d game character move a step forward every time the next button is clicked by the user. I am using Netbeans and have created a JLabel to use as the character and we have the button made but I have no clue where to start when it comes to actually having the event happen.
Could anyone help me please?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要将
ActionListener
添加到下一个按钮。一旦您单击按钮,actionListener 的actionPerformed
方法就会被调用,您可以在其中进行事件处理。 (有关详细信息,请参阅如何编写 ActionListener)。为了移动标签,我建议将标签容器的布局设置为 null(请参阅 使用布局管理器)并手动指定位置。在您的 actionPerformed 方法中,您可以将标签的位置设置为不同的值。
为了能够控制标签的位置,您必须使用三个核心操作:
container.setLayout(null);
(对于保存标签的容器组件label.addActionListener(myActionListener) );
将 ActionListener 添加到您的标签label.setLocation(newX, Y);
移动您的标签组件(需要在您的 actionPerformed 方法中执行)You need to add an
ActionListener
to your next button. As soon as you click your button, the actionListener'sactionPerformed
method will be called in which you can process the event handling. (see How to Write an ActionListener for further information).In order to move your label I recommend setting the layout for your label's container to null (see Using Layout Managers) and specifying the position manually. In your actionPerformed Method you can then set the label's position to a different value.
In order to be able to control your label's position you have to make use of three core operations:
container.setLayout(null);
(for the container component holding your labellabel.addActionListener(myActionListener);
to add the ActionListener to your labellabel.setLocation(newX, Y);
to move your label component (needs to be performed in your actionPerformed-method)