如何在层次结构方法中实现我的代码?

时间:2012-04-13 23:16:12

标签: java swing refactoring jframe

我正在制作游戏,我开始在一个班级中完成所有工作。但现在我想在不同的课程中分开。我遇到以下代码的问题。我在GameView类中创建了一个JFrame,其代码的一半代码我想将它复制到另一个类,它找不到变量帧,因为它在GameView中?以下是我的代码:

GameView类:

public void gui()
    {
        BorderLayout borderlayout = new BorderLayout();      

        //Creates the frame, set the visibility to true, sets the size and exit on close
        JFrame frame = new JFrame("Games");
        frame.setVisible(true);
        frame.setSize(600,400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Creates the Throw Dice button
        Panel p = new Panel();
        p.setLayout(new GridLayout());
        p.add(new Button("Throw Dice"));
        p.add(new Label("Dice Draw")); 
        p.setBackground(new Color(156, 93, 82));
        frame.add(p, BorderLayout.SOUTH);

骰子类:

//创建投掷骰子按钮//从GameView CLASS移动

Panel p = new Panel();
p.setLayout(new GridLayout());
p.add(new Button("Throw Dice"));
p.add(new Label("Dice Draw")); 
p.setBackground(new Color(156, 93, 82));
frame.add(p, BorderLayout.SOUTH);// cannot find variable frame when i put this section into a different class

所以我希望框架窗口在GameView类中,而骰子部分在Dice类中。但是它给出一个错误无法找到变量帧,因为它在GameView类中。我该如何实施呢?

1 个答案:

答案 0 :(得分:2)

你可能想要这样的东西:

在您的gui()方法中:

JFrame frame = new JFrame("Games");
...
frame.add(new Dice(), BorderLayout.SOUTH);

和Dice类

public class Dice extends Panel {

    public Dice() {
        setLayout(new GridLayout());
        add(new Button("Throw Dice"));
        // add more stuff here
    }
...