[英]How to add a method to a JPanel?
我正在處理此分配,但是我有一個問題需要將這個矩陣添加到JPanel。 我用另一種方法制作了矩陣,因為我認為這樣會更容易,但是找不到解決方案。 如果看起來很熟悉,我也會通過遵循Oracle網站上的教程來使用此布局。
文本也需要可編輯,這就是為什么我有按鈕。 我這里也沒有功能。
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();
}
});
}
從您概述的問題來看,您似乎想向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();
}
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.