Reputation: 95
I am creating a simple program, which will allow me to add single character to JTextField by pressing JButton. In this program, I have an array of string named words & I have a String name word, which is allowing me to choose words randomly from the array of words. I am using a for loop to draw the JTextFields. Number of the JTextField depends on the length of the 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);
I have a JButton named A, this JButton is having some error. I have the string named choice, it contains only one character "Ä". So, I added some method in my Jbutton, Which compare the string choice to the word ( the word which is randomly selected above). Whenever it find "A" in the word, it must have to draw that "A" in the Jtextfield to the specific location but its not drawing...
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());
}
}
Please check that video http://www.youtube.com/watch?v=Tx5QsET9IWs starting from 0.41 second . I wanna do the same thing...
Thanks....
Upvotes: 2
Views: 4685
Reputation: 347184
The problem is the use of the i
variable
It is first used to construct the fields
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]);
}
This now means that i
is now equal to word.length()
You then re-use the variable (as is)...
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) + " ");
}
}
}
Which won't work. i
equals word.length()
, meaning it will never enter the first level of the if
statement.
Make i
local and use it only to build the field array.
In the actionPerformed
method, you simply need to be checking all the occurrences of A
within the word and set the appropriate text field
There are a number of tricks for trying to find the index of all the occurrences of character in the String
.
The simplest would be to simply loop through the length of the String
and use String#charAt
and compare that with the value you are trying to match...
for (int index = 0; index < word.length(); index++) {
if (Character.toLowerCase(word.charAt(index)) == Character.toLowerCase(choice)) {
Text[index].setText(Character.toString(choice));
}
}
I use a slightly more complicated, but flexible approach, using regular expression to find all the occurrence of a given pattern...
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);
}
}
Upvotes: 4