使按钮写入数组中的一个JTextField

时间:2014-10-16 15:48:40

标签: java swing jbutton jtextfield

我正在开发一个TextTwist java实现,我正在开发GUI。我想知道你们中的一些Swing天才是否可以帮助我。我正在尝试使用GUI,只要单击一个按钮,该按钮的文本就会写入其下方的第一个空textField。我在思考如何做到这一点时遇到了麻烦。到目前为止我尝试过的第一个按钮点击填充所有TextFields。

任何正确方向的帮助或指示都会很棒。

        private void makeButtonLayout() {
    this.charArray = new char[6];
    ArrayList<Character> charArrayList = new ArrayList<Character>();

        this.charArray = this.randomString.toCharArray();
        for(char tempCharacter : this.charArray){
            charArrayList.add(tempCharacter);
        }

        for (int i = 0; i< 6; i++){

            JButton letterButton = new JButton();
            Character buttonCharacter = charArrayList.get(i);
            charArrayList.remove(i);

            String letterString = buttonCharacter.toString();
            letterButton.setText(letterString);
            this.letterButtonsArray.add(letterButton);
        }

        for (final JButton currentButton : this.letterButtonsArray){
            this.buttonPanel.add(currentButton);    
            currentButton.addActionListener(new ActionListener(){
                @Override
                public void actionPerformed(ActionEvent arg0) {
                    int i = 0;
                    currentButton.setVisible(false);
                    JTextField temporaryTextField = new JTextField();
                    String temporaryString = currentButton.getText();

                    temporaryTextField.setText(temporaryString);

                    if(textFieldArray.get(i).getText().isEmpty()){
                        textFieldArray.get(i).setText(temporaryString);
                        return;
                    }else{
                        i++;
                        return;
                    }

                }

            });
        }
    }

This is a screen shot to help better explain What I'm trying to do

1 个答案:

答案 0 :(得分:0)

我认为你的方法真的很奇怪。您混合了初始化代码和执行代码。这样做:

        for (final JButton currentButton : this.letterButtonsArray){
            this.buttonPanel.add(currentButton);    
            currentButton.addActionListener(new ActionListener(){
                @Override
                public void actionPerformed(ActionEvent arg0) {
                    currentButton.setVisible(false);

                    String temporaryString = currentButton.getText();

                    for(int i = 0; i < textFieldArray.size(); i++)
                      JTextField elem = textFieldArray.get(i);
                      if(elem.getText().equals("")){ // or if you don't want spaces do: elem.getText().trim().equals("");
                          elem.setText(temporaryString);
                          break;
                      }
                    }

                }

            });
        }