I working on this assignment and I have a problem where I need to add this matrix to a JPanel. I made the matrix in another method because I thought it would be easier but can't find a solution. I also used this layout by following a tutorial on Oracles website if it look familiar.
The text also needs to be editable which is why I have buttons. I don't have there functions here either.
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();
}
});
}
From the question you outline, it looks like you want to add an additional method to JPanel.
Ok, that would require you to create a custom instance of a JPanel like this:
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;
}
}
And instead of adding a pre-rolled JPanel to the frame, you would add an instance of 'MyPanel' to the frame instead.
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();
}
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.