【问题标题】:grid of buttons and actionlistener按钮网格和动作监听器
【发布时间】:2017-03-08 04:24:18
【问题描述】:

我正在使用以下代码通过 (ySize = 10) JButtons 创建一个 (xSize = 10) 网格。只要我在此代码所在的类中进行更改,我就可以更改按钮。

但是我试图从一个单独的类中更改按钮上的文本。

public class Ocean {

public Ocean(){
}

private final int xSize = 10;
private final int ySize = 10;
private final JButton[][] buttons = new JButton[xSize][ySize];

public gameBoard() {
    for (int row = 0; row < xSize; row++) {
        for (int col = 0; col < ySize; col++) {
            buttons[row][col] = new JButton(/*space1*/);
            buttons[row][col].setText("E");
            buttons[row][col].addActionListener(new myActionListener()); 
            buttons[row][col].setPreferredSize(new Dimension(50, 50));
            playerPanel.add(buttons[row][col]);
        }
    }

}

下一课

public class Battleship {

    int length = 4;

    public Battleship() {
    }

    public changeText(int row, int col) {
        ocean.buttons[row][col].setText("H");     need to make this work
    }

我希望这可以更好地提出问题

谢谢

【问题讨论】:

    标签: java variables actionlistener private


    【解决方案1】:

    你的问题归结为它的本质是:我怎样才能让一个对象改变另一个对象的状态?

    有很多可能的方法来给这只猫换皮,但最简单的是给一个类,这里​​是 Ocean(或者可能是 gameBoard?你的代码很混乱)外部 ActionListener 可以调用的公共方法来改变它的状态。例如,您可以给按钮网格持有类一个公共方法: setText(...) 像这样:

    public void setText(int row, int col, String text) {
        buttons[row][col].setText(text);
    }
    

    ActionListener 可以通过构造函数参数传递对这个网格持有类的引用,允许它在需要时调用这个方法。

    还请注意,您始终可以通过 ActionListener actionPerformed 方法的 ActionEvent 参数获取对按下的 JButton 的引用。它有一个getSource() 方法,该方法返回对启动事件的对象(此处为 JButton)的引用。

    如果您需要更详细的解决方案,请考虑创建并发布有效的Minimal, Complete, and Verifiable example

    例如:

    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    import javax.swing.*;
    
    public class SimpleButtonGridMain extends JPanel {
        private static void createAndShowGui() {
            SimpleButtonGrid simpleButtonGrid = new SimpleButtonGrid();
    
            MyButtonListener myButtonListener = new MyButtonListener();
            simpleButtonGrid.addActionListener(myButtonListener);
    
            JFrame frame = new JFrame("SimpleButtonGridMain");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.getContentPane().add(simpleButtonGrid);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(() -> createAndShowGui());
        }
    }
    
    class SimpleButtonGrid extends JPanel {
        private static final int ROWS = 10;
        private static final int COLS = ROWS;
        private JButton[][] buttons = new JButton[ROWS][COLS];
    
        public SimpleButtonGrid() {
            setLayout(new GridLayout(ROWS, COLS, 3, 3));
            for (int row = 0; row < buttons.length; row++) {
                for (int col = 0; col < buttons[row].length; col++) {
                    String text = String.format("  [  %d,  %d  ]  ", col, row);
                    JButton button = new JButton(text);
                    add(button);
                    buttons[row][col] = button;
                }
            }
        }
    
        public void addActionListener(ActionListener listener) {
            for (JButton[] jButtons : buttons) {
                for (JButton jButton : jButtons) {
                    jButton.addActionListener(listener);
                }
            }
        }
    }
    
    class MyButtonListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            String actionCommand = e.getActionCommand();
            JButton sourceBtn = (JButton) e.getSource();
    
            String message = "Button pressed: " + actionCommand;
            JOptionPane.showMessageDialog(sourceBtn, message, "Button Pressed", JOptionPane.PLAIN_MESSAGE);
            sourceBtn.setText("Pressed");
            sourceBtn.setEnabled(false);
        }
    }
    

    【讨论】:

      【解决方案2】:

      不清楚您想在代码中做什么。如果单击按钮,您的示例代码会更改每个按钮的文本。

      也许您想更改单击按钮的文本,那么这段代码可能会有所帮助:

      @Override
      public void actionPerformed(ActionEvent e) {
          JButton theClickedButton = (JButton) e.getSource();
          theClickedButton.setText("M");
      }
      

      【讨论】:

      • 我意识到我对我的问题不太清楚,哈哈,我真的不知道如何或问什么。感谢您的努力。我正在尝试做的是在板上放置一艘船,我选择的位置将根据船型将文本更改为一组字母。我正在使用 actionPerformed 来点击玩家猜测的按钮。
      • 我认为您不应该保留船舶位置的信息并在 JButton 数组中输入,而是在表示此信息的类中。每一次按钮点击都会改变点击位置的信息(仅仅是海洋吗?一艘船和什么类型的船?)。此类还可以保留有关已单击位置的信息,从而通过禁用按钮来避免再次单击。
      【解决方案3】:

      这对我有用。在该类中,我使用了一个在其参数中调用该类的方法。

      public void placeShipAt(int row, int column, Ocean ocean) {
      
              ocean.buttons[row][column].setText("B");
      }
      

      【讨论】:

        猜你喜欢
        • 2013-12-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-04
        • 2013-03-01
        • 2023-04-06
        • 1970-01-01
        • 2021-02-15
        相关资源
        最近更新 更多