Home > OS >  Trying to draw an image in a 2d graphics but it wont work
Trying to draw an image in a 2d graphics but it wont work

Time:06-12

I want to add an image in the top left corner of the JFrame but it won't appear there. I've tried changing the Image into a BufferedImage and ImageIcon but I don't know if I was doing it correctly.

Here's the code:

public class Board {
static Font font;
Board(){
    try { font = Font.createFont(Font.TRUETYPE_FONT, new File("AlphaRomaineFont.ttf"));
    }
    catch(IOException | FontFormatException e){

    }
}
public static JFrame createNewBoard(){
    JFrame screen = new JFrame();
    screen.setUndecorated(true);
    screen.setFont(font);
    screen.setMinimumSize(new Dimension(720,720));
    screen.setLocationRelativeTo(null); 
    screen.setMaximumSize(new Dimension(getScreenWidth(), getScreenHeight()));
    screen.setVisible(true);
    screen.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    screen.setBackground(Color.decode("#ebe4e4"));
    screen.setVisible(true);
    screen.setResizable(false);

    Map<Integer, Character> x_AxisMap = new HashMap<Integer, Character>();
    x_AxisMap.put(0, 'a');
    x_AxisMap.put(1, 'b');
    x_AxisMap.put(2, 'c');
    x_AxisMap.put(3, 'd');
    x_AxisMap.put(4, 'e');
    x_AxisMap.put(5, 'f');
    x_AxisMap.put(6, 'g');
    x_AxisMap.put(7, 'h');

    Map<Integer, Character> y_AxisMap = new HashMap<Integer, Character>();
    y_AxisMap.put(0, '8');
    y_AxisMap.put(1, '7');
    y_AxisMap.put(2, '6');
    y_AxisMap.put(3, '5');
    y_AxisMap.put(4, '4');
    y_AxisMap.put(5, '3');
    y_AxisMap.put(6, '2');
    y_AxisMap.put(7, '1');

    
    JPanel board = new JPanel(){
        boolean color = true;
        @Override
        public void paint(Graphics graphic){
            graphic.setFont(new Font("AlphaRomaineFont.ttf", Font.PLAIN, 18));
            for(int y = 0; y < 8; y  ){
                for(int x = 0; x < 8; x  ){
                    if(color){
                        graphic.setColor(Color.decode("#f5f1e6"));
                    }
                    else if(!color){
                        graphic.setColor(Color.decode("#449e48"));
                    }
                    graphic.fillRect(x*(screen.getWidth()/8), y*(screen.getHeight()/8), screen.getWidth()/8, screen.getHeight()/8);

                    if(y == 7){
                        graphic.setColor(Color.BLACK);
                        graphic.drawString(String.valueOf(x_AxisMap.get(x)), x*(screen.getWidth()/8) 3,  y*(screen.getHeight()/8) 87);
                        if(color){
                            graphic.setColor(Color.decode("#f5f1e6"));
                        }
                        else if(!color){
                            graphic.setColor(Color.decode("#449e48"));
                        }
                    }

                    if(x == 7){
                        graphic.setColor(Color.BLACK);
                        graphic.drawString(String.valueOf(y_AxisMap.get(y)), x*(screen.getWidth()/8) 80,  y*(screen.getHeight()/8) 15);
                        if(color){
                            graphic.setColor(Color.decode("#f5f1e6"));
                        }
                        else if(!color){
                            graphic.setColor(Color.decode("#449e48"));
                        }
                    }
                    if(x == 0){
                        if(y == 0){
                            Image piece = Piece.Rook.getWhiteRook();
                            graphic.drawImage(piece, x*(screen.getWidth()/8), y*(screen.getWidth()/8), this);
                        }
                    }
                    color = !color;
                }
                color = !color;
            }
        } 
    };
    board.setBounds(0, 0, screen.getWidth(), screen.getHeight());     
    
    screen.add(board);
    return screen;
}
private static int getScreenWidth() {
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    return screenSize.width;
}
private static int getScreenHeight() {
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    return screenSize.height;
}

}

and

public static final class Rook extends Piece{
    Rook(){

    }

    public static Image getWhiteRook(){
        Image image = null;
        try{
            image = Toolkit.getDefaultToolkit().getImage("75_px_white_rook.png");
        }
        catch(Exception e){
            System.out.println("Error");
        }
        return image;
    }
    public Image getBlackRook(){
        Image image = null;
        try{
            image = Toolkit.getDefaultToolkit().getImage("75_px_black_rook.png");
        }
        catch(Exception e){
            System.out.println("Error");
        }
        return image;
    }
}}

The problem piece of code is: (in the Board Class)

 if(x == 0){
    if(y == 0){
      Image piece = Piece.Rook.getWhiteRook();
      graphic.drawImage(piece, x*(screen.getWidth()/8), y*(screen.getWidth()/8), this);
    }
 }

CodePudding user response:

Prefer overriding paintComponent over paint. You should also call super.paintXxx before doing any custom painting. See enter image description here

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public final class Main {
    public static void main(String[] args) {
        new Main();
    }

    public Main() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    Piece.loadResources();
                    JFrame frame = new JFrame();
                    frame.add(new Board());
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                } catch (IOException ex) {
                    ex.printStackTrace();;
                    JOptionPane.showMessageDialog(null, "Failed to load resources", "Error", JOptionPane.ERROR_MESSAGE);
                }
            }
        });
    }

    public class Board extends JPanel {        
        private Map<Integer, Character> x_AxisMap = new HashMap<Integer, Character>();
        private Map<Integer, Character> y_AxisMap = new HashMap<Integer, Character>();

        public Board() {
            setBackground(Color.decode("#ebe4e4"));
            x_AxisMap.put(0, 'a');
            x_AxisMap.put(1, 'b');
            x_AxisMap.put(2, 'c');
            x_AxisMap.put(3, 'd');
            x_AxisMap.put(4, 'e');
            x_AxisMap.put(5, 'f');
            x_AxisMap.put(6, 'g');
            x_AxisMap.put(7, 'h');

            y_AxisMap.put(0, '8');
            y_AxisMap.put(1, '7');
            y_AxisMap.put(2, '6');
            y_AxisMap.put(3, '5');
            y_AxisMap.put(4, '4');
            y_AxisMap.put(5, '3');
            y_AxisMap.put(6, '2');
            y_AxisMap.put(7, '1');
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(720, 720);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            boolean color = true;
            for (int y = 0; y < 8; y  ) {
                for (int x = 0; x < 8; x  ) {
                    if (color) {
                        g2d.setColor(Color.decode("#f5f1e6"));
                    } else if (!color) {
                        g2d.setColor(Color.decode("#449e48"));
                    }
                    g2d.fillRect(x * (getWidth() / 8), y * (getHeight() / 8), getWidth() / 8, getHeight() / 8);

                    if (y == 7) {
                        g2d.setColor(Color.BLACK);
                        g2d.drawString(String.valueOf(x_AxisMap.get(x)), x * (getWidth() / 8)   3, y * (getHeight() / 8)   87);
                        if (color) {
                            g2d.setColor(Color.decode("#f5f1e6"));
                        } else if (!color) {
                            g2d.setColor(Color.decode("#449e48"));
                        }
                    }

                    if (x == 7) {
                        g2d.setColor(Color.BLACK);
                        g2d.drawString(String.valueOf(y_AxisMap.get(y)), x * (getWidth() / 8)   80, y * (getHeight() / 8)   15);
                        if (color) {
                            g2d.setColor(Color.decode("#f5f1e6"));
                        } else if (!color) {
                            g2d.setColor(Color.decode("#449e48"));
                        }
                    }
                    if (x == 0) {
                        if (y == 0) {
                            Image piece = Piece.ROOK.white();
                            g2d.drawImage(piece, x * (getWidth() / 8), y * (getWidth() / 8), this);
                        }
                    }
                    color = !color;
                }
                color = !color;
            }
        }
    }

    public enum Piece {
        ROOK;

        private Image white;
        private Image black;

        public Image white() {
            return white;
        }

        public Image black() {
            return black;
        }

        public static void loadResources() throws IOException {
            Piece.ROOK.white = ImageIO.read(Main.class.getResource("/images/RookWhite.png"));
            Piece.ROOK.black = ImageIO.read(Main.class.getResource("/images/RookBlack.png"));
        }
    }
}

nb: Obviously I'm using different image names, so you'll need to correct for that

  • Related