【问题标题】:How can I add single character to the JTextField by pressing the JButton如何通过按 JButton 将单个字符添加到 JTextField
【发布时间】:2013-05-25 01:43:58
【问题描述】:

我正在创建一个简单的程序,它允许我通过按 JButton 将单个字符添加到 JTextField。在这个程序中,我有一个名为 words 的字符串数组,并且我有一个字符串名称 word,它允许我从单词数组中随机选择单词。我正在使用 for 循环 来绘制 JTextFields。 JTextField 的数量取决于 word

的长度
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.text.*;
    import java.util.Random;

    public class secondTab extends JFrame 
         {
             JTabbedPane Pane = new JTabbedPane();

             JPanel second = new JPanel();

             JButton guess1 = new JButton();

             Random r = new Random();

             JTextField Text[] = new JTextField[10];

             JButton A = new JButton();

             String words[] = {"JAVA" , "FLOAT" , "MAIN" , "STATIC", "FINAL", "PRIVATE" , "CHAR", "BOOLEAN" ,  "CASE"}; // An array to put the words

             String word = words[r.nextInt(words.length)];

             int i;

    public static void main(String args[]) 
        {
            //construct frame
            new secondTab().show();
        }

    public secondTab() 
        {
            // code to build the form
            setTitle("Adding Character");

            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);     
            getContentPane().setLayout(new GridBagLayout());

            // position tabbed pane
            GridBagConstraints gridConstraints = new GridBagConstraints();
            gridConstraints.gridx = 1;
            gridConstraints.gridy = 1;
            Pane.setForeground(Color.YELLOW);
            Pane.setBackground(Color.MAGENTA);

            getContentPane().add(Pane, gridConstraints);
            getContentPane().setLayout(new GridBagLayout());



            second.setLayout(new GridBagLayout());

            guess1.setText("New Word");
            gridConstraints.gridx = 0;
            gridConstraints.gridy = 0;
            second.add(guess1, gridConstraints);

            for( i = 1; i <=word.length(); i++)
                {
                    Text[i] = new JTextField();
                    Text[i].setPreferredSize(new Dimension(80, 80));
                    gridConstraints.gridx = 0;
                    gridConstraints.gridy = 2;
                    second.add(Text[i]);
                }  




            A.setText("A");
            A.setPreferredSize(new Dimension(80, 80));
            gridConstraints.gridx = 0;
            gridConstraints.gridy = 2;
            A.setHorizontalAlignment(SwingConstants.CENTER);
            second.add(A, gridConstraints);

我有一个名为 A 的 JButton,这个 JButton 有一些错误。我有一个名为choice 的字符串,它只包含一个字符“Ä”。所以,我在我的 Jbutton 中添加了一些方法,将字符串 choiceword (上面随机选择的单词)进行比较。它在 word 中找到“A”,它必须将 Jtextfield 中的“A”绘制到特定位置但它没有绘制...

            A.addActionListener(new ActionListener() 
                {
                    public void actionPerformed(ActionEvent e) 
                        {               
                              String choice = "A";

                              if (i < word.length() & i < choice.length())
                                {
                                    if (word.charAt(i) == choice.charAt(i))
                                        {
                                           Text[i].setText(choice.charAt(i) + " ");
                                        }
                                }  
                        }
                });

            // Action Performed method for the JButton guess1
            guess1.addActionListener(new ActionListener() 
                {
                    public void actionPerformed(ActionEvent e) 
                        {
                            dispose();
                            new secondTab().show();
                        }
                });


            Pane.addTab("Game ", second); 

            pack();
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            setBounds((int) (0.5 * (screenSize.width - getWidth())), (int) (0.5 * 
                    (screenSize.height - getHeight())), getWidth(), getHeight());
        }

    }

请检查视频http://www.youtube.com/watch?v=Tx5QsET9IWs 从 0.41 秒开始。我也想做同样的事情...

谢谢....

【问题讨论】:

  • 我认为你的actionPerfomed方法的逻辑是错误的......
  • 这是可能的,因为我真的不知道该怎么做。我检查了一些程序并理解了它们,然后我做到了..
  • 1.为了尽快获得更好的帮助,请发布SSCCE。 2. 一个空白行总是足够的。 3. 类名、方法名和属性名请学习常用Java naming conventions(特别是名称的大小写)并统一使用。

标签: java swing jbutton jtextfield


【解决方案1】:

问题在于i变量的使用

它首先用于构造字段

for( i = 1; i <=word.length(); i++)
{
    Text[i] = new JTextField();
    Text[i].setPreferredSize(new Dimension(80, 80));
    gridConstraints.gridx = 0;
    gridConstraints.gridy = 2;
    second.add(Text[i]);
}  

这意味着i 现在等于word.length()

然后你重新使用变量(原样)......

public void actionPerformed(ActionEvent e) 
{               
    String choice = "A";

    if (i < word.length() & i < choice.length())
    {
        if (word.charAt(i) == choice.charAt(i))
        {
            Text[i].setText(choice.charAt(i) + " ");
        }
    }  
}

这行不通。 i 等于word.length(),这意味着它永远不会进入if 语句的第一级。

i 设为本地并仅用于构建字段数组。

actionPerformed 方法中,您只需检查单词中出现的所有A 并设置适当的文本字段

更新了工作示例...

有许多技巧可以尝试在String 中找到所有出现的字符的索引。

最简单的方法是简单地遍历 String 的长度并使用 String#charAt 并将其与您尝试匹配的值进行比较...

for (int index = 0; index < word.length(); index++) {
    if (Character.toLowerCase(word.charAt(index)) == Character.toLowerCase(choice)) {
        Text[index].setText(Character.toString(choice));
    }
}

我使用了一种稍微复杂但灵活的方法,使用正则表达式来查找给定模式的所有出现...

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.AbstractAction;
import static javax.swing.Action.NAME;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class WordGuess {

    public static void main(String[] args) {
        new WordGuess();
    }

    public WordGuess() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Test");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }

        });
    }

    public static class TestPane extends JPanel {

        public static final String WORDS[] = {"JAVA", "FLOAT", "MAIN", "STATIC", "FINAL", "PRIVATE", "CHAR", "BOOLEAN", "CASE"}; // An array to put the words
        private String word;
        private List<JTextField> fields;
        private JPanel pnlFields;

        public TestPane() {
            setLayout(new BorderLayout());
            pnlFields = new JPanel();
            add(pnlFields);

            JPanel buttons = new JPanel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridx = 0;
            gbc.gridy = 0;
            for (int index = 0; index < 26; index++) {
                if (index % 13 == 0) {
                    gbc.gridx = 0;
                    gbc.gridy++;
                }
                gbc.gridx++;
                JButton btn = new JButton(new LetterAction(Character.toString((char) ('A' + index))));
                btn.setMargin(new Insets(0, 0, 0, 0));
                buttons.add(btn, gbc);
            }

            add(buttons, BorderLayout.NORTH);

            reset();
        }

        public void reset() {

            word = WORDS[(int) Math.round(Math.random() * (WORDS.length - 1))];
            pnlFields.removeAll();
            fields = new ArrayList<>(word.length());
            for (int index = 0; index < word.length(); index++) {
                JTextField field = new JTextField(3);
                field.setEditable(false);
                field.setHorizontalAlignment(JTextField.CENTER);
                pnlFields.add(field);
                fields.add(field);
            }

        }

        protected class LetterAction extends AbstractAction {

            public LetterAction(String value) {
                putValue(NAME, value);
            }

            @Override
            public void actionPerformed(ActionEvent e) {
                String value = getValue(NAME).toString().toLowerCase();
                List<Integer[]> occurances = findAllIndicies(word.toLowerCase(), value);
                System.out.println(word + " has " + occurances.size() + " occurances of " + value);
                for (Integer[] index : occurances) {
                    fields.get(index[0]).setText(value.toUpperCase());
                }
            }
        }
    }

    public static List<Integer[]> findAllIndicies(String value, String regExp) {
        Pattern pattern = Pattern.compile(regExp);
        return findAllIndicies(value, pattern);
    }

    public static List<Integer[]> findAllIndicies(String value, Pattern pattern) {
        Matcher matcher = pattern.matcher(value);
        String match = null;
        List<Integer[]> lstMatches = new ArrayList<Integer[]>(5);
        while (matcher.find()) {
            int startIndex = matcher.start();
            int endIndex = matcher.end();
            lstMatches.add(new Integer[]{startIndex, endIndex});
        }

        return Collections.unmodifiableList(lstMatches);
    }
}

【讨论】:

  • 我可以检查出现的情况,但是如何设置适当的文本字段,这部分令人困惑
  • 我知道它很有用,但它的方式很复杂...... :(。我的水平还没有那么高......!!
  • 是时候伸展一下了。查找不需要使用正则表达式,您可以将其替换为我首先建议的循环
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-24
  • 1970-01-01
  • 2019-12-11
  • 2017-04-26
  • 1970-01-01
  • 2011-07-16
相关资源
最近更新 更多