gpt4 book ai didi

java - 将字符网格添加到 jPanel

转载 作者:行者123 更新时间:2023-12-01 13:39:28 25 4
gpt4 key购买 nike

我有两个类,一个是设置网格的类,另一个是制作 GUI 的类。我希望将第一类中的网格插入到第二类中的 jPanel 中。第一个网格是字符网格,填充有随机启动的数字。我无法弄清楚如何将网格插入 jpanel,因为这比预期的更复杂。我尝试了很多事情,但没有任何运气......有什么帮助吗?

//set grid class

public void setgrid() {
Random ran = new Random();
for (int i = 0; i < X; i++) {
for (int j = 0; j < Y; j++) {
int num = ran.nextInt(10);
if (num == 4) {
grid[i][j] = 'F';
} else if (num == 9) {
grid[i][j] = 'O';
} else {
grid[i][j] = ' ';
}}}


// Panel Class
Panel = new JPanel(new GridLayout(X, Y));
for (int i = 0; i < X; i++) {
for (int j = 0; j < Y; j++) {
world[i][j] = new JPanel();
world[i][j].setBackground(Color.white);
world[i][j].setBorder(BorderFactory
.createLineBorder(Color.black));
Panel.add(world[i][j]);

不确定要在此处添加什么才能将网格添加到面板中

最佳答案

"I am having trouble working out how to insert the grid into the jpanel as this is more complicated than expected. I have tried many things but havent had any luck..Any help?"

不确定您到底想做什么或做错了什么,但我可以建议的一件事是使用JLabel。它们以文本作为参数,在标签中显示文本。另一方面,JPanel 需要进行绘制(这意味着您需要自己实际绘制文本)。

测试一下这个程序,看看我在说什么

enter image description here

import java.awt.GridLayout;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class DrawGrid {

public DrawGrid() {
int[][] grid = getGrid();

JPanel panel = new JPanel(new GridLayout(10, 10));
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
panel.add(new JLabel(String.valueOf(grid[i][j])));
}
}

JFrame frame = new JFrame();
frame.add(panel);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);


}

public int[][] getGrid() {
int[][] grid = new int[10][10];
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
grid[i][j] = i;
}
}
return grid;

}
public static void main(String[] args) {
new DrawGrid();

}

}
<小时/>

这是我将 JLabel 添加到 JPanel 的代码

    JPanel panel = new JPanel(new GridLayout(10, 10));
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
panel.add(new JLabel(String.valueOf(grid[i][j])));
}
}

与向 JPanel 添加边框和背景的方式相同,您也可以使用 JLabel

关于java - 将字符网格添加到 jPanel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20952698/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com