在Java中向类添加私有字段

时间:2014-08-31 23:45:47

标签: java swing

我有两个相关的类SpaceInvadersApp和HighScoreTableModel

我需要向类型为HighScoreTableModel的SpaceInvadersApp类添加一个新的私有字段,并在SpaceInvadersApp构造函数的开头初始化该字段。

这是我的尝试,我认为我没有正确地做到这一点。

public class SpaceInvadersApp extends JFrame {

/**
 * 
 */
private static final long serialVersionUID = 1L;

private final GamePanel game;

private HighScoreTableModel highScoreTableModel; // unsure about this

final private JMenuItem menuItemGamePause;

/**
 * Create new Space Invaders application.
 * @throws HeadlessException 
 */
public SpaceInvadersApp() throws HeadlessException {

    highScoreTableModel = new HighScoreTableModel("Name", "Score"); //unsure about this

来自HighScoreTableModel类的相关代码

package spaceinvaders.highscores;

import java.util.*;
import javax.swing.event.*;
import javax.swing.table.*;

public class HighScoreTableModel implements TableModel {


private List<String> col1StringList = new ArrayList<String>();
private List<Integer> col2IntegerList = new ArrayList<Integer>();
private String col1Name, col2Name;

private List<TableModelListener> listenerList = new ArrayList<TableModelListener>();

public HighScoreTableModel(String col1Name, String col2Name) {
    this.col1Name = col1Name;
    this.col2Name = col2Name;

1 个答案:

答案 0 :(得分:2)

考虑查看这些类的包,需要在同一个包中或导入。

另一个细节是您的变量menuItemGamePause,需要初始化,因为它是final

final private JMenuItem menuItemGamePause = new JMenuItem();