为什么我的Paint表面方法不起作用?

时间:2015-10-13 21:33:01

标签: java swing paint

所以暂时覆盖JComponent的paint方法给了我麻烦,我永远无法弄明白为什么。我正在制作一个项目,它将采用黑白图像并在屏幕上绘制,其中图片中的每个像素都是50 x 50的屏幕,显然有些绘画将在屏幕外完成但是没关系因为这将是一个带有移动屏幕的2D自上而下游戏。无论我尝试过什么,当它运行时它从不在屏幕上绘制任何东西,它与我的1:50逻辑无关,因为当我试图让它绘制一个简单的矩形时,它甚至没有绘制那。所以问题必须在于绘画方法,但我无法弄清楚出了什么问题。我知道这是很多代码,但有人可以让我知道什么是错的? (我知道有很多方法还没有被使用,只是忽略那些方法)

这是Jframe类:

(您必须指定要在此课程中绘制的黑白图像的路径)

`package Code;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.RenderingHints;
import java.awt.event.ActionListener;

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

//class that stores all of the painting methods and the GUI methods:
public class Window extends JFrame{

    double WINDOWWIDTH, WINDOWHEIGHT;
    JPanel TitlePanel;
    JButton PlayGame, Quit;
    JLabel Title;
    Map DigitizedMap;
    PaintSurface PS;

    int x = 0;
    int y = 0;
    int TilesAcross;
    int TilesDown;

    public Window(){

        WINDOWWIDTH = 1200;
        WINDOWHEIGHT = (Math.floor(WINDOWWIDTH / 50)*0.66) * 50;
        TilesAcross = (int) (WINDOWWIDTH / 50);
        TilesDown = (int) (WINDOWHEIGHT / 50);

        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setSize((int) WINDOWWIDTH, (int) WINDOWHEIGHT);
        this.setTitle("Stealth Client    ||    Version 1.0");

        //all of the code for the user interface will go here:
        //DrawStartInterface(this);

        //creating the digitized verion of the map for the paint method to use:
        MapLoader ML = new MapLoader("C:\\Users\\Greg\\Desktop\\TestMap.png");
        DigitizedMap = ML.ConvertMap();
        PS = new PaintSurface();
        TitlePanel = new JPanel();
        TitlePanel.add(PS, BorderLayout.CENTER);
        this.add(TitlePanel);

        this.setVisible(true);
        this.setResizable(false);
    }

    private void DrawStartInterface(JFrame f){
        //all of the starting UI:

        TitlePanel = new JPanel(new GridBagLayout());
        TitlePanel.setBackground(Color.DARK_GRAY);

        Title = new JLabel("STEALTH");
        Title.setForeground(Color.ORANGE);
        Title.setFont(new Font("Calabri", Font.BOLD, 48));
        addItem(TitlePanel, Title, 0, 0, 1, 1, 1);

        PlayGame = new JButton("Play");
        PlayGame.setBackground(Color.BLACK);
        PlayGame.setForeground(Color.ORANGE);
        PlayGame.setFont(new Font("Calabri", Font.BOLD, 36));
        PlayGame.addActionListener(new ActionEvent());
        addItem(TitlePanel, PlayGame, 0, 1, 1, 1, 1);

        Quit = new JButton("Quit");
        Quit.setBackground(Color.BLACK);
        Quit.setForeground(Color.ORANGE);
        Quit.setFont(new Font("Calabri", Font.BOLD, 36));
        Quit.addActionListener(new ActionEvent());
        addItem(TitlePanel, Quit, 0, 2, 1, 1, 1);

        f.add(TitlePanel);
    }

    private class ActionEvent implements ActionListener{
        @Override
        public void actionPerformed(java.awt.event.ActionEvent e) {
            //which action has been heard:
            if(e.getSource() == PlayGame){
                //plays the game:
                StartGame();
            } else if(e.getSource() == Quit){
                //Quits the game:
                Terminate();
            }
        }

    }

    public void Terminate(){
        //exits the game:

        System.exit(0);
    }

    //Starts the game:
    private void StartGame(){
        TitlePanel.add(PS);
    }

    //The paint Surface class that will be stored in the panel and paint the game:
    class PaintSurface extends JComponent{
        @Override
        public void paint (Graphics g){
            //basic graphics shizel wizel:
            Graphics2D g2 = (Graphics2D) g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);
            g2.drawRect(100, 100, 100, 100);
            render(g2);
            System.out.println("Painted");
        }

        private void render(Graphics2D g2){
            //renders only the squares within a certain distance of the center of the screen:
            int PlayerTileX = (int) Math.ceil((x + (WINDOWWIDTH / 2))/50);      // This is the x tile that the player is in
            int PlayerTileY = (int) Math.ceil((y + (WINDOWHEIGHT / 2))/50);     // this is the y tile that the player is in
            //now we are going through only the tiles around the player and rendering them:
            int XOffset = x - (int) (PlayerTileX - (Math.ceil(TilesAcross / 2)));
            int YOffset = y - (int) (PlayerTileY - (Math.ceil(TilesDown / 2)));
            for (int i = (int) (PlayerTileX - (Math.ceil(TilesAcross / 2))); i < (int) (PlayerTileX + (Math.ceil(TilesAcross / 2))); i++){
                for (int n = (int) (PlayerTileY - (Math.ceil(TilesDown / 2))); n < (int) (PlayerTileY + (Math.ceil(TilesDown / 2))); n++){
                    //this is where only the coorect boxes will be rendered because of the limiting for loops:
                    //The if statement for determining what type of thing it is:
                    if (DigitizedMap.getTile(i, n) == 1){
                        //Rendering the walls:
                        g2.drawRect((int)(((i * 50) % WINDOWWIDTH) - XOffset), (int)(((i * 50) % WINDOWHEIGHT) - YOffset), 50, 50);
                    }
                }
            }
        }
    }

    //used to add things to panels:
    public void addItem(JPanel p, JComponent c, int x, int y, int width, int height,
            int align /* Defines the spot on the coordinate */) {
        GridBagConstraints gc = new GridBagConstraints();
        gc.gridx = x;
        gc.gridy = y;
        gc.gridwidth = width;
        gc.gridheight = height;
        gc.insets = new Insets(10, 10, 10, 10);

        switch (align) {
        case 1:
            gc.anchor = GridBagConstraints.NORTH;
            break;
        case 2:
            gc.anchor = GridBagConstraints.EAST;
            break;
        case 3:
            gc.anchor = GridBagConstraints.SOUTH;
            break;
        case 4:
            gc.anchor = GridBagConstraints.WEST;
            break;
        case 5:
            gc.anchor = GridBagConstraints.CENTER;
            break;
        }
        p.add(c, gc);
    }

}
`

这是Starthere类(包含main方法的类):

    package Code;

public class StartHere {
    public static void main(String[] args) {
        //Creating the frame:
        final Window Frame = new Window();
    }

}

这是存储所有地图数据的地图类:

package Code;

public class Map {

    //the Array for all of the codes:
    double Tiles[][];
    int width;
    int height;

    //setters and getters for the width and height:
    public int getWidth() {
        return width;
    }

    public void setWidth(int width) {
        this.width = width;
    }

    public int getHeight() {
        return height;
    }

    public void setHeight(int height) {
        this.height = height;
    }


    //the constructor for the double map:
    public Map(long Width, long Height){
        Tiles = new double[(int) Width][(int) Height];
    }

    //this is where the double array is going to be set:
    public void setTile(int x, int y, double type){
        Tiles[x][y] = type;
    }

    //this gets the given tile code:
    public double getTile(int x, int y){
        return Tiles[x][y];
    }

}

最后,这是负责从图像文件加载地图的地图加载器类:

package Code;

import java.awt.Color;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class MapLoader {

    BufferedImage MapImage;

    public MapLoader(String MapPath){
        //loading the map image from the specified map path:
        try {
            MapImage = ImageIO.read(new File(MapPath));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    public Map ConvertMap(){
        Map m = new Map(MapImage.getWidth(), MapImage.getHeight());

        //now to read the individual pixels of the image and determine the code for the map object:
        for(int i = 0; i < MapImage.getWidth(); i++){
            for(int n = 0; n < MapImage.getHeight(); n++){
                if (MapImage.getRGB(i, n) == Color.BLACK.getRGB()){
                    //Black = Wall = 1
                    m.setTile(i, n, 1);
                    System.out.print("1");
                } else {
                    //else it is nothing so White = Space = 0
                    m.setTile(i, n, 0);
                    System.out.print("0");
                }
            }
            System.out.println("");
        }

        return m;
    }

}

非常感谢任何能帮助我这几天困扰我的人,而且我没有想法。

此处还有一个我一直使用的示例文件: Example File

1 个答案:

答案 0 :(得分:3)

你的绘画方法有效,但没有人能看到PaintSurface对象。你有:

  PS = new PaintSurface();
  TitlePanel = new JPanel();
  TitlePanel.add(PS, BorderLayout.CENTER);

您正在将PS对象添加到BorderLayout.CENTER位置,但TitlePanel不使用BorderLayout - 它使用默认的FlowLayout。现在PaintSurface的首选大小为0,0,因为TitlePanel使用FlowLayout,PS将非常小。

解决方案:将TitlePanel的布局设置为BorderLayout。

  PS = new PaintSurface();
  TitlePanel = new JPanel(new BorderLayout());
  TitlePanel.add(PS, BorderLayout.CENTER);

这将使PaintSurface实例填充TitlePanel。

另外,根据我的评论:

  • 始终覆盖paintComponent,而不是绘制。任何体面的图形教程都会告诉你这个。
  • 如果您在覆盖范围内覆盖了super的绘画方法,那么总是调用super.paintComponent(...)。
  • 以这样的方式创建代码,以便每个类都可以独立测试和调试,使用小型模拟类来帮助您完成此操作。
  • 这样,如果您遇到错误,可以创建并发布您的Minimal,Complete和Verifiable示例供我们测试,而不是要求我们完成整个大型程序。
  • 请注意,您永远不会致电DrawStartInterface(...)
  • 请学习并遵循Java命名约定,因为这样做有助于其他人更好地理解您的代码。字段和方法名称都应以小写字母开头,而类和接口名称应以大写字母开头。