Warcaby MouseListener

0

Witam, mam taki problem, wziąłem się za pisanie gry Warcaby i staram się małymi krokami zrealizować swój cel, jestem na etapie rysowania planszy oraz pionków, dodatkowo zrobiłem takie coś, że gdy klikniemy na dany pionek to jego pole się podświetla i problem polega na tym, że gdy zbyt szybko klikamy na pionki to albo ich nie zaznacza albo robi to bardzo wolno.

Oto kod:

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package warcaby;

import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;

/**
*
* @author Rafal
*/
public class Warcaby extends javax.swing.JFrame implements MouseListener {

    int xLocation, yLocation, xRysowanie, yRysowanie;
    int rozmPola = 40;
    int[][] plansza = new int[][]{
    {0, 1, 0, 1, 0, 1, 0, 1},
    {1, 0, 1, 0, 1, 0, 1, 0},
    {0, 1, 0, 1, 0, 1, 0, 1},
    {1, 0, 1, 0, 1, 0, 1, 0},
    {0, 1, 0, 1, 0, 1, 0, 1},
    {1, 0, 1, 0, 1, 0, 1, 0},
    {0, 1, 0, 1, 0, 1, 0, 1},
    {1, 0, 1, 0, 1, 0, 1, 0}};
    int[][] pionki = new int[][]{
    {0, 2, 0, 2, 0, 2, 0, 2},
    {2, 0, 2, 0, 2, 0, 2, 0},
    {0, 2, 0, 2, 0, 2, 0, 2},
    {0, 0, 0, 0, 0, 0, 0, 0},
    {0, 0, 0, 0, 0, 0, 0, 0},
    {1, 0, 1, 0, 1, 0, 1, 0},
    {0, 1, 0, 1, 0, 1, 0, 1},
    {1, 0, 1, 0, 1, 0, 1, 0}};

    /**
     * Creates new form Warcaby
     */
    public Warcaby() {
        this.setLocation(200, 200);
        initComponents();
        addMouseListener(this);

    }
   
    public void paint(Graphics g) {
        xLocation = 40;
        yLocation = 50;
        for (int x = 0; x < 8; x++) {
            for (int y = 0; y < 8; y++) {
                if (xLocation < x_mouse && (xLocation + rozmPola) > x_mouse && yLocation < y_mouse && (yLocation + rozmPola) > y_mouse && plansza[x][y] == 1 && pionki[y][x] != 0) {
                    g.setColor(Color.getHSBColor(300, 400, 200));
                } else {
                    if (plansza[x][y] == 1) {
                        g.setColor(Color.getHSBColor(0, 0, 0));
                    } else if (plansza[x][y] == 0) {
                        g.setColor(Color.getHSBColor(200, 200, 200));
                    }
                }
                g.fillRect(xLocation, yLocation, rozmPola, rozmPola);
                yLocation = yLocation + rozmPola;
            }
            xLocation = xLocation + rozmPola;
            yLocation = 50;
        }
        xLocation = 40;
        for (int x = 0; x < 8; x++) {
            for (int y = 0; y < 8; y++) {
                if (pionki[y][x] == 1) {
                    g.setColor(Color.getHSBColor(100, 100, 100));
                } else if (pionki[y][x] == 2) {
                    g.setColor(Color.getHSBColor(250, 250, 250));
                }
                if (pionki[y][x] != 0) {
                    g.fillOval(xLocation, yLocation, rozmPola, rozmPola);
                }
                yLocation = yLocation + rozmPola;
            }
            xLocation = xLocation + rozmPola;
            yLocation = 50;
        }
        x_mouse = 0;
        y_mouse = 0;
    }

    public void update(Graphics g)
    {
           paint(g);
     }
   
    int x_mouse = 0, y_mouse = 0;

    public void przesowanie() {

    }

    @Override
    public void mouseClicked(MouseEvent ev) {
        x_mouse = ev.getX();
        y_mouse = ev.getY();
        repaint();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
    private void initComponents() {

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setPreferredSize(new java.awt.Dimension(400, 400));
        setResizable(false);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>                       

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
       
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Warcaby.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Warcaby.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Warcaby.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Warcaby.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Warcaby().setVisible(true);

            }
        });
    }

    @Override
    public void mousePressed(MouseEvent me) {
       
    }

    @Override
    public void mouseReleased(MouseEvent me) {
       
    }

    @Override
    public void mouseEntered(MouseEvent me) {
       
    }

    @Override
    public void mouseExited(MouseEvent me) {
       
    }
}

    // Variables declaration - do not modify                    
    // End of variables declaration                  
 

Czy ktoś byłby mi wstanie wytłumaczyć dlaczego tak się dzieje i dać jakieś wskazówki jak zrobić to aby działo się to odpowiednio szybko? Dodam, że nie jestem jakimś wirtuozem programowania i zajmuję się tym od niedawna.

0

Zbyt wiele robisz w metodzie paint. Kiepski jest też pomysł by MouseListener był podpięty do całego okna. Lepiej jest rozmieścić w oknie 64 przyciski i do połowy z nich podpiąć ActionListenera. Poniżej przykładowy kod - wykonanie ruchu zmienia tylko ikonę na przycisku.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Warcaby extends JFrame
{
    private Color light = new Color(224,196,155);
    private Color dark = new Color(149,95,33);
    private Icon whiteIcon = new Ikona(new Color(248,248,248));
    private Icon blackIcon = new Ikona(new Color(0,135,189));
    private Field[][] fields = new Field[8][8];
    private Listener listener = new Listener();
    private Field from = null;
    public enum players
    {
        WHITE,BLACK
    };
    private players player = players.WHITE;
    //------------------------
    public static void main(String[] args)
    {
        new Warcaby();
    }
    //------------------------
    public Warcaby()
    {
        setTitle("Warcaby");
        add(new Plansza(),BorderLayout.CENTER);
        pack();
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }
    //------------------------
    Icon playerIcon()
    {
        if(player == players.WHITE)
        {
            return whiteIcon;
        }
        else
        {
            return blackIcon;
        }
    }
    //------------------------
    boolean moveIsPossible(int xFrom,int yFrom)
    {
        //sprawdzenie czy ruch jest możliwy
        return true;
    }
    //------------------------
    class Plansza extends JPanel
    {
        public Plansza()
        {
            setBackground(Color.BLACK);
            setLayout(new GridLayout(8,8,2,2));
            for(int i=0;i<8;i++)
            {
                for(int j=0;j<8;j++)
                {
                    Field p = new Field(i,j);
                    fields[i][j] = p;
                    if((i+j) % 2 == 0)
                    {
                        p.setBackground(light);
                    }
                    else
                    {
                        p.setBackground(dark);                        
                        p.addActionListener(listener);
                    }
                    if(i < 3 && (i+j) % 2 == 1)
                    {
                        p.setIcon(blackIcon);
                    }
                    if(i > 4 && (i+j) % 2 == 1)
                    {
                        p.setIcon(whiteIcon);
                    }
                    add(p);                    
                }
            }
        }
    }
    //------------------------
    class Field extends JButton
    {
        int row;
        int col;
        public Field(int row, int col)
        {
            this.row = row;
            this.col = col;
            setPreferredSize(new Dimension(50,50));
        }
    }
    //------------------------
    class Listener implements ActionListener
    {
        public void actionPerformed(ActionEvent ae)
        {
            if(from == null)
            {
                Field p = (Field)(ae.getSource());
                if(p.getIcon() == playerIcon() && moveIsPossible(p.row,p.col))
                {
                    from = (Field)(ae.getSource());
                }
                return;
            }
            Field toWhere = (Field)(ae.getSource());
            if(toWhere.getIcon() != null)
            {
                return;
            }
            toWhere.setIcon(from.getIcon());
            from.setIcon(null);
            from = null;
        }
    }
    //------------------------
    public class Ikona implements Icon
    {
        private Color color;
        //------------------------
        Ikona(Color color)
        {
            this.color = color;
        }
        //--------------------
        public void paintIcon(Component c,Graphics g,int x,int y)
        {
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);        
            g2.setColor(color);
            g2.fillOval(10,15,30,10);
            g2.fillOval(10,25,30,10);
            g2.setColor(Color.BLACK);        
            g2.drawOval(10,25,30,10);
            g2.drawLine(10,20,10,30);
            g2.drawLine(40,20,40,30);
            g2.setColor(color);
            g2.fillRect(10,20,30,10);
            g2.setColor(Color.BLACK);
            g2.drawOval(10,15,30,10);

        }
        //--------------------
        public int getIconWidth()
        {
            return 30;
        }
        //--------------------
        public int getIconHeight()
        {
            return 20;
        }
    }    
}

Zarejestruj się i dołącz do największej społeczności programistów w Polsce.

Otrzymaj wsparcie, dziel się wiedzą i rozwijaj swoje umiejętności z najlepszymi.