我正在做一个游戏,我正在尝试去掉代码中的所有冗余。我所有的面板(PlayPanel
,HighScore
,Quit
,..)都有很多共同的特性,所以我在所有面板中都制作了IPanel
类。它看起来像这样:我可以在另一个类中使用一个类(构造函数+方法)的代码吗? (java)
package menu;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
public class IPanel extends JPanel implements ActionListener{
public Image achtergrond;
public Tanks mainVenster;
public String backgroundPath;
public IPanel(String backgroundPath, Tanks mainVenster)
{
super();
this.mainVenster = mainVenster;
this.setLayout(null);
this.backgroundPath = backgroundPath;
achtergrond = new //achtergrond is dutch for background
ImageIcon(getClass().getResource(backgroundPath)).getImage();
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(achtergrond, 0, 0, this.getWidth(), this.getHeight(),
this);
}
public void actionPerformed(ActionEvent ae)
{
mainVenster.switchPanel();
}
public void switchPanel(Tanks toActivate)
{
remove(mainVenster);
mainVenster = toActivate;
add(mainVenster); //this is wrong, no idea what to do actually
validate();
repaint();
}
}
我能使用构造函数在其他类,但我不知道如何使用 paintComponent
和actionPerformed
方法在其他类。我在所有面板中都使用了这两种方法,所以我认为没有必要为所有这些面板重新编写方法。
我的面板之一的一个例子是QuitPanel
:
package menu;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
@SuppressWarnings("serial")
public class QuitPanel extends JPanel implements ActionListener
{
public Button yesKnop, noKnop;
public JLabel label;
public Tanks mainVenster;
public QuitPanel quitPanel;
public IPanel quit;
public QuitPanel(Tanks mainVenster)
{
quit = new IPanel("/achtergronden/menu.jpg", mainVenster);
int x = 95, width = 200, height = 50;
label = new JLabel("ARE YOU SURE?");
Font font = new Font("Courier", Font.BOLD, 25);
label.setFont(font);
label.setBounds(x+20, 400, width, height);
yesKnop = new Button("/buttons/YES.png",x, 450, this);
noKnop = new Button("/buttons/NO.png",x, 525, this);
this.add(quit);
this.add(label);
this.add(noKnop);
this.add(yesKnop);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource() == noKnop)
quit.switchPanel(mainVenster); //this is wrong
else if(ae.getSource() == yesKnop)
System.exit(0);
}
}
,你可以看到我扩展了类JPanel
,因为当我试图扩大IPanel
我得到了在public HTPPanel(Tanks mainVenster)
一个错误,说
当我打开我的quitPanel我得到这个:
,所以我知道一定有我的代码正确的一部分,唯一的问题是,我背景不加载 - >(public void paintComponent(Graphics g)
法)
的问题是:我如何使用我在类nr 2中的类nr 1中创建的方法?
此外,noButton不工作(yesButton工作正常) - >(public void actionPerformed(ActionEvent ae)
方法) - >也因为public void switchPanel(Tanks toActivate)
我猜
太感谢你了!
这似乎是一个合理的答案,但我真的不明白如何我可以调用构造函数没有我想要的参数... – Lola