java - 动态按钮单击更新其他 JButton

标签 java swing netbeans jbutton

如何动态创建8*8 Jbuttons板 。还有另外 3 个按钮(A、B、C、D)

然后我如何使用 ActionListenet,以便用户在单击“A Button”时,板上的某些 Jbutton 会更改其背景

我只是知道如何更改我单击的按钮,但不知道如何更改其他按钮!!!? 我该怎么做?

    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.
    }
}

最佳答案

您面临的问题是将 JButton 封装在方法中。因此您无法从方法外部访问它。相反,让该方法返回一个 JButton

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

    ....

    return button;
}

然后您可以在其他地方引用该按钮。

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

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

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

关于java - 动态按钮单击更新其他 JButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20581756/

相关文章:

java - 如何改变JFrame的背景颜色

java - NetBeans - Java EE 服务器类路径设置不正确 - 服务器主目录丢失错误

tomcat - 服务器位置(Catalina Home)文件夹无效

Java Swing 窗口未出现在 Eclipse 中

java - c++ 像 protected in java

java - 通过注释快速添加日志记录(例如用于 getter/setter 的 lombok) - 有可用的解决方案吗?

java - 在单个项目 netbeans 中有两个同名的 jar 文件

Java mysql 错误 : Could not find or load main class lib\mysql-connector-java-5. 1.25-bin.jar

java - KeyListener 不工作?

java - 康威的生命游戏 GUI