[英]JButtons aren't working?
对于游戏,我制作了一个按钮类,可用于菜单中的所有按钮。 我终于设法使我的按钮出现在屏幕上,但是现在当我单击它们时,什么也没发生。
我的按钮类:
package menu;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JPanel;
public class Button extends JButton{
public JButton button;
public ImageIcon buttonImage;
public int width, height;
public String backgroundPath;
public int x, y;
public ActionListener listener;
public Button(String backgroundPath,int x, int y, ActionListener listener)
{
super();
this.backgroundPath = backgroundPath;
this.x = x;
this.y = y;
this.addActionListener(listener);
buttonImage = new
ImageIcon(PlayPanel.class.getResource(backgroundPath));
button = new JButton();
this.setIcon(buttonImage);
this.setBounds(x, y, buttonImage.getIconWidth(),
buttonImage.getIconHeight());
}
}
我知道菜单面板中可能存在错误(@ actionPerformed)。 代码如下:
package menu;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
@SuppressWarnings("serial")
public class MenuPanel extends JPanel implements ActionListener
{
private Button playKnop, highScoreKnop, quitKnop, HTPKnop;
private Tanks mainVenster;
public MenuPanel menuPanel;
int x = 95, width = 200, height = 50;
public MenuPanel(Tanks mainVenster)
{
this.mainVenster = mainVenster;
this.setLayout(null);
playKnop = new Button("/buttons/PLAY.png",x, 350, menuPanel);
highScoreKnop = new Button("/buttons/HS.png",x, 460, menuPanel);
HTPKnop = new Button("/buttons/HTP.png",x, 515, menuPanel);
quitKnop = new Button("/buttons/QUIT.png",x, 570, menuPanel);
this.add(playKnop);
this.add(quitKnop);
this.add(HTPKnop);
this.add(highScoreKnop);
validate();
}
public void actionPerformed(ActionEvent ae)
{
if (ae.getSource() == playKnop){
mainVenster.switchPanel(new PlayPanel(mainVenster));
} else if (ae.getSource() == quitKnop) {
mainVenster.switchPanel(new QuitPanel(mainVenster));
} else if (ae.getSource() == HTPKnop) {
mainVenster.switchPanel(new HTPPanel(mainVenster));
} else if (ae.getSource() == highScoreKnop) {
mainVenster.switchPanel(new HSPanel(mainVenster));
}
}
}
我认为错误是我正在编写mainVenster(面板/窗口的Venster =荷兰语)并且我可能应该编写其他参数的事实。 问题是我不知道哪个。
要定义在监听你的按钮,所以你必须引用类本身作为this
:
playKnop = new Button("/buttons/PLAY.png",x, 350, this);
highScoreKnop = new Button("/buttons/HS.png",x, 460, this);
HTPKnop = new Button("/buttons/HTP.png",x, 515, this);
quitKnop = new Button("/buttons/QUIT.png",x, 570, this);
您已经具有menuPanel
属性,因此在创建类时可以分配一个值,在这种情况下为this
。
menuPanel = this;
但我不建议您删除此属性或将其重命名为_this
或_menuPanel
以同意约定。
有一个java.awt.Button
类。 我会考虑不调用您的新按钮类Button
,以防止任何名称空间混乱。
你需要通过this
来代替menuPanel
作为ActionListener
为了你们的按钮:
playKnop = new Button("/buttons/PLAY.png",x, 350, this);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.