简体   繁体   中英

Graphics disappear for unknown reason

I am creating a battleship type game using swing. i draw images in one panel and it shows up fine, but when i draw more images in a different panel it either deletes most if not all of the images in the first panel and keeps the images in the second panel intact. How would I go about keeping the images from disappearing after drawn in the panel.

I have been searching for an answer online for about a week or so and have come up with nothing...

public class GameBoard extends JPanel{
Graphics g0;
public void paintComponent(Graphics g1) {
    g0 = this.getGraphics();
    // fill with the color you want
    int wide = 275;
    int tall = 275;

    // go into Graphics2D for all the fine art, more options
    // optional, here I just get variable Stroke sizes
    Graphics2D g2 = (Graphics2D) g1;
    g2.setColor(Color.black);
    g2.setStroke(new BasicStroke(1));
    Graphics2D g3 = (Graphics2D) g0;
    g3.setColor(Color.black);
    g3.setStroke(new BasicStroke(1));
    // the verticals
    for (int i = 0; i < 12*25; i+=25) {
        g2.drawLine(i, 0, i, tall);
        g3.drawLine(i, 0, i, tall);
    }
    // the horizontal
    for (int i = 0; i < 12*25; i+=25) {
        g2.drawLine(0, i, wide, i);
        g3.drawLine(0, i, wide, i);
    }
    g0 = this.getGraphics();
} 
public void paintComponent(Image i, int x, int y) {
    g0.drawImage(i, x, y, null);
}

}

the above are my panels that are created the first function draws the grid and the second is to draw and image at the inserted cooridnates (x,y)

public class Game {
static JFrame main = new JFrame();
static GameBoard panel = new GameBoard(), panel1 = new GameBoard();
static Container c = main.getContentPane();
static JLabel title = new JLabel("BattleShip!");
static int count = 0, x, y, j;
static String b;
static BufferedImage pB = null, aC = null, bS = null, deS = null, suB = null;
static BattleShips[] player = new BattleShips[5];
static BattleShips[] computer = new BattleShips[5];
static Graphics g;

public static void setup(){
    player[0] = new BattleShips();
    player[1] = new BattleShips();
    player[2] = new BattleShips();
    player[3] = new BattleShips();
    player[4] = new BattleShips();
    computer[0] = new BattleShips();
    computer[1] = new BattleShips();
    computer[2] = new BattleShips();
    computer[3] = new BattleShips();
    computer[4] = new BattleShips();
    c.add(title);
    c.add(panel);
    c.add(panel1);
    panel.setAlignmentY(Component.CENTER_ALIGNMENT);
    panel.setAlignmentX(Component.CENTER_ALIGNMENT);
    panel.setSize(276, 276);
    panel1.setAlignmentY(Component.CENTER_ALIGNMENT);
    panel1.setAlignmentX(Component.CENTER_ALIGNMENT);
    panel1.setSize(276, 276);
    title.setAlignmentY(Component.CENTER_ALIGNMENT);
    title.setAlignmentX(Component.CENTER_ALIGNMENT);

    main.setVisible(true);
    main.setSize(new Dimension(291,630));
    main.setResizable(true);
    main.setLayout(new BoxLayout(c, BoxLayout.Y_AXIS));
    main.setLocation(400, 15);
    main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    Graphics g = panel.getGraphics(), g1 = panel1.getGraphics();
    panel.paintComponent(g);
    panel1.paintComponent(g1);
    panel.setBorder(new EmptyBorder(0,0,25,0));

    panel1.addMouseListener(new MouseListener(){

        @Override
        public void mouseClicked(MouseEvent e) {

            String d = "H";


            switch(count){
            case 0:
                player[0].Name = "patrolBoat";
                player[0].x[0] = e.getX()-(e.getX()%25);
                player[0].y[0] = (e.getY()-(e.getY()%25));
                Object[] possibilities = {"H", "V"};
                 d = (String)JOptionPane.showInputDialog(
                                    main,
                                    "Place " + player[0].Name + " vertically or horizontally?",
                                    "Customized Dialog",
                                    JOptionPane.PLAIN_MESSAGE,
                                    null,
                                    possibilities,
                                    "ham");
                try {pB = ImageIO.read(new File("src/resources/"+player[0].Name+d+".png"));} catch (IOException e1) {}
                panel1.paintComponent(pB,player[0].x[0],player[0].y[0]);
                count++;
                break;
            case 1:
                player[1].Name = "battleship";
                player[1].x[0] = e.getX()-(e.getX()%25);
                player[1].y[0] = (e.getY()-(e.getY()%25));
                Object[] possibilities1 = {"H", "V"};
                 d = (String)JOptionPane.showInputDialog(
                                    main,
                                    "Place " + player[1].Name + " vertically or horizontally?",
                                    "Customized Dialog",
                                    JOptionPane.PLAIN_MESSAGE,
                                    null,
                                    possibilities1,
                                    "ham");

                try {bS = ImageIO.read(new File("src/resources/"+player[1].Name+d+".png"));} catch (IOException e1) {}
                panel1.paintComponent(bS,player[1].x[0],player[1].y[0]);
                count++;
                break;
            case 2:
                player[2].Name = "aircraftCarrier";
                player[2].x[0] = e.getX()-(e.getX()%25);
                player[2].y[0] = (e.getY()-(e.getY()%25));
                Object[] possibilities11 = {"H", "V"};
                 d = (String)JOptionPane.showInputDialog(
                                    main,
                                    "Place " + player[2].Name + " vertically or horizontally?",
                                    "Customized Dialog",
                                    JOptionPane.PLAIN_MESSAGE,
                                    null,
                                    possibilities11,
                                    "ham");
                try {aC = ImageIO.read(new File("src/resources/"+player[2].Name+d+".png"));} catch (IOException e3) {}
                panel1.paintComponent(aC,player[2].x[0],player[2].y[0]);
                count++;
                break;
            case 3:
                player[3].Name = "destroyer";
                player[3].x[0] = e.getX()-(e.getX()%25);
                player[3].y[0] = (e.getY()-(e.getY()%25));
                Object[] possibilities111 = {"H", "V"};
                 d = (String)JOptionPane.showInputDialog(
                                    main,
                                    "Place " + player[3].Name + " vertically or horizontally?",
                                    "Customized Dialog",
                                    JOptionPane.PLAIN_MESSAGE,
                                    null,
                                    possibilities111,
                                    "ham");

                try {deS = ImageIO.read(new File("src/resources/"+player[3].Name+d+".png"));} catch (IOException e2) {}
                panel1.paintComponent(deS,player[3].x[0],player[3].y[0]);
                count++;
                break;
            case 4:
                player[4].Name = "submarine";
                player[4].x[0] = e.getX()-(e.getX()%25);
                player[4].y[0] = (e.getY()-(e.getY()%25));
                Object[] possibilities1111 = {"H", "V"};
                 d = (String)JOptionPane.showInputDialog( main, "Place " + player[4].Name + " vertically or horizontally?", "Customized Dialog",JOptionPane.PLAIN_MESSAGE,null, possibilities1111, "ham");
                 try {suB = ImageIO.read(new File("src/resources/"+player[4].Name+d+".png"));} catch (IOException e1) {}
                panel1.paintComponent(suB,player[4].x[0],player[4].y[0]);
                count = 5;
                break;
            case 5:
                try {setupComp();
                count++;} catch (IOException e1) {}
            }


        }

        @Override
        public void mousePressed(MouseEvent e) {}

        @Override
        public void mouseReleased(MouseEvent e) {}

        @Override
        public void mouseEntered(MouseEvent e) {}

        @Override
        public void mouseExited(MouseEvent e) {}
    });

}

static void setupComp() throws IOException{
    b = "H";
    g = panel.getGraphics();

    ////////DESTROYER
    j = (int) (Math.random()*1);
    computer[1].Name = "destroyer";
    if(j == 0){
        b = "H";
        deS = ImageIO.read(new File("src/resources/"+computer[1].Name+b+".png"));}
    else if(j == 1){
        b = "V";
        deS = ImageIO.read(new File("src/resources/"+computer[1].Name+b+".png"));}

    computer[1].x[0] = ((int)(Math.random()*150));
    computer[1].x[0] = computer[1].x[0]-computer[1].x[0]%25;
    computer[1].y[0] = ((int)(Math.random()*150));
    computer[1].y[0] = computer[1].y[0]-computer[1].y[0]%25;
    ///////END DESTROYER

    //////PATROL BOAT
    j = (int) (Math.random()*1);
    computer[2].Name = "patrolBoat";
    switch(j){
    case 0:
        b = "H";
        pB = ImageIO.read(new File("src/resources/"+computer[2].Name+b+".png"));
    case 1:
        b = "V";
        pB = ImageIO.read(new File("src/resources/"+computer[2].Name+b+".png"));
    }
    computer[2].x[0] = ((int)(Math.random()*225));
    computer[2].x[0] = computer[2].x[0]-computer[2].x[0]%25;
    computer[2].y[0] = ((int)(Math.random()*225));
    computer[2].y[0] = computer[2].y[0]-computer[2].y[0]%25;


    ///////END PATROL BOAT

    ///////AIRCRAFT CARRIER
    j = (int) (Math.random()*1);
    computer[3].Name = "aircraftCarrier";
    switch(j){
    case 1:b = "H";
        aC = ImageIO.read(new File("src/resources/"+computer[3].Name+b+".png"));
    case 0:
        b = "V";
        aC = ImageIO.read(new File("src/resources/"+computer[3].Name+b+".png"));
    }
    computer[3].x[0] = ((int)(Math.random()*125));
    computer[3].x[0] =computer[3].x[0]-computer[3].x[0]%25;
    computer[3].y[0] = ((int)(Math.random()*125));
    computer[3].y[0] = computer[3].y[0]-computer[3].y[0]%25;
    ///////END AIRCRAFT CARRIER

    ///////SUBMARINE
    j = (int) (Math.random()*1);
    computer[4].Name = "submarine";
    switch(j){
    case 0:b = "H";
        suB = ImageIO.read(new File("src/resources/"+computer[4].Name+b+".png"));
    case 1:
        b = "V";
        suB = ImageIO.read(new File("src/resources/"+computer[4].Name+b+".png"));
    }
    computer[4].x[0] = ((int)(Math.random()*200));
    computer[4].x[0] = computer[4].x[0]-computer[4].x[0]%25;
    computer[4].y[0] = ((int)(Math.random()*200));
    computer[4].y[0] = computer[4].y[0]-computer[4].y[0]%25;
    //END SUBMARINE

    ///////BATTLESHIP
    j = (int) (Math.random()*1);
    computer[0].Name = "battleship";
    switch(j){
    case 1:b = "H";
        bS = ImageIO.read(new File("src/resources/"+computer[0].Name+b+".png"));
    case 0:
        b = "V";
        bS = ImageIO.read(new File("src/resources/"+computer[0].Name+b+".png"));
    }
    computer[0].x[0] = ((int)(Math.random()*200));
    computer[0].x[0] = computer[0].x[0]-computer[0].x[0]%25;
    computer[0].x[0] = ((int)(Math.random()*200));
    computer[0].x[0] = computer[0].y[0]-computer[0].y[0]%25;
    ///////END BATTLESHIP

    System.out.println(computer[0].x[0]+","+computer[0].y[0]);
    System.out.println(computer[1].x[0]+","+computer[1].y[0]);
    System.out.println(computer[2].x[0]+","+computer[2].y[0]);
    System.out.println(computer[3].x[0]+","+computer[3].y[0]);
    System.out.println(computer[4].x[0]+","+computer[4].y[0]);
    g.drawImage(bS, computer[0].x[0], computer[0].x[0], null);
    g.drawImage(aC, computer[1].x[0], computer[1].x[0], null);
    g.drawImage(pB, computer[2].x[0], computer[2].x[0], null);
    g.drawImage(suB, computer[3].x[0], computer[3].x[0], null);
    g.drawImage(deS, computer[4].x[0], computer[4].x[0], null); }}

Don't use getGraphics() to obtain the Graphics object of a Component, and never call paintComponent(...) directly yourself. The Graphics object obtained via getGraphics() is only temporary and will not persist whenever a repainting occurs.

Do all your painting either directly in the paintComponent method (or method called by it), or indirectly in a BufferedImage that is then displayed in paintComponent. Then call repaint() on the component that needs to display a changed image. This will tell the JVM that it should call paintComponent(...) and pass in a valid Graphics object.

Above all, read the graphics tutorials to see how to do it right. It's all there for you to see and learn from -- your "1 week or so" of searching should have found these as they'll be at the top of any Google search on the subject.

Edit
Having said all this, something tells me that you will do better by not messing with any of this drawing business at all, but instead create ImageIcons from your images and then displaying them in JLabels. This is the easiest way to show images using Java Swing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM