【发布时间】:2014-07-06 19:30:31
【问题描述】:
我有如下所示的三个类,用于游戏 GUI:-
//this is the parent class.
import javax.swing.*;
import java.awt.*;
public class GameGui extends JFrame{
public void decorateButton(JButton aBut,Color forg,Color back){
Font afont = new Font(Font.SANS_SERIF,Font.PLAIN,18);
aBut.setFont(afont);
aBut.setBackground(back);
aBut.setForeground(forg);
}
public void setFrameDefault(){
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(400, 475);
this.setLocationRelativeTo(null);
this.setResizable(false);
}
public void setConstraints(int x,int y,int weightx,int weighty,GridBagConstraints gbc){
gbc.weighty=weighty;
gbc.weightx=weightx;
gbc.gridx=x;
gbc.gridy=y;
}
}
//this class is for result to be shown for the game.
import javax.swing.*;
import java.awt.*;
class Result extends GameGui{
JPanel mainPanel = new JPanel();
JLabel backImage = new JLabel();//I want this variable to be shadowed by the subclass variable,but it is not happening.
JButton continueGame = new JButton("continueGame");
JButton exitGame = new JButton("exitGame");
public Result(){
this.setFrameDefault();
backImage.setLayout(new BorderLayout());
this.setContentPane(backImage);
mainPanel.setLayout(new GridBagLayout());
decorateButton(continueGame,Color.green,Color.white);
decorateButton(exitGame,Color.green,Color.white);
setGui();
}
public void setGui(){
GridBagConstraints gbc = new GridBagConstraints();
mainPanel.setOpaque(false);
gbc.gridy=200;
gbc.gridx=0;
gbc.insets=new Insets(410,0,0,130);
mainPanel.add(continueGame,gbc);
gbc.gridx=GridBagConstraints.RELATIVE;
gbc.insets = new Insets(410,0,0,0);
mainPanel.add(exitGame,gbc);
setFrameDefault();
this.getContentPane().add(mainPanel);
}
}
//this class is for showing the result for a Win.
import javax.swing.*;
import java.awt.*;
public class Win extends Result{
JLabel backImage = new JLabel(new ImageIcon("C:\\Users\\BSK\\Desktop\\win.png"));//Problem is here as i have declared the same named JLabel as in Result class but iam not getting the image as background.
public static void main(String[] args) { //this main method is for testing.
Win w = new Win();
w.setVisible(true);
}
}
我在层次结构的末尾需要两个类,它们是 Win 和 Defeat(第二个我还没有实现)。我需要这个,因为我想要胜利框架和失败框架只在图像上有所不同。
所以我的问题是,虽然我在Result 和Win 两个类中都声明了与backImage 相同的JLabel,但为什么我没有在背景中获取图像?我已经通过将图像放入JLabel 来测试它backImage 属于 Result 类,然后它就可以工作了!但我想利用 data shadowing 因为在我的 Defeat 类(也扩展了 Result)中,我将命名为 JLabel与backImage同名,但设置了不同的图像。希望你明白,那么出路是什么?
提前致谢。
注意请使用您的图片进行测试。
【问题讨论】:
-
看起来你在这里误用了继承:你在组合会更好的地方使用继承。
-
@HovercraftFullOfEels 如果你能提供一个详细的答案......很多很多thanx
-
@HovercraftFullOfEels plese if you can describe....等待你的回答。
标签: java swing inheritance scope