Графика исчезает по неизвестной причине - PullRequest
0 голосов
/ 12 декабря 2011

Я создаю игру типа линкора, используя свинг.Я рисую изображения на одной панели, и они отображаются нормально, но когда я рисую больше изображений на другой панели, он либо удаляет большинство, если не все изображения на первой панели, и сохраняет изображения на второй панели нетронутыми.Как бы я сделал так, чтобы изображения не исчезали после рисования на панели.

Я искал ответ в Интернете около недели или около того и ничего не нашел ...

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);
}

}

выше приведены мои панели, которые были созданы при первом рисовании функциисетка и вторая - рисовать и изображать на вставленных координатах (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); }}

1 Ответ

5 голосов
/ 12 декабря 2011

Не используйте getGraphics() для получения графического объекта Компонента, и никогда не вызывайте paintComponent(...) напрямую. Графический объект, полученный с помощью getGraphics(), является только временным и не будет сохраняться при перерисовке.

Выполняйте все свои рисования либо непосредственно в методе paintComponent (или вызываемом им методе), либо косвенно в BufferedImage, который затем отображается в paintComponent. Затем вызовите repaint() на компоненте, который должен отображать измененное изображение. Это сообщит JVM, что он должен вызвать paintComponent(...) и передать действительный объект Graphics.

Прежде всего, прочитайте учебники по графике, чтобы узнать, как это сделать правильно. Это все, что вы можете увидеть и почерпнуть из вашего опыта поиска за 1 неделю или около того, поскольку они будут в верхней части любого поиска Google по этому вопросу.

Редактировать
Сказав все это, что-то подсказывает мне, что вы добьетесь большего успеха, вообще не связываясь с каким-либо бизнесом рисования, а вместо этого создадите ImageIcons из ваших изображений и затем отобразите их в JLabels. Это самый простой способ показа изображений с помощью Java Swing.

...