如何将方法添加到JPanel?

时间:2015-08-06 00:43:12

标签: java methods jpanel

我正在处理这项任务,我有一个问题,我需要将此矩阵添加到JPanel。我用另一种方法制作了矩阵,因为我认为它更容易,但无法找到解决方案。如果它看起来很熟悉,我也会按照Oracles网站上的教程使用这个布局。

文本也需要可编辑,这就是我有按钮的原因。我也没有这里的功能。

public static void addComponentsToPane(Container pane) {

    if (RIGHT_TO_LEFT) {
        pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
    }

    JPanel array;
    JButton button;
    pane.setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();

    if (shouldFill) {
        c.fill = GridBagConstraints.HORIZONTAL;
    }

    button = new JButton("Reset to 0");
    pane.add(button, c);

    // WHERE IT NEEDS TO BE ADDED***********************
    array = new JPanel();
    pane.add(array, c);

}

private static void createAndShowGUI() {
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    addComponentsToPane(frame.getContentPane());
    frame.pack();
    frame.setVisible(true);
}

public int[][] getRandomMatrix() {
int[][] randomMatrix = new int[10][10];
    for (int r = 0; r < randomMatrix.length; r++) {
        for (int c = 0; c < randomMatrix[r].length; c++) {
        randomMatrix[r][c] = (int)(Math.random() * 2);
        }
    }
    return randomMatrix;
}

public static void main(String[] args) {
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            createAndShowGUI();
        }
    });
}

1 个答案:

答案 0 :(得分:0)

从您提出的问题来看,您似乎想要为JPanel添加其他方法。

好的,这需要您创建一个JPanel的自定义实例,如下所示:

public class MyPanel extends JPanel {

    public MyPanel() {
        super();   
    }


    public int[][] getRandomMatrix() {
         int[][] randomMatrix = new int[10][10];
         for (int r = 0; r < randomMatrix.length; r++) {
             for (int c = 0; c < randomMatrix[r].length; c++) {
             randomMatrix[r][c] = (int)(Math.random() * 2);
         }
     }
    return randomMatrix;
   }
}

而不是将预先滚动的JPanel添加到帧中,而是将“MyPanel”的实例添加到帧中。

public static void addComponentsToPane(Container pane) {

if (RIGHT_TO_LEFT) {
    pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
}

MyPanel array;
JButton button;
pane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();

if (shouldFill) {
    c.fill = GridBagConstraints.HORIZONTAL;
}

button = new JButton("Reset to 0");
pane.add(button, c);

array = new MyPanel();
pane.add(myPanel, c);

}

private static void createAndShowGUI() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addComponentsToPane(frame.getContentPane());
frame.pack();
frame.setVisible(true);
}



public static void main(String[] args) {
   javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            createAndShowGUI();
        }
  });
}