在actionPerformed方法中引用contentPane

时间:2013-03-24 20:36:57

标签: java swing jpanel grid-layout border-layout

我正在创建一个加载按钮,并希望它填充嵌套在边框布局(主窗口)的CENTER面板内的9x9 gridlayout内容窗格。此方法位于边框布局的PAGE_START部分内。问题是如何将按钮放在CENTER部分的网格布局中?

       //Load Button
    JButton load = new JButton("Load");
    load.addActionListener(new ActionListener() { 
        @Override
        public void actionPerformed (ActionEvent a) {
            //Dialog Box To Locate The Puzzle
                SudokuPuzzle puzzle;
                JFileChooser chooser = new JFileChooser();
                FileNameExtensionFilter filter = new FileNameExtensionFilter(
                        "Text Files", "txt");
                chooser.setFileFilter(filter);
                int returnVal = chooser.showOpenDialog(SudukoGUI.this);
                if(returnVal == JFileChooser.APPROVE_OPTION) {
                    String fileLocation = chooser.getSelectedFile().getName();
                    Scanner file = new Scanner(fileLocation);
                    puzzle = new SudokuPuzzle(file, file);

                    //Load Puzzle To Model and draw it
                    try {
                        gridView = new JButton[9][9];
                        int[][] viewArray = puzzle.getArray();

                        for (int row = 0; row < 9; row++) {
                            for (int col = 0; col < 9; col++) {
                                gridView[row][col] = new JButton(String.valueOf(viewArray[row][col])); 

***************THE NEXT LINE REPRESENTS MY PROBLEM***************
                                this.getContentPane().board.add(gridView[row][col]);

                            }
                        }

这是在构造函数

     JPanel board = new JPanel();
    board.setLayout (new GridLayout (9,9));
    board.setPreferredSize(new Dimension(400,400));
    this.getContentPane().add(board, BorderLayout.CENTER);

2 个答案:

答案 0 :(得分:0)

首先使用以下内容将board声明为final变量:

final JPanel board = new JPanel();

因此可以从board的匿名内部类访问ActionListener。此后,更改此行:

this.getContentPane().board.add(gridView[row][col]);


board.add(gridView[row][col]);

答案 1 :(得分:0)

this.getContentPane().board.add(gridView[row][col]);

没有任何意义。您已将board添加到构造函数的内容窗格中,但这并不意味着board现在是内容窗格的字段。所以

getContentPane().board

无法编译。

您应该将board作为类的字段,而不是在构造函数中将其声明为局部变量。然后,您可以在课堂上引用board

基本示例:

public class Example
{
    private JPanel board;

    public Example()
    {
         board = new JPanel();
         getContentPane().add(board);
         //assuming above code takes place in the constructor
         JButton load = new JButton("load");
         load.addActionListener(new ActionListener()
         {
              public void actionPerformed(ActionEvent e)
              {
                    ...lots of code
                    //as board is no longer a local variable this will compile
                    board.add(gridView[row][col]);
              }
         }
    }
}

请注意,您可能希望在某个时刻将load添加到您的框架中。