简体   繁体   English

Dyanamic JButtons单击更新其他JButtons

[英]Dyanamic JButtons click updating other JButtons

How to create board of 8*8 Jbuttons Dynamically . 如何动态创建8 * 8 Jbuttons板。 And have 3 other button (A, B,C,D) 并有3个其他按钮(A,B,C,D)

How then I use ActionListenet so that user when he click “A Button “ certain Jbuttons in the board will change its background 然后如何使用ActionListenet,以便用户单击“ A Button”时,面板中的某些Jbuttons会更改其背景

Simply I know how to change the button I clicked but not other buttons!!!?? 我只是简单地知道如何更改我单击的按钮,但不能更改其他按钮! How I do that ? 我该怎么做?

    package test;

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Random;

    public class test2 extends javax.swing.JFrame implements ActionListener {


     public JPanel contentPane;
     public  int  GameBoardWidth = 800;
     public  int  GameBoardHeight = 900;
     public  int  ReservedHeight = 100;

     public final int  ButtonRows = 5;
     public final int  ButtonColumns = 5;
     private int ButtonCount = 0;

    private JButton[] GameControlButtons = new JButton[4];
    public test2() {
        initComponents();
              this.contentPane = new JPanel();
        this. contentPane.setOpaque(true);
        this.contentPane.setBackground(Color.LIGHT_GRAY);
        this.contentPane.setLayout(null);
        this.makeGameBoard();
         this.setContentPane(contentPane);
        this.setSize(GameBoardWidth, GameBoardHeight);
        this.setLocationByPlatform(true);
        this.setVisible(true);            
    }

     public void makeGameBoard()
    {
         // Splatter all the buttons
         for (int i = 0; i < this.ButtonRows; i++)
         {
              for (int j = 0; j < this.ButtonColumns; j++)
              {    
                     this.MakeGameButton(i, j);
                     //this.MakeGameButton3(i, j);
              }
         }             
         // Make  Game Control Buttons
          for (int i = 0; i < 4; i++)
          {
                this.MakeGameControlButton(i);
          }
    }
     public void MakeGameButton(int X, int Y)
    {
             int ButtonWidth = this.GameBoardWidth/this.ButtonColumns;
             int ButtonHeight = this.GameBoardHeight/this.ButtonRows;
             ButtonWidth -= 3;
             ButtonHeight -= 25;                 
            JButton button = new JButton();
            button.setName("GameButton," + X +"," + Y);
            button.setSize(ButtonWidth, ButtonHeight);
            Font myFont = new Font("Serif", Font.BOLD, 36);
            button.setFont(myFont);
            // Generate Random Number for button
             Random Rn = new Random();                 
             button.setText("");
             button.setToolTipText(Integer.toString(Rn.nextInt(11)));                 
            // Compute Button Location
            int XCoor =  X * ButtonWidth;
            int YCoor = (this.ReservedHeight/2) + Y * ButtonHeight;                
            button.setLocation(XCoor, YCoor);    
            //Add action listener to button
            button.addActionListener(this);
            this.contentPane.add(button);
    }
      public void MakeGameControlButton(int X)
    {
             int ButtonWidth = 2 * this.GameBoardWidth/this.ButtonColumns;
             int ButtonHeight = this.GameBoardHeight/this.ButtonRows;
             ButtonWidth -= 5;
             ButtonHeight -= 25;                 
            JButton button = new JButton();
            button.setName("GameControlButton" + X);
            button.setSize(ButtonWidth, ButtonHeight);                
            button.setBackground(Color.cyan);                
            Font myFont = new Font("Serif", Font.BOLD, 48);
            button.setFont(myFont);                
            // Compute Button Location
            int XCoor =  X * ButtonWidth;
            int YCoor =  this.GameBoardHeight - (ButtonHeight + 60);                
            button.setLocation(XCoor, YCoor);    
            //Add action listener to button
            button.addActionListener(this);                
            GameControlButtons[ButtonCount] = button;
            ButtonCount++;    
            this.contentPane.add(button);
    }

    /**
     * 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);

        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, 300, 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(test2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(test2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(test2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(test2.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 test2().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify                     
    // End of variables declaration                   

    @Override
    public void actionPerformed(ActionEvent e) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
}

The problem you're facing is encapsulating the JButton in the method. 您面临的问题是将JButton封装在方法中。 So you can't access it from outside the method. 因此,您不能从方法外部访问它。 Instead, have the method return a JButton 而是让方法返回JButton

public JButton MakeGameButton(int X, int Y) {
    JButton button = new JButton();

    ....

    return button;
}

Then you can reference the button elsewhere. 然后,您可以在其他位置引用该按钮。

JButton button1 = MakeGameButton(...);
JButton button2 = MakeGameButton(...);

JButton buttonA = new JButton("A Button");

buttonA.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
         button1.setBackground(...);
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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