所以我试图制作单迷宫(没有发电机)在Java中,我遇到了障碍。我现在的代码将制作一个迷宫,制作一个jframe,但它不会给它上色...有没有办法让着色工作?
import java.awt.*;
import javax.swing.*;
import java.lang.*;
public class ayy{
public static void main(String [] args){
JFrame frame = new JFrame("Maze");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setSize(1000,1000);
frame.setVisible(true);
int width = 1;
int height = 1;
int [][] map= {
{0,0,0,0,0,0,0,0,0,0,},
{0,0,0,0,0,0,0,0,0,0,},
{2,1,1,1,0,0,0,0,0,0,},
{0,0,0,1,0,0,0,1,1,2,},
{0,0,0,1,0,0,0,1,0,0,},
{0,0,0,1,0,0,0,1,0,0,},
{0,0,0,1,1,1,1,1,0,0,},
{0,0,0,0,0,0,0,0,0,0,},
{0,0,0,0,0,0,0,0,0,0,},
{0,0,0,0,0,0,0,0,0,0,}
};
for(int i=0;i<map.length;i++){
for(int j=0;j<map.length;j++){
switch(map[i][j]){
case 0:
class rectangle{
public void paint(Graphics g){
g.drawRect(1,1,1,1);
g.setColor(Color.red);
}
}
break;
case 1:
class rectangle2{
public void paint(Graphics g){
g.drawRect(1,1,1,1);
g.setColor(Color.yellow);
}
} break;
case 2:
class rectangle3{
public void paint(Graphics g){
g.drawRect(1,1,1,1);
g.setColor(Color.blue);
}
} break;
}
}
}
}
}
任何帮助都可以 谢谢!
答案 0 :(得分:1)
1-)不要在Switch案例上创建类,这不是一个好习惯。
2-)如果Class没有继承JComponent,那么它将无法覆盖paint和paintComponent方法,因为它没有它们。
3-)大写类名的第一个字母,并使用有意义的名称。
4-)修改您的代码,如下所示:
public class MazeApp extends JFrame {
public static void main(String[] args) {
JFrame frame = new JFrame("Maze");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setSize(1000, 1000);
Maze brd = new Maze();
frame.add(brd);
frame.setVisible(true);
}
}
class Maze extends JPanel {
public Maze() {
}
protected void paintComponent(Graphics g) {
int width = 1;
int height = 1;
int[][] map = { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, },
{ 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, },
{ 0, 0, 0, 1, 0, 0, 0, 1, 1, 2, },
{ 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, },
{ 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, },
{ 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, },
{ 0, 0, 2, 0, 0, 2, 0, 0, 2, 0, },
{ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, },
{ 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, } };
for (int i = 0; i < map.length; i++) {
for (int j = 0; j < map.length; j++) {
int factori = i * 50;
int factorj = j * 50;
switch (map[i][j]) {
case 0: {
g.setColor(Color.red);
g.fillRect(factori, factorj, 2, 2);
}
break;
case 1: {
g.setColor(Color.yellow);
g.fillRect(factori, factorj, 2, 2);
}
break;
case 2: {
g.setColor(Color.blue);
g.fillRect(factori, factorj, 2, 2);
}
break;
}
}
}
}
}