gpt4 book ai didi

java - JButton 不起作用?

转载 作者:行者123 更新时间:2023-11-30 08:12:51 25 4
gpt4 key购买 nike

对于我正在制作的游戏,我制作了一个按钮类以用于菜单中的所有按钮。我终于设法让我的按钮出现在屏幕上,但现在当我单击它们时什么也没有发生。

我的按钮类:

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 - JButton 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30121657/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com