我是java中的图形新手,由于某种原因,图形不会显示在jframe上。我对如何设置和实例化图形感到困惑。代码中也可能有一个愚蠢的错误,我只是没有看到。感谢您的任何反馈!
地图类
public class Map extends JPanel{
private static int WIDTH;
private static int HEIGHT;
private static int ROWS;
private static int COLS;
private static int TILE_SIZE;
private static int CLEAR = 0;
private static int BLOCKED = 1;
private static int[][] GRID;
public Map(int w, int h, int t){
WIDTH = w;
HEIGHT = h;
TILE_SIZE = t;
ROWS = HEIGHT/TILE_SIZE;
COLS = WIDTH/TILE_SIZE;
GRID = new int[ROWS][COLS];
for (int row = 0; row < ROWS; row++){
for (int col = 0; col < COLS; col++){
GRID[row][col] = BLOCKED;
}
}
randomMap();
}
public void randomMap(){
int row = 0;
int col = 0;
int turn;
Random rand = new Random();
GRID[row][col] = CLEAR;
do{
turn = rand.nextInt(2)+1;
if (turn == 1)
row++;
else
col++;
GRID[row][col] = CLEAR;
}while(row<ROWS-1 && col<COLS-1);
if (row == ROWS-1){
for (int i = col; i < COLS; i++){
GRID[row][i] = CLEAR;
}
}
else{
for (int i = row; i < ROWS; i++){
GRID[i][col] = CLEAR;
}
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
for (int row = 0; row < WIDTH; row++){
for (int col = 0; col < HEIGHT; col++){
if (GRID[row][col] == 1){
g2d.setColor(Color.BLACK);
g2d.fillRect(row*TILE_SIZE, col*TILE_SIZE, TILE_SIZE, TILE_SIZE);
}else{
g2d.setColor(Color.WHITE);
g2d.fillRect(row*TILE_SIZE, col*TILE_SIZE, TILE_SIZE, TILE_SIZE);
}
}
}
}
public void displayConsole(){
for (int row = 0; row < ROWS; row++){
for (int col = 0; col < COLS; col++){
System.out.print(GRID[row][col] + " ");
}
System.out.println("");
System.out.println("");
}
}
}
游戏类
public class Game extends JFrame{
private Map map;
public Game(){
setLayout(null);
setBounds(0,0,500,500);
setSize(500,500);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Map map = new Map(500,500,50);
map.displayConsole();
add(map);
repaint();
setVisible(true);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Game game = new Game();
}
}
答案 0 :(得分:4)
绘制的组件可能大小为0x0。自定义绘制的组件应返回组件的首选大小。
将组件添加到框架后,打包框架以确保框架是显示组件所需的确切尺寸。
当然,要么在框架中使用或设置适当的布局/约束。在这种情况下,我会使用BorderLayout
的默认布局和CENTER
的默认约束。
答案 1 :(得分:1)
安德鲁是对的。我不得不重新做布局才能让它发挥作用。我添加了<div id="circle">
<div class="hand"></div>
<div class="hand"></div>
<div class="hand"></div>
<div class="hand"></div>
</div>
和perferredSize()
的代码,并添加了对minimumSize()
的调用并删除了pack()
。此外,你在计算你的高度和宽度时遇到问题,他们没有排列到ROWS和COLS并且会抛出Index Out Of Bounds。
更正了以下代码。
setLayout(null)