【问题标题】:How to implement my code in a hierarchy method?如何在层次结构方法中实现我的代码?
【发布时间】:2012-04-14 08:18:01
【问题描述】:

我正在制作一款游戏,我开始在一个班级中完成所有工作。但现在我想分开不同的班级。我对以下代码有一个问题。我在 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);

骰子类:

//创建掷骰子按钮 //MOVED FROM THE 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 类中。如何实现?

【问题讨论】:

标签: java swing refactoring jframe


【解决方案1】:

你可能想要这样的东西:

在您的 gui() 方法中:

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

还有骰子类

public class Dice extends Panel {

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-27
    • 1970-01-01
    • 2014-01-30
    • 1970-01-01
    相关资源
    最近更新 更多