i'm making a tank game. to avoid redundancy to make my buttons in the menupanel i wrote a class button:
package menu;
import java.awt.Image;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
public class Button extends JButton{
public JButton button;
public ImageIcon buttonImage;
public int x, width, height;
public String backgroundPath;
public int y;
public Button(String backgroundPath,int x, int y, MenuPanel menuPanel)
{
super();
this.backgroundPath = backgroundPath;
this.x = x;
this.y = y;
buttonImage = new
ImageIcon(PlayPanel.class.getResource(backgroundPath));
this.setIcon(buttonImage);
this.setBounds(x, y, buttonImage.getIconWidth(),
buttonImage.getIconHeight());
this.addActionListener(menuPanel);
}
}
in the constructor of the method i have MenuPanel menupanel
but i want to be able to use this code is multiple panels like the QuitPanel, HighScorePanel, ...etc.
i don't know which parameter i have to use for this so i'm stuck.
thanks in advance!!
将MenuPanel menuPanel
参数更改为ActionListener
侦听器,因为这样做的唯一原因是使向其附加ActionListener
更加容易,因此按钮不需要了解MenuPanel
You can declare an interface IPanel
and make your QuitPanel
, HighScorePanel
, and MenuPanel
implement that interface. I believe each of these panels must be implementing some common methods whose declarations can be moved to IPanel
interface. Then you can pass IPanel
as an argument in constructor rather than MenuPanel
.
如果MenuPanel是JPanel的实例,那么您可以像这样更改代码...
public Button(String backgroundPath,int x, int y, JPanel pane);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.