【发布时间】:2015-05-08 22:59:00
【问题描述】:
我正在制作一款游戏,并试图消除代码中的所有冗余。我所有的面板(PlayPanel,HighScore,Quit,..)都有很多共同的属性,所以我创建了一个类 IPanel 来扩展我的所有面板。它看起来像这样:
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) 方法)
问题是:如何在第 2 类中使用我在第 1 类中创建的方法?
另外,noButton 不工作(yesButton 工作正常)
--> (public void actionPerformed(ActionEvent ae) 中的方法)
--> 我猜也是因为public void switchPanel(Tanks toActivate)
非常感谢!
【问题讨论】:
标签: java swing inheritance redundancy