如何将JButton的一个组件转移到我点击的第二个JButton?

时间:2012-05-24 14:27:42

标签: java swing mouseevent jbutton mouselistener

我制作的游戏中有一个名为move(int x1,int y1,int x2,int y2)的方法,它从第一个按钮(x1,y1)移动棋子并将其放在第二个按钮上(x2, Y2)

我如何在GUI中编写方法,当我按下第一个他等待第二个应用移动? p.s(动作完成时按钮图标应该改变)

这是我到目前为止写的:

package eg.edu.guc.dvonn.gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.TextArea;
import java.awt.TextField;

import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;



import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

import eg.edu.guc.dvonn.engine.Board;


public class FirstWindow extends JFrame implements ActionListener, MouseListener {
    JButton Startbutton;
    JPanel welcomePanel;
    JPanel SecondPanel;
    JPanel StandardPanel;
    JPanel custPanel;
    JPanel  panelFill;
    JButton Standard;
    JButton fill;
    JButton put;
    JButton clear;
    JButton cust;
    JButton beginGame;
    JButton clickedButton = null;
    JLabel label;
    JLabel put2;
    TextField rows;
    TextField col;
    Board b;
    JButton[][] button;
    int r1;
    int cc;

    Icon red = new ImageIcon(getClass().getResource("index.jpg"));
    Icon Black=new ImageIcon(getClass().getResource("black.jpg"));
    Icon white= new ImageIcon(getClass().getResource("images.jpg"));



         public FirstWindow(){

             setSize(800,600);
             setVisible(true);
             setLayout(new BorderLayout());

             setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

              welcomePanel = new JPanel();
              welcomePanel.setLayout(new BorderLayout());
              label  = new JLabel("Welcome to Dvonn");
              welcomePanel.add(label, BorderLayout.NORTH);
              welcomePanel.setVisible(true);

             label.setForeground(Color.RED);
             label.setFont(new Font("Serif", Font.PLAIN, 40));


             Startbutton = new JButton ("Start");
             Startbutton.setBackground(Color.BLACK);
             Startbutton.setForeground(Color.RED);
             Startbutton.setFont(new Font("Times New Roman", Font.PLAIN, 40));
             Startbutton.setPreferredSize(new Dimension(120,40));

             welcomePanel.add(Startbutton, BorderLayout.CENTER);

             add(welcomePanel);

             Startbutton.addActionListener(this);


             SecondPanel = new JPanel();
             SecondPanel.setVisible(false);
             SecondPanel.setSize(400,400);
              rows = new TextField();
              col= new TextField();
              SecondPanel.add(rows);
              SecondPanel.add(col);

              fill = new JButton("Fill random");
              fill.addActionListener(this);
              fill.setBackground(Color.LIGHT_GRAY);
              fill.setForeground(Color.BLUE);

          /*    
              put = new JButton("Put");
              put.setBackground(Color.LIGHT_GRAY);
              put.setForeground(Color.BLUE);
            */  
              put2 = new JLabel("Place Pieaces Manually on the Board or Choose Fill Random");
              put2.setBackground(Color.LIGHT_GRAY);
              put2.setForeground(Color.BLUE);

              clear = new JButton("Clear Board");
              clear.addActionListener(this);
              clear.setBackground(Color.LIGHT_GRAY);
              clear.setForeground(Color.BLUE);

              beginGame = new JButton("Start The Game");
              beginGame.addActionListener(this);
              beginGame.setBackground(Color.LIGHT_GRAY);
              beginGame.setForeground(Color.BLUE);
              beginGame.setVisible(false);

              Standard = new JButton("Standardised board");
              Standard.setBackground(Color.LIGHT_GRAY);
              Standard.setForeground(Color.BLUE);
              Standard.addActionListener(this);
              Standard.addMouseListener(this);


              cust = new JButton("customized");
              cust.setBackground(Color.LIGHT_GRAY);
              cust.setForeground(Color.BLUE);
              cust.addActionListener(this);
              cust.addMouseListener(this);

              panelFill = new JPanel();

              panelFill.add(fill);
        //    panelFill.add(put2);
              panelFill.add(clear);
              panelFill.add(beginGame);
              SecondPanel.add(Standard);
              SecondPanel.add(cust);



                this.r1 =5;
                this.cc = 11;
                b = new Board(r1,cc);
                button = new JButton [r1][cc];
                StandardPanel = new JPanel();
                StandardPanel.setBackground(Color.WHITE);
                StandardPanel.setLayout(new GridLayout(r1, cc));
                for (int i = 0; i <= r1 - 1; i++) {
                    for (int j = 0; j <= cc - 1; j++) {
                        button[i][j] = new JButton("Place");
                        button[i][j].addActionListener(this);
                    }
                }
                for (int i = 0; i <= r1 - 1; i++) {
                    for (int j = 0; j <= cc - 1; j++) {

                        button[i][j].setLayout(new FlowLayout());
                        button[i][j].setBackground(Color.WHITE);


                        StandardPanel.add(button[i][j], i, j);



                    }
                }



         }  

         public FirstWindow(int row,int cols){

             setSize(800,600);
             setVisible(true);
             setLayout(new BorderLayout());

             setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


              fill = new JButton("fill random");
              fill.addActionListener(this);
              fill.setBackground(Color.LIGHT_GRAY);
              fill.setForeground(Color.BLUE);

           /*   
              put = new JButton("put");
              put.setBackground(Color.LIGHT_GRAY);
              put.setForeground(Color.BLUE);
             */ 
              put2 = new JLabel("Place Pieaces Manually on the Board or Choose Fill Random");
              put2.setBackground(Color.LIGHT_GRAY);
              put2.setForeground(Color.BLUE);

              clear = new JButton("Clear Board");
              clear.addActionListener(this);
              clear.setBackground(Color.LIGHT_GRAY);
              clear.setForeground(Color.BLUE);

              Standard = new JButton("Standardised board");
              Standard.setBackground(Color.LIGHT_GRAY);
              Standard.setForeground(Color.BLUE);
              Standard.addActionListener(this);
              Standard.addMouseListener(this);

              cust = new JButton("customized");
              cust.setBackground(Color.LIGHT_GRAY);
              cust.setForeground(Color.BLUE);
              cust.addActionListener(this);
              cust.addMouseListener(this);

              panelFill = new JPanel();
              panelFill.add(fill);
        //    panelFill.add(put2);
              panelFill.add(clear);





            this.r1 = row;
            this.cc = cols;



                 b = new Board(r1,cc);  


                button = new JButton [r1][cc];

                custPanel = new JPanel();
                custPanel.setBackground(Color.WHITE);
                custPanel.setLayout(new GridLayout(r1, cc));

                for (int i = 0; i <= r1 - 1; i++) {
                    for (int j = 0; j <= cc - 1; j++) {
                        button[i][j] = new JButton("Place");
                        button[i][j].addActionListener(this);
                    }
                }
                for (int i = 0; i <= r1 - 1; i++) {
                    for (int j = 0; j <= cc - 1; j++) {

                        button[i][j].setLayout(new FlowLayout());
                        button[i][j].setBackground(Color.WHITE);
                        custPanel.add(button[i][j], i, j);

                    }
                }
                add(custPanel);
                add(panelFill,BorderLayout.SOUTH);


         }
         public boolean checkBoard() { // checks if the board is full or not to start the game and the move process
        //   boolean fullBoard = false;
             for (int i = 0; i < this.r1; i++) {
                 for ( int j = 0; j < this.cc; j++) {
                     if(button[i][j].getIcon() == null) {
                         return true;
                     }
                 }

             }
             return false;
         }

         public static void main  (String [] args){
             FirstWindow window = new FirstWindow();



         }
        @Override
        public void actionPerformed(ActionEvent e) {

            if (e.getSource()==Startbutton){

                this.remove(welcomePanel);
                this.add(SecondPanel);
                SecondPanel.setVisible(true);
                //this.add(SecondPanel);

                JLabel label1 = new JLabel("dvonn");
                label1.setForeground(Color.RED);
                label1.setFont(new Font("Serif", Font.PLAIN, 25));
                SecondPanel.add(label1);

                }

                if(e.getSource()== cust){
                   String rowText = rows.getText();
                   String colText = col.getText();

                   r1 = Integer.parseInt(rowText);
                   cc = Integer.parseInt(colText);
                   this.setVisible(false);

                FirstWindow custom = new FirstWindow(r1, cc);




                 } 
                      if(e.getSource()==Standard){ //places the standard panel
                         SecondPanel.setVisible(false); // set the second panel invisible
                         this.add(StandardPanel); //to add the panel with the buttons
                         StandardPanel.setVisible(true);

                         add(put2, BorderLayout.NORTH);
                         add(panelFill,BorderLayout.SOUTH);
                         add(StandardPanel,BorderLayout.CENTER);

                     } 

                if (e.getSource() == fill) { //randomly fills the board
                         b.fillRandom();

                  for (int i = 0; i <=r1-1; i++) {
                    for (int j = 0; j <=cc-1; j++) {
                        if (b.getColor(i, j)==0){
                            button[i][j].setIcon(red);

                        } else if (b.getColor(i, j) == 1) {
                            button[i][j].setIcon(white);
                        } else if (b.getColor(i, j) == 2) {
                            button[i][j].setIcon(Black);
                        }   
                    }
                    }

                  beginGame.setVisible(true); 

                     }


                        if (e.getActionCommand().equals("Place")) {

                        // u press on the button to manually place a piece
                            for(int i=0; i< this.r1; i++){

                             for (int j = 0; j < cc; j++) {
                              if(e.getSource() == button[i][j]){
                               b.put(i, j);
                               if (b.getColor(i, j) == 0) {
                                   button[i][j].setText("");
                                   button[i][j].setIcon(red);
                                   if (checkBoard()) {
                                    beginGame.setVisible(true);   
                                   }
                                   break;
                               } else {
                               if (b.getColor(i, j) == 1) {
                                   button[i][j].setText("");
                                   button[i][j].setIcon(white);
                                   if (checkBoard()) {
                                        beginGame.setVisible(true);   
                                   }
                                   break;
                               } else {
                                   button[i][j].setText("");
                                  button[i][j].setIcon(Black);
                                  if (checkBoard()) {
                                        beginGame.setVisible(true);   
                                    }
                                  break;

                            }
                         }
                     }
                   }
                        }
                         }

                if (e.getSource() == clear) {

                    for (int i = 0; i <= r1 - 1; i++) {
                        for (int j = 0; j <= cc - 1; j++) {
                        button[i][j].setIcon(null); 
                        if (button[i][j].getText().equals("")) {
                            button[i][j].setText("Place");
                        }
                        }
                    }

                }

              if (e.getSource() == beginGame) {  //begins the move part
                  b.currentPhase = 2;
                  panelFill.setVisible(false);
                  remove(panelFill);

              }


            }

        public void mouseClicked(MouseEvent e) { //move mouselistener

            if (b.getCurrentPhase() == 2) {

             if (clickedButton == null) { 

                    clickedButton = button[e.getX()][e.getY()];
                }
                else {
                    // second button, so do the 'move'
                    int x1 = clickedButton.getX();
                    int y1 = clickedButton.getY();
                    int x2 = e.getX();
                    int y2 = e.getY();
                    b.move(x1, y1, x2, y2);
                    if (button[x1][y1].getIcon() == red) {
                        button[x2][y2].setIcon(red);
                        button[x1][y1].setIcon(null);
                    }
                    if (button[x1][y1].getIcon() == white) {
                        button[x2][y2].setIcon(white);
                        button[x1][y1].setIcon(null);
                    }if (button[x1][y1].getIcon() == Black) {
                        button[x2][y2].setIcon(Black);
                        button[x1][y1].setIcon(null);
                    }
                    // clear the clickedButton so that we know the next click is a first click
                    clickedButton = null;
                }
            }


        }

        @Override
        public void mouseEntered(MouseEvent e) {
            // TODO Auto-generated method stub

        }

        @Override
        public void mouseExited(MouseEvent e) {
            // TODO Auto-generated method stub

        }

        @Override
        public void mousePressed(MouseEvent e) {
            // TODO Auto-generated method stub

        }

        @Override
        public void mouseReleased(MouseEvent e) {
            // TODO Auto-generated method stub

        }


}       

2 个答案:

答案 0 :(得分:1)

你应该有一个全局变量,它保存对单击的第一个按钮的引用,然后在单击第二个按钮时使用它。例如......

JButton clickedButton = null;

public void mouseClicked(MouseEvent e){
    if (clickedButton == null){
        // first button clicked - so remember the button
        clickedButton = (JButton)e.getSource();
    }
    else {
        // second button, so do the 'move'
        JButton secondButton = (JButton)e.getSource();
        doMove(clickedButton,secondButton);

        // clear the clickedButton so that we know the next click is a first click
        clickedButton = null;
    }
}

在此代码中,我们有一个JButton全局变量。当此变量为null时,我们知道用户尚未点击任何内容。当变量有值时,我们知道用户已经点击了第一个按钮,这是该变量的值。

因此,当触发mouseClicked()事件并且clickedButton变量有值时,我们知道move clickedButton到刚刚点击的按钮(第二个按钮)。


请注意,我们正在将e.getSource()投射到JButton,而不先检查它实际上是JButton。我没有在上面的代码中包含这个,因为它会使它复杂化,但你应该在做这些演员之前先检查一下,就像这样......

Object sourceObject = e.getSource();
if (sourceObject instanceof JButton){
    JButton button = (JButton)sourceObject;
    // other processing code
}

如果在不是JButton的对象上触发事件,这将防止它失败。


我希望这有道理 - 让我知道你是否需要更好的解释。

答案 1 :(得分:1)

Swing ActionActionListener添加到JButton以致anotherButton.doClick()