Hot questions for Using JTextField in input

Question:

I am new to GUI stuff and am having trouble with the following problem. I have 3 JTextFields, credit card number, expiration date, and security number. I am able to input information into the fields. I also implemented the focus listener for each button. If I click it, it says gained focus, if I click anywhere else, it loses focus. Under these text fields, I have a number pad (touch screen/mouse click) to enter the numbers. How do I keep focus on that particular text field until ONLY and SPECIFICALLY one of the other two textfields are clicked? The textfield that currently has focus will lose focus once I try to click to input numbers. I don't want this to happen. I searched online and wasn't able to find something specific to my case. Any help or tips would be appreciated.


Answer:

myJButton.setFocusable(false);

or if a bunch of buttons held in an allMyButtons collection:

for (JButton button: allMyButtons) {
    button.setFocusable(false);
}

That's it.

Question:

I want to make a custom JTextField, and my requirements are:

  1. Show Hint in Text Field.
  2. It will take a limited number of characters.

Both the requirements are working. But the problem is that if I set the limit to 6, then it sets the input length to 6. I need to set an additional limit.

Like, Input Hint limit: 20, Number Input Limit: 6 Example: Input Hint: Enter a Number Here, Input: 666666 (Maximum 6 digit).

Here are both of the class.

CustomTextField.java

public class CustomTextField extends JTextField implements KeyListener, FocusListener{
    private static final long serialVersionUID = 1L;

    private final int CHAR_LIMIT = 6;
    private String hint = null;
    private boolean showingHint;

    public CustomTextField(String hint) {
        super(hint);
        this.hint = hint;
        this.showingHint = true;
        this.setDocument(new CustomJTextFieldCharLimit(CHAR_LIMIT));
        super.addFocusListener(this);
        this.addKeyListener(this);
    }

    @Override
    public void keyPressed(KeyEvent arg0) {

    }

    @Override
    public void keyReleased(KeyEvent arg0) {

    }

    @Override
    public void keyTyped(KeyEvent event) {
        char c = event.getKeyChar();

        if (!(Character.isDigit(c) || c == KeyEvent.VK_BACK_SPACE || c== KeyEvent.VK_DELETE)) {
            event.consume();
        }
    }

    @Override
    public void focusGained(FocusEvent e) {
        if(this.getText().isEmpty()) {
        super.setText("");
        showingHint = false;
        }
    }
    @Override
    public void focusLost(FocusEvent e) {
        if(this.getText().isEmpty()) {
          super.setText(hint);
          showingHint = true;
        }
    }

    @Override
    public String getText() {
        return showingHint ? "" : super.getText();
    }
}

CustomJTextFieldCharLimit.java

public class CustomJTextFieldCharLimit extends PlainDocument{
    private int limit;

    public CustomJTextFieldCharLimit(int limit) {
        this.limit = limit;
    }

    public void insertString(int offset, String string, AttributeSet set) throws BadLocationException {
        if (string == null) {
            return ;
        }else if ((getLength() + string.length()) <= limit) {
            super.insertString(offset, string, set);
        }
    }
}

Answer:

Okay, I'll check DocumentFilter in few min

You haven't changed your code? The DocumentFilter is the preferred approach because it is reusable. You can add it to any Document so it will work for a JTextField, JTextArea, JTextPane.

Both the requirements are working. But the problem is that if I set the limit to 6, then it sets the input length to 6. I need to set an additional limit.

You need to use a different approach. For example you can use the Text Prompt class. The prompt is independent of the actual text so the lengths can be different.

Question:

I am Trying to to create an actionListener For jTextField Using Netbeans 8.1. I did the Following: created the textfield then right Click > Events> Action > ActionPerformed. It Built for me the following code:

jTextField1.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
          jTextField1ActionPerformed(evt);
      }
});

private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {                                            
    // TODO add your handling code here:
   jTextField1.setText("Box1");
} 

but it is not working! I have tried to manually code it but still didn't work.

FYI: ActionListener for CheckBox and Radio buttons-in the same panel- are working fine, but non of the text fields!


Answer:

Use focus change listeners, in case you want to check after tab clicked or another field.

jTextField1.addFocusListener(new java.awt.event.FocusAdapter() {
        public void focusGained(java.awt.event.FocusEvent evt) {
        }
        public void focusLost(java.awt.event.FocusEvent evt) {
          //this will be called on tab i.e when the field looses focus
              jTextField1FocusLost(evt);
        }
    });

private void jTextField1FocusLost(java.awt.event.FocusEvent evt) {                                    
    jTextField1.setText("Box1");
}

you can use InputVerifier also as suggested by @MadProgrammer

Question:

I know this has been asked and answered many times but I still can't get the answer that I really need. Hopefully this time, somebody can help me and I thank you in advance. :)

This is what I want in my program, I want user to limit to input only numbers. Whenever they input letters and others there will be a prompt message. I can do that, there is a prompt message for letters and other char but the inputted value still remain, I want it to be cleared.

Please see my code.

private void txtQty1KeyTyped(java.awt.event.KeyEvent evt) {                                 
    txtQty1.addKeyListener(new KeyAdapter() {});
    char char_input = evt.getKeyChar();
    if (((char_input < '0') || (char_input > '9')) && (char_input != '\b'))
    {
        JOptionPane.showMessageDialog(this, "Number only!","Invalid Input",JOptionPane.ERROR_MESSAGE);
        txtQty1.setText(" ");
    }

}    

Though I clear my textfield, the character that I input still appears. Any help would be much appreciated. Thank you! :)


Answer:

You need to create a subclass of DocumentFilter class and use a regular expression to match each inserted string/character if they are digits or not and perform actions accordingly.

Below is a fully working sample code of this working. Thanks to @camickr for pointing out using DocumentFilter is more up-to-date than the old way of extending JTextField to achieve the same result.

import java.awt.BorderLayout;
import java.util.regex.Pattern;

import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;

public class TestDocumentFilter {

    public static void main(String... args) {
        new TestDocumentFilter();
    }

    public TestDocumentFilter() {
        JTextField textField = new JTextField(10);
        ((AbstractDocument) textField.getDocument()).setDocumentFilter(new CustomDocumentFilter());

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(new BorderLayout(5, 5));
        frame.getContentPane().add(textField, BorderLayout.NORTH);
        frame.setSize(400, 200);
        frame.setVisible(true);
    }

    private class CustomDocumentFilter extends DocumentFilter {

        private Pattern regexCheck = Pattern.compile("[0-9]+");

        @Override
        public void insertString(FilterBypass fb, int offs, String str, AttributeSet a) throws BadLocationException {
            if (str == null) {
                return;
            }

            if (regexCheck.matcher(str).matches()) {
                super.insertString(fb, offs, str, a);
            }
        }

        @Override
        public void replace(FilterBypass fb, int offset, int length, String str, AttributeSet attrs)
                throws BadLocationException {
            if (str == null) {
                return;
            }

            if (regexCheck.matcher(str).matches()) {
                fb.replace(offset, length, str, attrs);
            }
        }
    }
}

Question:

So I am attempting to create a login screen that prompts the user with a text box and 2 buttons (Login and Cancel). When the user hits login, I want the value of the JTextField to be stored in a variable or at least be usable. When I attempt to do anything with the playerNameTxt.getText() method, I get an error as if playerNameTxt doesn't exist.

public class GUI extends JPanel implements ActionListener {

protected JTextField playerNameTxt;

public GUI() {
    JTextField playerNameTxt = new JTextField(20);

    JLabel playerNameLbl = new JLabel("Enter Player Name");

    JButton loginBtn = new JButton("Login");
    loginBtn.setVerticalTextPosition(AbstractButton.BOTTOM);
    loginBtn.setHorizontalTextPosition(AbstractButton.LEFT);
    loginBtn.setMnemonic(KeyEvent.VK_D);
    loginBtn.setActionCommand("login");
    loginBtn.addActionListener(this);
    loginBtn.setToolTipText("Click this to Login");

    JButton cancelBtn = new JButton("Cancel");
    cancelBtn.setVerticalTextPosition(AbstractButton.BOTTOM);
    cancelBtn.setHorizontalTextPosition(AbstractButton.RIGHT);
    cancelBtn.setMnemonic(KeyEvent.VK_M);
    cancelBtn.setActionCommand("cancel");
    cancelBtn.addActionListener(this);
    cancelBtn.setToolTipText("Click this to Cancel");

    add(playerNameLbl);
    add(playerNameTxt);
    add(loginBtn);
    add(cancelBtn);
}

public void actionPerformed(ActionEvent e) {
    if ("login".equals(e.getActionCommand())) {
        System.out.println(playerNameTxt);
    } else {
        System.exit(0);
    }
}

private static void createAndShowGUI() {
    JFrame frame = new JFrame("-- Munitions Login --");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocation(400, 200);

    GUI newContentPane = new GUI();
    newContentPane.setOpaque(true);
    frame.setContentPane(newContentPane);

    frame.pack();
    frame.setVisible(true);
}

public static void main(String[] args) {
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            createAndShowGUI();
        }
    });
}
}

Answer:

You firstly declare the field outside of the constructor, then you declare it inside the constructor again, so that it will be deleted after the constructor returns and the GUI was destroyed, and it will not be usable for your class after the constructor has finished. You should change this line:

JTextField playerNameTxt = new JTextField(20);

to this:

playerNameTxt = new JTextField(20);

Question:

I'm having the hardest time finding out how to code how many words there are in the input for the JTextField, I have a set a clear input button, and once I figure out how to find out how many words there are, I'll be able to clear that as well. Thanks guys here's my code!

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class CopyTextPanel extends JPanel
{
private JTextField input;
private JLabel output, inlabel, outlabel;
private JButton compute, clear;
private JPanel panel;

public CopyTextPanel()
{
    inlabel = new JLabel("Input Text:  ");
    outlabel = new JLabel("Text Statistics Results: ");
    input = new JTextField (" ", 25);
    output = new JLabel();
    compute = new JButton("Compute Statistics");
    compute.addActionListener (new ButtonListener());
    clear = new JButton("Clear Text");
    clear.addActionListener (new ButtonListener());
    panel = new JPanel();

    output.setPreferredSize (new Dimension(550, 30));
    panel.setPreferredSize (new Dimension(620, 100));
    panel.setBackground(Color.gray);
    panel.add(inlabel);
    panel.add(input);
    //panel.add(outlabel);
    //panel.add(output);
    panel.add(compute);
    panel.add(clear);
    panel.add(outlabel);
    panel.add(output);

    setPreferredSize (new Dimension(700, 150));
    setBackground(Color.cyan);
    add(panel);
}

private class ButtonListener implements ActionListener
{
    public void actionPerformed (ActionEvent event)
    {
        if (event.getSource()==compute)
        {
            {
                output.setText (input.getText());                     
            }
        }
        else
            input.setText("");
    }
}

Answer:

For small piece of text like that one in an inputText you could use split to generate a string array with the string break into words and so read the array's length:

String test = "um dois      tres quatro        cinco ";
String [] splitted = test.trim().split("\\p{javaSpaceChar}{1,}");
System.out.println(splitted.length);

//output 5

So, for your input:

String inputText = input.getText();
String [] splitted = inputText.trim().split("\\p{javaSpaceChar}{1,}");
int numberOfWords = splitted.length;

Question:

My application offers the possibility to copy text from a JTextArea to a JTextField (used as editor component of a JComboBox, but I assume that doesn't matter) and I'd like to provide to remove leading and trailing whitespace if a boolean condition is true (e.g. a check box is checked). Entering leading and trailing whitespace into the JTextField should still be possible, only the pasted text should be manipulated as described.

I added a DocumentFilter, but it responds to both typed changes and pasted changes and I don't find any condition in its method arguments which allow to distinguish typed from pasted insertions. A KeyListener doesn't respond to pasted changes.


Answer:

I don't find any condition in its method arguments which allow to distinguish typed from pasted insertions. A KeyListener doesn't respond to pasted changes.

Listener does not provide a direct means to determine whether the input comes from a paste-action. But I have a simple work around solution which may work.

  1. Use a DocumentListener to detect for text changes in the JTextField. If changes were detected, proceed to next step.

  2. Grab the String text from the Clipboard object.

  3. Compare text within the JTextField and the text from the Clipboard. If the Strings are the same, we assume pasting has occurred.


In case the user paste some text in-between existing text in the textfield, you can get the caret position and compare the String from the caret position onwards.


Update:

To read from Clipboard:

import java.awt.Toolkit;
import java.awt.datatransfer.*;

Clipboard cb=Toolkit.getDefaultToolkit().getSystemClipboard();
System.out.println(cb.getData(DataFlavor.stringFlavor));

Question:


Answer:

You should use a DocumentFilter for this, take a look at Implementing a Document Filter and DocumentFilter Examples

It will allow you to filter out text coming directly before it's applied to the underlying Document, which makes it flexible enough to be used with any Document implementation that extends from AbstractDocument, takes into account the use cases where the user pastes text into the field or calls setText

For example...

import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.Toolkit;
import javax.print.attribute.AttributeSet;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.text.AbstractDocument;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import javax.swing.text.DocumentFilter.FilterBypass;

public class FilterTest {

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

    public FilterTest() {
        EventQueue.invokeLater(new Runnable() {

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

                JTextField field = new JTextField(10);
                ((AbstractDocument)field.getDocument()).setDocumentFilter(new SizeFilter(5));

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new GridBagLayout());
                frame.add(field);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }

        });
    }

    public class SizeFilter extends DocumentFilter {

        private int maxCharacters;

        public SizeFilter(int maxChars) {
            maxCharacters = maxChars;
        }

        public void insertString(FilterBypass fb, int offs, String str, AttributeSet a)
                        throws BadLocationException {

            if ((fb.getDocument().getLength() + str.length()) <= maxCharacters) {
                super.insertString(fb, offs, str, a);
            } else {
                Toolkit.getDefaultToolkit().beep();
            }
        }

        public void replace(FilterBypass fb, int offs, int length, String str, AttributeSet a)
                        throws BadLocationException {

            if ((fb.getDocument().getLength() + str.length()
                            - length) <= maxCharacters) {
                super.replace(fb, offs, length, str, a);
            } else {
                Toolkit.getDefaultToolkit().beep();
            }
        }
    }

}

Question:

I was able to make the code do what i want except for the fact i can't get input from this now. What i want to do now is still get text from the JTextfield and return it to the main method that creates the frame object. Can somebody help me get the input from the following code?

 package assignment5;

    import java.awt.*;
    import java.awt.event.*;

    import javax.swing.*;

    public class Frame2 extends JDialog implements ActionListener 
    {

        private String a;
        private JTextField field = new JTextField(30); 

        public Frame2(JFrame parent, String title, String message) 
        {
            super(parent, title, true);

            if (parent != null) 
            {
                this.setSize(500,150);
                this.setLocation(400,200);
            }

            JPanel messagePane = new JPanel();
            messagePane.add(new JLabel(message));
            getContentPane().add(messagePane, BorderLayout.PAGE_START);

            JPanel buttonPane = new JPanel();
            JPanel button2Pane = new JPanel();

            JButton button = new JButton("OK"); 
            JButton button2 = new JButton("Cancel");

            buttonPane.add(button); 
            button2Pane.add(button2);

            getContentPane().add(buttonPane, BorderLayout.PAGE_END);
            getContentPane().add(button2Pane,BorderLayout.EAST);

            //button.addActionListener(this);
            button.addActionListener(new ActionListener()
            {
                @Override 
                public void actionPerformed( ActionEvent event)
                {
                    parent.dispose();
                }
            });

            button2.addActionListener(new ActionListener()
            {
                @Override 
                public void actionPerformed( ActionEvent event)
                {
                    parent.dispose();
                }
            });

            JPanel textPane = new JPanel();
            JTextField field = new JTextField(30); 
            textPane.add(field);
            getContentPane().add(textPane, BorderLayout.CENTER);

            field.addActionListener(this);


            setDefaultCloseOperation(DISPOSE_ON_CLOSE);

            //pack(); 
            setVisible(true);
}


        public void b ()
        {
            a = field.getText();
        }

        public String g ()
        {
            System.out.println("wasdfsdf" + a);
            return a;
        }

        @Override
        public void actionPerformed(ActionEvent event) 
        {
            a = field.getText();
            System.out.println("wasdfsdfsafddsfsdfsdfsafdsggsdfsdf" + a);
            // TODO Auto-generated method stub

        }

    }

Answer:

You're creating a non-modal JFrame when you really want to instead use a modal JDialog. Change the MyFrame2 to a modal JDialog and your problems are solved.

Details as to why:

  • When you create and display a non-modal JFrame, program flow continues immediately in the calling code below the code where you display the JFrame.
  • This means that you'll be trying to extract data from the JTextField before the user's had nary a chance to add information to it.
  • With a modal JDialog on the other hand, code flow halts in the calling code immediately when you display the JDialog, and it does not resume until the JDialog is no longer visible.
  • Thus the code below where you display the dialog won't get called until the dialog has been dealt with by the user, and now hopefully the JTextField in the dialog will have useful information in it.

Edit I'm surprised that this will even compile:

many = Integer.parseInt()

You're parsing nothing on this line, and that won't fly.

You would want to give your MyFrame2 a public method that extracts the String from its JTextField and then call the method after displaying it. Something like:

public String getMyTextFieldText() {
    return myTextField.getText();
}

And then in the calling code:

MyFrame2 myFrame2 = new MyFrame2();
myFrame2.setVisible(true);

String text = myFrame2.getMyTextFieldText();
if (text != null && !text.trim().isEmpty()) {
  int someNumber = Integer.parseInt(text);
}

Question:

I wanna make a programmable calculator, i got the basic GUI, and now i'm trying to set up the buttons, and the display. My display text will be "0" basically and if the user type in a number, that number should to be displayed. I tried to do it with KeyListener, but if i press a key it will display the key twice. Why?

 textField.addKeyListener(new KeyListener(){
        boolean newNumber = true;

        public void keyTyped(KeyEvent e) {
        }

        public void keyPressed(KeyEvent e) {
            int keyCode = e.getKeyCode();


            if(keyCode == e.VK_BACK_SPACE && textField.getText().length() == 1){
                textField.setText("0");
                newNumber = true;
                }

            if(textField.getText().equals("0") && newNumber){
                textField.setText(KeyEvent.getKeyText(keyCode));
                newNumber = false;
            }
        }

        public void keyReleased(KeyEvent e) {
        }

    });

Before input:

After "1" input:


Answer:

Here a simple solution:

If you use keyPressed, you have to do something in keyReleased and this become complicated. keyTyped is a more simple way.

You can use e.consume() to prevent having the double digit inserted.

    textField.addKeyListener(new KeyListener() {

        int codeDelete = KeyEvent.getExtendedKeyCodeForChar(KeyEvent.VK_DELETE);
        int codeBackSpace = KeyEvent.getExtendedKeyCodeForChar(KeyEvent.VK_BACK_SPACE);

        @Override
        public void keyTyped(KeyEvent e) {

            char keyChar = e.getKeyChar();

            if (textField.getText().length() == 0) {
                textField.setText("0");
            }
            else if (textField.getText().equals("0") && keyChar != codeDelete && keyChar != codeBackSpace) {
                textField.setText(String.valueOf(e.getKeyChar()));
                e.consume();
            }
        }

        @Override
        public void keyPressed(KeyEvent e) {
        }

        @Override
        public void keyReleased(KeyEvent e) {
        }

    });

Question:

I am trying to make my JTextField input visible to my other classes. I am not going to clog up the page with a ton of code, just where the problem is.

I have done a ton of online research but I am getting nowhere.

public class browseropen extends JFrame { 

    public browseropen() {
        setDefaultCloseOperation(EXIT_ON_CLOSE); // setting app close on exit 
        JPanel panel = new JPanel(); // creating new app panel

        JTextField urltxt = new JTextField(10); // establishing new text field for URL input
        urltxt.addActionListener(new ActionListener() { // adding event for enter key
            @Override
            public void actionPerformed(ActionEvent event ) {
                runClient();              // run browser open command
            }
        });

        public String geturltxt() { // attempting to set input of JTextField to be available in other class

                    return urltxt.getText();

                }

I would appreciate any insight as I am just starting to learn Java and want to learn the right way :)

Edit: the problem is in geturltxt


Answer:

The easy answer is: turn that local variable into a field of your class, like

public class BrowserOpen extends JFrame {
  private final JTextField urltxt; // to be init'ed in your constructor for example

And voila, now your other methods can use that field urltxt.

Notes: please read about java coding styleguides to get your class/field names "right".

Question:

Hi I'm making a game in Java that randomly generates 100 numbers, and then ask the user to memorize as many as then can and then try to recall as many as they can. My game uses a JPanel and a Graphics g object to do all the drawing. How do I "draw" a JTextfield or get one to work on a jpanel?


Answer:

Add a ActionListener to JTextField and then add that JTextField to JPanel. Now add this JPanel to JFrame using this.add(jpnel, BorderLayout.SOUTH); Create a new JPanel class Board where you draw things. Add that JPanel to JFrame as, this.add(new Board(), BorderLayout.CENTER);. Here I coded one example for you. Now you should have an idea how to do that...

Board class

    public class Board extends JPanel {

    int[] numbers = {3, 25, 5, 6, 60, 100};
    int index = 0;
    static String num;
    boolean once = true;
    FontMetrics fm;

    Board() {
        setPreferredSize(new Dimension(400, 200));
        setBackground(Color.decode("#ffde00"));
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        Graphics2D g2 = (Graphics2D) g;
        if (index < 6) {
            num = numbers[index] + "";
        } else {
            num = "Game Ended.";
            Window.ans.setEditable(false);
        }
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setFont(new Font("Arial", Font.PLAIN, 50));
        if(once){
            fm = g2.getFontMetrics();
            once = false;
        }
        int x = ((getWidth() - fm.stringWidth(num)) / 2);
        int y = ((getHeight() - fm.getHeight()) / 2) + fm.getAscent();
        g2.drawString(num + "", x, y);
        index++;
    }

}

Window class

    public class Window extends JFrame {

    JPanel p = new JPanel();
    JLabel lbl = new JLabel("Enter the number if you have seen it before, Else empty.");
    JLabel res = new JLabel("....");
    static JTextField ans = new JTextField(10);
    Board board = new Board();

    public Window() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        add(board, BorderLayout.CENTER);
        p.setLayout(new BorderLayout(8, 8));
        p.add(lbl, BorderLayout.WEST);
        ans.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                if (ans.getText().equals(Board.num)) {
                    res.setText("Good");
                } else {
                    res.setText("Bad");
                }
                ans.setText("");
                board.repaint();
            }

        });
        p.add(ans, BorderLayout.CENTER);
        p.add(res, BorderLayout.EAST);
        p.setBorder(new EmptyBorder(10, 10, 10, 10));
        this.add(p, BorderLayout.SOUTH);
        setResizable(false);
        pack();
        setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Window();
            }
        });
    }

}

Question:

My application is in Hebrew. The computers that are running my app all have English set as the default language and Hebrew as the secondary language.

Every time they need to input stuff to my JTextFields, they have to "alt + shift" to change language, Some of them don't even look at the monitor and just begin to write, and I get gibberish because they wrote in Hebrew but with English chars :)

Is it possible to set the language when a JTextFields gets the focus , or maybe in some other way ?

thanks,

Dave


Answer:

Try jTextField.getInputContext().selectInputMethod(new Locale("iw", "IL")); on FocusGained event

Question:

I'm very new to Java and I'm trying to create a small program that reverses text (That part I've figured out).

Where I'm getting stuck on is my GUI, my envisioned plan for the gui is a window with a centered text field for user input then under it in the directly middle of the window a button that reverses the text from the above text box and outputs it in a text box below the button.

Right now I'm using JTextField boxes and after trying to make them look the way I want I'm getting the feeling that there's an easier way to do it, but I don't know it.

Here's my GUI class:

public class ReverseTextGUI extends ReverseRun implements ActionListener {

    public static JFrame frame;

    private JPanel northFlowLayoutPanel;
    private JPanel centerFlowLayoutPanel;
    private JPanel southFlowLayoutPanel;

    private final JButton reverse = new JButton("Reverse");
    private final JTextField userInput = new JTextField(50);
    private final JTextField reverseOutput = new JTextField(50);

    public void actionPerformed(ActionEvent e) {

        reverse.addActionListener((ActionListener) reverse);
        reverse.setActionCommand("Reverse");

        if ("algorithm".equals(e.getActionCommand())) {
            System.out.println("test");
        }

    }

    public void initUI() {

        northFlowLayoutPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        northFlowLayoutPanel.add(userInput);
        userInput.setPreferredSize(new Dimension(150,100));

        centerFlowLayoutPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        centerFlowLayoutPanel.add(reverse);

        southFlowLayoutPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        southFlowLayoutPanel.setBorder(BorderFactory.createTitledBorder("Output text"));
        southFlowLayoutPanel.add(reverseOutput);
        reverseOutput.setPreferredSize(new Dimension(150,100));

        JFrame frame = new JFrame("Backwardizer");
        frame.setLayout(new BorderLayout());      // This is the default layout
        frame.add(northFlowLayoutPanel, BorderLayout.PAGE_START);
        frame.add(centerFlowLayoutPanel, BorderLayout.CENTER);
        frame.add(southFlowLayoutPanel, BorderLayout.PAGE_END);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        frame.setSize(750, 500);

    }

Any ideas how to either move the cursor to the start of the box (it shows up in the middle as of now) or a better way to accomplish what I'm trying to do?


Answer:

For the reversing aspect, you can add the text from the first box to a string builder

StringBuilder rev = new StringBuilder(firstBox.getText());
String reversedText = rev.reverse().toString();
secondBox.setText(reversedText);

Something along those line should get the desired result if you nest it in the button action.

Question:

Due to a gui with a lot of buttons and labels, I'm using netbeans. When I test-run it in netbeans, if I leave the jtextfield blank and submit it, I get:

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 1

I was looking at the jbutton I am using to submit the data and although I can see the following field, I cannot edit it:

        butSub.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            butSubActionPerformed(evt);
        }
    });

I thought maybe in that I could run an if or a try/catch block, but again it won't let me edit it. If the user inputs nothing, I want it to tell them so and then return to the start.


Answer:

You are trying to edit IDE generated code. Don't do that. Instead edit the code in butSubActionPerformed() which is being called by the ActionListener. You can check if the text field is empty using:

if(jTextField.getText().isEmpty()){
    //error
} else //every thing is fine, you can continue.

Again, this code has to be in the method being called by the ActionListener.

Question:

I'm working on a small personal project.

I have two JFrame windows, Viewer and Console.

  • Viewer only contains a subclass of JPanel, and it should respond to mouse input (clicking, mostly).
  • Console contains a button, a JTextField (the input), and a JTextArea (the output).

I need to make sure than when I press keys on my keyboard, the corresponding text appears in the Console JTextField, not only when the focus is held by the JTextField, but also when it's held any other component in my app.

In other words, I want the JTextField to accept input even right after I clicked on the Viewer frame.

Is this feasible?

In case that matters, I'm running win 8 x64 and I don't really care about portability (I'm the only one that will ever look at or use this code).

EDIT: here is an example of my code:

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;



public class main {
    public static Viewer v; 
    public static Console c;
    public static void main(String[] args) {
        v=new Viewer();
        c=new Console();
    }


    static class Viewer extends JFrame {
        public Viewer(){
            setSize(600,600);
            getContentPane().add(new myPanel());
            addMouseListener(new mouse());
            setVisible(true);

        }
    }
    static class myPanel extends JPanel{
        public void paintComponent(Graphics g){
            g.setColor(new Color((int)(Math.random()*255),(int)(Math.random()*255),(int)(Math.random()*255)));
            g.fillRect(0, 0, 600, 600);
        }
    }
    static class Console extends JFrame {
        public Console(){
            setSize(600,200);
            JTextField text=new JTextField();
            getContentPane().add(text);
            setVisible(true);

        }
    }
    static class mouse implements MouseListener{
        @Override
        public void mouseClicked(MouseEvent arg0) {
            v.repaint();
        }

        @Override
        public void mouseEntered(MouseEvent arg0) {
        }

        @Override
        public void mouseExited(MouseEvent arg0) {
        }

        @Override
        public void mousePressed(MouseEvent arg0) {
        }

        @Override
        public void mouseReleased(MouseEvent arg0) {
        }
    }

}

In this example, after I click on the big window to change its color, if I want to write stuff in the other window I have to click on it first.


Answer:

Can I suggest the KeyboardFocusManager? I've found this to be the easiest way to achieve what I believe you are trying to achieve

KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(
  new KeyEventDispatcher() {
     public void dispatchKeyEvent(KeyEvent ke) {
       //TODO: fill this in
     }
  });

Question:

I am working on this assignment for school. I have been looking my code over and over. The problem is that when I try and run this program I can't input data into the fields. When I try to select the fields to enter the data it won't let me. Someone please help me!

import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.text.DecimalFormat;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class OfficeAreaCalculator extends JFrame{

private JFrame mainFrame;
private JButton calculateButton;
private JButton exitButton;
private JTextField lengthField;
private JTextField widthField;
private JTextField areaField;
private JLabel lengthLabel;
private JLabel widthLabel;
private JLabel areaLabel;

public OfficeAreaCalculator()
{
    mainFrame = new JFrame("Office Area Calculator");

    exitButton = new JButton("Exit");
    lengthLabel = new JLabel("Enter the length of the office:");
    widthLabel = new JLabel("Enter the width of the office:");
    areaLabel = new JLabel("Office area:");
    lengthField = new JTextField(5);
    widthField = new JTextField(5);
    areaField = new JTextField(5);
    areaField.setEditable(false);
    calculateButton = new JButton("Calculate");

    Container c = mainFrame.getContentPane();
    c.setLayout(new FlowLayout());

    c.add(lengthLabel);
    c.add(lengthField);
    c.add(widthLabel);
    c.add(widthField);
    c.add(areaLabel);
    c.add(areaField);
    c.add(calculateButton);
    c.add(exitButton);

    calculateButton.setMnemonic('C');
    exitButton.setMnemonic('X');

    mainFrame.setSize(260, 150);

    mainFrame.addWindowListener(new WindowAdapter(){
        public void windowClosing(WindowEvent e) {
            System.exit(0);
        }
    });

    CalculateButtonHandler chandler = new CalculateButtonHandler();
    calculateButton.addActionListener(chandler);

    ExitButtonHandler ehandler = new ExitButtonHandler();
    exitButton.addActionListener(ehandler);

    FocusHandler fhandler = new FocusHandler();
    lengthField.addFocusListener(fhandler);
    widthField.addFocusListener(fhandler);
    areaField.addFocusListener(fhandler);

    mainFrame.setVisible(true);
}

class CalculateButtonHandler implements ActionListener
{
    public void actionPerformed(ActionEvent e)
    {
        DecimalFormat num = new DecimalFormat(",###.##");
        double width, length, area;
        String instring;

        instring = lengthField.getText();
        if (instring.equals(""));
        {
            instring = ("0");
            lengthField.setText("0");
        }
        length = Double.parseDouble(instring);

        instring = widthField.getText();
        if (instring.equals(""))
        {
            instring = "0";
            widthField.setText("0");
        }
        width = Double.parseDouble(instring);

        area = length * width;
        areaField.setText(num.format(area));

    }

}

class ExitButtonHandler implements ActionListener
{
    public void actionPerformed(ActionEvent e) {
        System.exit(0);
    }       
}

class FocusHandler implements FocusListener
{
    public void focusGained(FocusEvent e)
    {
        if (e.getSource() == lengthField || e.getSource() == widthField)
        {
            areaField.setText("");
        }
        else if (e.getSource() == areaField);
        {
            calculateButton.requestFocus();
        }
    }

    public void focusLost(FocusEvent e)
    {
        if (e.getSource() == widthField)
        {
            calculateButton.requestFocus();
        }
    }
}

public static void main(String arg[])
{
    new OfficeAreaCalculator();
}
}

Answer:

General advice. Don't write your whole program all at once before you start testing.

1) Just create the GUI with all your components. That is remove all the listener code and see if it works.

2) Add back in the listeners one at a time and see if each listener works.

3) When the code stops working then you know where the problem is and you will know where to spend your time doing your debugging and you will be able to give us more information to help solve the problem.

As it turns out the problem is a typo:

    else if (e.getSource() == areaField);

You should not have the ";" at the end of the statement, this is causing the calculateButton.requestFocus(); statement to be executed every time to try to place focus on either of the text fields.

As a general rule you should NOT be using a FocusListener to try to control focus of components. Focus will move naturally when you use the Tab key. Your "areaField" should not really be a text field. It should probably be a JLabel which will never gain focus anyway so focus will go directly to the button from the width text field.

Question:

I am writing a program that utilizes the provided library ScriptEngineManager to try and write a math calculator that goes beyond the basic functions of +, -, / and *. How would I be able to go about implementing this in the existing code.

I have already attempted using .replace, although it's possible that I have implemented it wrong.

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class GUIRunner {

    public static void main(String args[]) {
        JFrame f = new JFrame("megamath1.0");
        f.setSize(300,300); 
        f.setLocation(100,150);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JFrame.setDefaultLookAndFeelDecorated(true);
        JLabel labelM = new JLabel("Enter Equation: ");
        labelM.setBounds(50, 50, 200, 30);
        JLabel label = new JLabel(); 
        label.setBounds(50,100,200,30);
        label.setVisible(true);
        JTextField motto1 = new JTextField();
        //set size of the text box
        motto1.setBounds(50, 100, 200, 30);
       //add elements to the frame
        f.add(labelM);
        f.add(motto1);
        f.setLayout(null);
        f.setVisible(true);
        JButton b = new JButton("Submit");
        b.setBounds(50, 150, 100, 30);
        b.addActionListener(new ActionListener() {
         @Override
            public void actionPerformed(ActionEvent arg0) {
                String inputText = motto1.getText(); 

            ScriptEngineManager mgr = new ScriptEngineManager();
            ScriptEngine engine = mgr.getEngineByName("JavaScript");
                try {
                motto1.setText("Output: " + engine.eval(inputText));
                } catch (ScriptException e) {
                // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

       });
       //add button to the frame
       f.add(b);
       f.add(label);
}
}

It currently does work for standard calculations such as the ones provided above (+, -, *, /) by simply changing the text in the text field to the proper answer. How could I implement more complicated mathematics


Answer:

So at the moment you only put the input text into a JavaScript engine and hope that the thing works. If you really want to stick to this approach, the user has to know JavaScript to use the calculator. For example if you input Math.sin(42) you will get the sine value of 42.

If you want to implement a more convenient math syntax similar to real math you need to write your own script engine for the math expressions. There are libraries that can help with this, but you'll need a good understanding of what you are doing.

Question:

I am trying to recreate console game with JTextArea as console/output and JTextField as user input. Since the GUI is event driven I do not understand how could I stop the code from executing, to wait for user input before proceeding with opponents turn. The only solution I can think of is While(userTurn) and userTurn would be changed to false upon actionlistener is there a better way?

My console solution

 String getInput(String prompt){
        String inputLine = null;
      console.setTextConsole(prompt + " ");
        try{
            BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
            inputLine = is.readLine();
            if(inputLine.length() == 0) return null;

        }catch(IOException e){
            console.setTextConsole("IOException "+e);
        }
        return inputLine;
    }

I just called this getInput method and I proceeded with opponents turn.

What I want to accomplish is:

  1. Opponents turn
  2. Game waits for user
  3. User types text into JtextField and presses enter
  4. Game executes players command
  5. Opponents turn again ..

Answer:

I've written an example game so you can observe the difference. The computer and the user try to guess a random number between 0-2 inclusive. Who ever gets it right wins. If both get it right or both get it wrong its a draw.

EDIT: Updated GUI version

Here's the console program:

import java.util.Random;
import java.util.Scanner;

public class ConsoleGame {
    public static void main(String[] args) {
        Scanner console = new Scanner(System.in);
        Random rand = new Random();
        boolean playAgain = false;
        int wins = 0, losses = 0, draw = 0;
        do {
            int num = rand.nextInt(3); // 0-2 inclusive
            System.out.println("Guess the number [0-2]: ");
            int guess = Integer.parseInt(console.nextLine());
            int computerGuess = rand.nextInt(3);
            System.out.println("You: " + guess + "\tComputer: " + computerGuess + "\tNumber: " + num);
            if (guess == num && computerGuess == num || guess != num && computerGuess != num) {
                draw++;
                System.out.println("Draw!");
            } else if (guess == num) {
                wins++;
                System.out.println("You win!");
            } else if (computerGuess == num) {
                losses++;
                System.out.println("Computer wins :(");
            }
            System.out.println("Play again [y/n]? ");
            playAgain = console.nextLine().startsWith("y");
        } while (playAgain);
        System.out.println("Wins: " + wins + "\nLosses: " + losses + "\nDraw: " + draw);
        console.close();
    }
}

Here's the GUI program:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class GUIGame extends JFrame {
    private JPanel contentPane;
    private JTextField textField;
    private JTextArea textArea;
    private boolean textReceived;

     /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    GUIGame frame = new GUIGame();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public GUIGame() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setLayout(new BorderLayout());
        setContentPane(contentPane);

        textField = new JTextField();
        textField.addActionListener(new ActionListener() {
            @Override
            // user pressed 'enter' key,
            public void actionPerformed(ActionEvent e) {
                textReceived = true;
                synchronized (textField) {
                    // notify game loop thread which is waiting on this event
                    textField.notifyAll();
                }
            }
        });
        contentPane.add(textField, BorderLayout.SOUTH);

        JScrollPane scrollPane = new JScrollPane();
        contentPane.add(scrollPane, BorderLayout.CENTER);

        textArea = new JTextArea();
        textArea.setFont(new Font("Consolas", Font.PLAIN, 12));
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        textArea.setForeground(Color.LIGHT_GRAY);
        textArea.setBackground(Color.BLACK);
        textArea.setEditable(false);
        scrollPane.setViewportView(textArea);

        // Start game loop in new thread since we block the thread when
        // waiting for input and we don't want to block the UI thread
        new Thread(new Runnable() {
            @Override
            public void run() {
                playGame();
            }
        }).start();
    }

    private void playGame() {
        Random rand = new Random();
        boolean playAgain = false;
        int wins = 0, losses = 0, draw = 0;
        do {
            int num = rand.nextInt(3); // 0-2 inclusive
            textArea.append("Guess the number [0-2]: \n");
            int guess = Integer.parseInt(requestInput());
            int computerGuess = rand.nextInt(3);
            textArea.append("You: " + guess + "\tComputer: " + computerGuess + "\tNumber: " + num + "\n");
            if (guess == num && computerGuess == num || guess != num && computerGuess != num) {
                draw++;
                textArea.append("Draw!\n");
            } else if (guess == num) {
                wins++;
                textArea.append("You win!\n");
            } else if (computerGuess == num) {
                losses++;
                textArea.append("Computer wins :(\n");
            }
            textArea.append("Play again [y/n]? \n");
            playAgain = requestInput().startsWith("y");
        } while (playAgain);
        textArea.append("Wins: " + wins + "\nLosses: " + losses + "\nDraw: " + draw + "\n");
    }

    private String requestInput() {
        textField.setEnabled(true);
        textField.requestFocus();
        // wait on text field till UI thread signals a user input event
        synchronized (textField) {
            while (!textReceived) {
                try {
                    textField.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        String input = textField.getText();
        textField.setText("");
        textField.setEnabled(false);
        textReceived = false;
        return input;
    }
}

Question:

Is there a way so that when a user enters values into one textfield and another textfield such as 1 and 1, a third textfield immediately calculates the sum and displays it without having to add a button to the GUI?


Answer:

add a document listener to your TextField, that does something on update.

textField.getDocument().addDocumentListener(new DocumentListener() {
  public void changedUpdate(DocumentEvent e) {
    doSomethingInAnotherTextfield();
  }
  public void removeUpdate(DocumentEvent e) {
    doSomethingInAnotherTextfield();
  }
  public void insertUpdate(DocumentEvent e) {
    doSomethingInAnotherTextfield();
  }

  public void doSomethingInAnotherTextfield() {
     //whatever you have to do
  }
});

Question:

I'm really surprised this is not in the documentation or at least google.

I have a class that is likely to need to remove the verifier or replace it with another one. In particular, these methods are defined in the interface:

  /**
   * Add the verifier
   */
  public void bind();
  /**
   * Remove the verifier from input
   */
  public void unbind();

I can implement bind:

  /**
   * Binds the events to the field using InputVerifier
   */
  @Override
  public void bind() {
    //Internal verifier
    final SettingsInputVerifier<T> verif = this.verifier;
    //Event to be called if new value is valid
    final ValueChanged<T> onchange = this.onchange;
    //Only works when you leave the field
    field.setInputVerifier(new InputVerifier() {
      @Override
      public boolean verify(JComponent in) {
        //If verification fails, return false and ignore the value
        if(!verif.verify(in))
          return false;
        //Sucessful verification means we get the value and update it
        onchange.changed(verif.value(in));
        return true;
      }
    });
  }

But how can I unset input verifier from JTextField?


Answer:

Try this way:

field.setInputVerifier(null);

Question:

I want to make it so that when I run this program I can keep entering input from the text field and it will print to the file which we are trying to write.

The code I have so far only works the first time I hit 'Enter'. After that when I do it again, it throws an exception.

Is anyone able to help me out here?

public static void main(String [] args) throws IOException {

    //creates file or opens existing file
    File f = new File("C:/Users/User/Desktop/course.txt");
    Scanner sc = new Scanner(System.in);
    FileWriter w = new FileWriter(f.getAbsoluteFile(), true);
    BufferedWriter r = new BufferedWriter(w);

    //GUI Setting
    JFrame frame = new JFrame();
    JLabel text = new JLabel();
    JLabel results = new JLabel();
    JPanel panel = new JPanel();
    JTextField textField = new JTextField();

    textField.setPreferredSize(new Dimension(450, 30));
    text.setText("Enter \"END\" to terminate program OR \"CLEAR ALL\" to delete everything in the file");

    frame.getContentPane().add(panel);
    frame.setSize(new Dimension(500, 150));
    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setTitle("Course");
    frame.setResizable(true);
    frame.setVisible(true);

    panel.add(text);
    panel.add(textField);
    panel.add(results);

    //action listener for textfield when user hits enter
    textField.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String message;
                message = textField.getText();
            try {
                    if(message.contains("END")) {
                        System.exit(0);
                    }
                    if(message.contains("CLEAR ALL")) {
                            clear();
                    }
                    else {
                            r.write(message);
                            r.newLine();
                    }
                    r.close();
                }catch(IOException e1) {
                    results.setText("Error");
                }
            textField.setText("");
        }
    }
);

    //set focus to text field once GUI is opened
    SwingUtilities.invokeLater(new Runnable() {
          public void run() {
            textField.requestFocus();
          }
        });
}

//clear function to empty the file
private static void clear() throws FileNotFoundException {
    File f = new File("C:/Users/User/Desktop/course.txt");
    PrintWriter w = new PrintWriter(f);
    w.print("");
    w.close();
}
}

Answer:

The problem is pretty simple. You're calling close on the BufferedWriter.

else {
   r.write(message);
   r.newLine();
}

r.close();

The Javadoc for BufferedWriter#close states

Closes the stream, flushing it first. Once the stream has been closed, further write() or flush() invocations will cause an IOException to be thrown.


You're also writing to the same file using two different objects. I recommend you to stick with one and ditch the other.

Question:

I am working on an application that gets a shutter speed that a user enters into a text field. The user can type in a shutter speed in the form of a fraction "1/250" or a whole number. From that input I want to convert that to a variable of type double.

But when I try inputting "1/250" I get many errors, the first being:

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: 
    For input string: "1/250"

I know it has to do with the '/' in the input but how would I go about converting the fraction to a double?

        JTextField userShutter = new JTextField("", 10);
        userShutter.setBounds(60, 180, 50, 25);

        userShutter.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                double shutter = Double.parseDouble(userShutter.getText());
                baseShutterSpeed = shutter;
            }
        });

        // Calculate shutter speed
        calculator(stopValue, baseShutterSpeed);

Answer:

You simply need to use the String that you are getting back from the textfield and split it into two parts based on the / character. Then you can use those two numbers and divide them like you would using basic math to get the double.

String str = userShutter.getText();
String[] arr = str.split("/");

double answer = Double.parseDouble(arr[0]) / Double.parseDouble(arr[1]);
System.out.println(answer);

Question:

I am trying to create a desktop application that will open a specified URL.

I am using Java to build the app and here is my code so far.

browseropen.java

 public class browseropen {


    public static void main(String[] args) {

            JFrame frame = new JFrame("Desktop Browser Search"); // We create our initial app frame
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // next we are making sure our app stops running
            JPanel panel = new JPanel(); // Our new application window
            JLabel optext = new JLabel("Welcome Please Enter URL to Begin!"); // Our new window text
            frame.setSize(400, 400); // Set Application Window Size
            //pack();
            // Now adding Text box
            JTextField txtbox = new JTextField(10);
            JButton gourl = new JButton("Go To URL"); // creating new button to activate browser function
            frame.setVisible(true);
            optext.setVisible(true);
            frame.setLayout( new GridLayout(3,4,5,10));
            panel.add(optext); // We are adding our objects to our app window
            panel.add(txtbox);
            panel.add(gourl);
            frame.add(panel); // And finally we add our app panel to our frame 
            String geturl = txtbox.getText();


     gourl.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
             //run client main
             runClient();
         }




public void runClient() {
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            String[] args1={"10"};
            openbrowserurl.main(args1);
        }
    });
}
});
    }

    public void texturl() {



    };



}

openbrowser.java

public class openbrowserurl extends browseropen {

    public static void main(String[] args)  {

        Desktop desktop = Desktop.getDesktop();
        String urlinput = "https://www.google.com";
        if( !java.awt.Desktop.isDesktopSupported() ) {
            System.err.println("Desktop Not Supported");
            System.exit(1);
        }
        if (args.length == 0) {
              System.out.println( "Usage: OpenURI [URI [URI ... ]]" );
                System.exit( 0 );
        }

        if(!desktop.isSupported( java.awt.Desktop.Action.BROWSE ) ) {

            System.err.println( "Desktop doesn't support the browse action (fatal)" );
            System.exit( 1 );
        }

        for ( String arg : args ) {

            try {

                java.net.URI uri = new java.net.URI( urlinput );
                desktop.browse( uri );
            }
            catch ( Exception e ) {

                System.err.println( e.getMessage() );
            }
    }

}
}

I can open a specified URL if it is specified inside the openbrowser.java, but I want to read the value of the JTextField I created in browseropen.java.


Answer:

You currently can't get information from the JTextField within the browseropen class because it is declared within a static main method and thus is visible only within that method. Your whole project screams to us -- he doesn't yet know about object-oriented programming or how Java implements it, since this is what is hampering your attempts.

Suggestions:

  • First of all, learn about object oriented programming with Java, including use of non-static methods and fields. There are many tutorials on this that are easy to find including those that can be found here: The Really Big Index
  • Make your browseropen more "OOP" compliant by giving it non-static fields and methods, including a private JTextField field.
  • Give it a public method that returns the String held by the JTextField
  • Don't have your openbrowserurl class extend the browseropen as that makes no sense. Instead have the first class contain an instance of the second class.

Other issues:

  • It's good that you're trying to use layout managers rather than the null layout and setBounds(...), but I'm confused about just what you're trying to do. You set the JFrame's layout to a GridLayout, one that expects 3 rows and 4 columns (12 components in all), and yet you only add one component to the JFrame, the "panel" JPanel. I'm not sure what you're trying to do, making it difficult what to advise in this situation.

For instance, you could create a class like so:

public class GetUrlPanel extends JPanel {
    private static final String PROMPT = "Welcome Please Enter URL to Begin!";
    private JTextField urlField = new JTextField(10);
    private JButton goToUrlButton = new JButton("Go To URL");

    public GetUrlPanel() {
        add(new JLabel(PROMPT));
        add(urlField);
        add(goToUrlButton);
    }

    public String getUrlFieldText() {
        return urlField.getText();
    }

    public void addGoToUrlListener(ActionListener listener) {
        goToUrlButton.addActionListener(listener);
    }
}

which would allow outside classes to display this JPanel wherever it is needed, would allow them to decide what to do when the button is pushed, and would allow them to extract the contents of the JTextField.

Another option is to get the URL more simply from a JOptionPane, such as:

public static void main(String[] args) {
    if (!Desktop.isDesktopSupported()) {
        System.err.println("Desktop is not supported. Exiting");
        System.exit(1);
    }
    String message = "Welcome Please Enter URL to Begin!";
    String title = "Enter URL";
    int messageType = JOptionPane.PLAIN_MESSAGE;
    String url = JOptionPane.showInputDialog(null, message, title, messageType);
    if (url == null) {
        System.err.println("Cancelled by user");
        System.exit(0);
    } else if (url.trim().isEmpty()) {
        System.err.println("You must enter a URL. Exiting");
        System.exit(2);
    }


    URI uri = null;
    try {
        uri = new URI(url);
        Desktop desktop = Desktop.getDesktop();
        desktop.browse(uri);
    } catch (URISyntaxException | IOException e) {
        String text = "Invalid URL \"" + url + "\". Exiting";
        System.err.println(text);
        e.printStackTrace();            
    }
}

There are lots of ways to skin this cat, but if there is one and only one thing that I want to stress in answering this question it is this:

You will want to study and learn OOPS concepts and techniques before doing anything else.

Question:

So I have to take a string input from GUI using Textfield and make it show up in a pdf document, when I use ActionListener :

b1[0].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) 
{
    s=tf1[0].getText();
}
});

When I run the gui and type in the tf1 and press b1, it should save it in s right? But it isn't doing that, however if I just hardcode s="string" it shows up in the pdf. Any ideas?

Forgot to mention I am using iText so the only problem i am having is that the String s is not getting saved from the TextField

Also the code for the actionlistener class if you want it:

public class GUI {
public  static String s;
public static void  gui(){

    {   
        try{
        String File_Name="C:/Users/Ray/Desktop/test.txt";
        ReadFile rf=new ReadFile(File_Name);
        JFrame f1=new JFrame("Maintest");
        JPanel p1=new JPanel();
        JPanel p2=new JPanel();
        final String[] aryLines=rf.OpenFile();
        final JTextField tf1[]=new JTextField[22];
        JButton []b1=new JButton[6];
        String bNames="OK";
        final JTextField tf2[]=new JTextField[aryLines.length];
        f1.setSize(200,450);


        JLabel l1[]=new JLabel[20];

        for ( int i=0; i < aryLines.length; i++ )
        {
            b1[i]=new JButton(bNames);
            l1[i]=new JLabel("Enter Serial# for "+ aryLines[i]);

            p1.add(l1[i]);p1.add(tf1[i] = new JTextField());p1.add(b1[i]);
        }


            p1.setLayout(new BoxLayout(p1,BoxLayout.PAGE_AXIS));

            f1.add(p1,BorderLayout.WEST);



                b1[0].addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent arg0) 
                {
                    s=""+tf1[0].getText();
                    System.out.println(s);
                }
                });

            f1.show();
        }

            catch(Exception e)
            {
                System.out.print(e);
            }
    }
 }
}

Answer:

Sorry that I can't answer in more detail, but you could check if the tf1[0].getText() works. Just put a System.out.println("Text: "tf1[0].getText()); into your ActionListener. I'm pretty sure it will be null or "Text: ". For further help you'll have to provide more code.

Please take a look at this link

Question:

public static void main(String[] args) throws IOException {
    //cevir("ornek3.txt");
    JFrame frame=new JFrame("Print");
    JPanel input=new JPanel();
    JPanel output=new JPanel(); output.setBackground(Color.black);
    final JTextArea ita = new JTextArea(30, 40);
    JScrollPane ijp = new JScrollPane(ita);
    JTextArea ota = new JTextArea(30, 40);
    JScrollPane ojp = new JScrollPane(ota);
    JButton buton=new JButton("Print");

    frame.setLayout(new FlowLayout());
    buton.setSize(50, 20);
    input.setBounds(0,0,500, 500);
    output.setBounds(500, 0, 500, 450);
    frame.setBounds(100, 50, 1000, 500);


    input.add(ijp, BorderLayout.CENTER);
    output.add(ojp, BorderLayout.EAST);
    input.add(buton, BorderLayout.SOUTH);
    frame.add(input);
    frame.add(output);

    buton.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            for(String line: ita.getText().split("\\n"));
                System.out.println(line);


        }
    });


    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
}

This is my code and i want to get the text that i wrote while the program running and print it to the console. Is it possible with JtextArea. This code prints null when i clicked the button to the console even if i write something to the textarea.


Answer:

You have use the JtextArea#append method.

        public void actionPerformed(ActionEvent e) {

            for(String line: ita.getText().split("\\n"))
               ota.append(line);


        }

Also variables used inside the methods inner class should be final, so make ota as final

    final JTextArea ota = new JTextArea(30, 40);

Question:

So I'm trying to have users type in an answer to the question via a text field, but the way I have it set up, the name field is only being stored inside the ActionListener Class and not the QName class. I've checked by trying to output Name using the Name() function. Does anyone have any ideas on how I can pull out the info and store it into QName's name field? Thanks in advance

Code for my QName function Code showing null output


Answer:

The reason why your name field is null is because typing in your textfield doesn't generate any events that are caught by the associated listener.

You seem to have attached an ActionListener directly to your JTextField. The more typical (and for your purposes, the more correct) implementation is to associate the listener to a button in your QName object.

To fix your code, you're going to have to create a button. Let's assume you call it "OK". Then associate an ActionListener to the button instead of the textfield. Then your user can type a character name and click OK. In turn, your listener will detect the button press and set name to the contents of the textfield.

I'd post sample code, but I'm not going to key in all the code from your picture (this is another reason why you don't post pictures).

Question:

I am fairly new to Java and just wanted to ask about ActionListener method. I've created a GUI and in one panel I want to ask the user to input values of x and press submit. It looks like this: f(x)= [input field] - [input field] ^2 (submit button) I am lost and don't know what to put in ActionPerformed method to get the values that user inputs (also the method in which I created the panel, text fields etc is private if that's relevant )

I have already tried x1.getText(), but it seems like it can't access the variable as the JPanel method is private, and ActionPerformed is public

private JPanel panel2() 
    {    
        inputPanel.setLayout(new FlowLayout());

        JTextField  x1 = new JTextField();
        JTextField  x2 = new JTextField();

        JLabel f = new JLabel ("F(x)= ");
        JLabel f2= new JLabel (" - ");
        JLabel f3 = new JLabel (" ^2 ");
        JButton submit1 = new JButton("Submit values");

        submit1.addActionListener(this);

        inputPanel.add(f);
        inputPanel.add(x1);
        inputPanel.add(f2);
        inputPanel.add(x2);
        inputPanel.add(f3);
        inputPanel.add(submit1);
      }
    {
        if("submit1".equals(e.getActionCommand()))
        {
           // and that's where I get lost

        }
    } 

Answer:

I am inferring by your discription that panel2 is a method and both JTextfields x1 and x2 are local variables of method panel2 which won't be accessible outside it.

You will need to declare the x1 and x2 globally and if you want them to be private, associate getters and setters with them and use it in the actionperformed method.

Question:

I posted my full code below so you guys could have a solid understanding of what I want. When I click send, the text field clears but is not ready for input. I have to click for the input. I want it to be ready for the input immediately and textfield.setText("") will not work. Any ideas?

package javaapplication2;

import java.util.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
import java.io.*;
import javax.swing.*;//class to use to create GUI's
import javax.swing.border.Border;
import javax.swing.plaf.FontUIResource;

/**
 *
 * @author Jordan Anthony Hangman with dictionary
 */

public class JavaApplication2 extends JFrame{

static JLabel[] labels = new JLabel[20];//labels for displaying words under 20 characters
static int counter = 0;
static int badguess = 0;//keeps track of wrong guesses
static String wordbank = "   Letter Bank:";
static char[] guesses = new char[26];
static int nguesses = 0;
static int amountc = 0;

public JavaApplication2(){

}

public static void main(String[] args) throws FileNotFoundException, IOException {

    //Loading images to use for hangman game
    ImageIcon hanginit = new ImageIcon("hangmaninit.jpg");
    ImageIcon hang1 = new ImageIcon("hangman1.jpg");
    ImageIcon hang2 = new ImageIcon("hangman2.jpg");
    ImageIcon hang3 = new ImageIcon("hangman3.jpg");
    ImageIcon hang4 = new ImageIcon("hangman4.jpg");
    ImageIcon hang5 = new ImageIcon("hangman5.jpg");
    ImageIcon hang6 = new ImageIcon("hangman6.jpg");

    //initializing array for index values
    int wordcount = 10;
    String[] words1 = new String[wordcount];
    int[] wordssel = new int[10];
    for (int j=0; j<10; j++){
        wordssel[j] = -1;
    }

    //setting instructions
    String Instructions = "To start the game, click on the new game button. You get 6 incorrect guesses for every word. Once you get 6 guesses, the game will end. Click the end game button to go back to the home page. If you want to play again, you can click New Game and you will be able to guess a different word. After every game, a message will appear to tell you how many words you have guesses correctly. When all the words are played, a dialog box will be shown that says Game Over. Exit this box to exit the game.";

    //reading in the words
    int number = 0;
    try(BufferedReader br = new BufferedReader(new FileReader("words.txt")))       
    {
        String line = br.readLine();
        while(line != null){
            words1[number] = line;
            number++;
            line = br.readLine();
        }
    }

    //randomizes words
    boolean flag = false;
    int rand = 0;
    int count = 0;
    int wordcounter = 0;
    while(!flag){
        Random random = new Random();
        rand = random.nextInt(wordcount);
        count = 0;
        for (int o=0; o<wordcount; o++){
            if(wordssel[o] != rand){
                count++;
            }
        }
        if(count == wordcount){
            wordssel[wordcounter] = rand;
            wordcounter++;
        }
        if(wordcounter == wordcount){
            flag = true;
        }
    }
    String[] randwords = new String[10];
    for(int o=0; o<10; o++){
        randwords[wordssel[o]] = words1[o];
    }

    //initializing label
    for(int i=0; i<20; i++){
        labels[i] = new JLabel(" ");
        labels[i].setFont(new Font("Serif", Font.BOLD, 30));
    }

    //initializing guessedchar array
    for(int i=0; i<26; i++){
        guesses[i] = ' ';
    }

    //value for window size
    int xlim = 1200;
    int ylim = 1200;
    int xlim2 = 1600;
    int ylim2 = 1600;
    int xlim3 = 900;
    int ylim3 = 600;

    //value for x and y centers
    int xcent = xlim/2 - 20;
    int ycent = ylim/2;
    int xcent2 = xlim2/2;
    int ycent2 = ylim2/2 - 20;
    int xcent3 = xlim3/2;
    int ycent3 = ylim3/2 - 20;

    //creating frames
    JFrame frame1 = new JFrame("Hangman");//creates a new frame or window
    frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// I thiunk exits when clicks on red x
    frame1.setSize(xlim, ylim); //size of window in pixels
    JFrame frame2 = new JFrame("Hangman");//creates a new frame or window
    frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// I thiunk exits when clicks on red x
    frame2.setSize(xlim2, ylim2); //size of window in pixels
    JFrame frame3 = new JFrame();
    frame3.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame3.setSize(xlim3, ylim3);

    //change font size for label, button, and textfield
    UIManager.put("Button.font", new FontUIResource(new Font("Dialog", Font.BOLD, 24)));
    UIManager.put("Label.font", new FontUIResource(new Font("Dialog", Font.PLAIN, 24)));
    UIManager.put("TextField.font", new FontUIResource(new Font("Dialog", Font.PLAIN, 24)));
    UIManager.put("TextArea.font", new FontUIResource(new Font("Dialog", Font.PLAIN, 24)));

    //creates buttons
    JButton button1 = new JButton("New Game?");
    button1.setBounds(xcent - 90, ycent - 165, 180, 130);//(xstart, ytop, width, height)
    JButton button2 = new JButton("End Game?");
    button2.setBounds(xcent - 90, ycent - 65, 180, 130);//(xstart, ytop, width, height)
    JButton button3 = new JButton("Instructions");
    button3.setBounds(xcent - 120, ycent, 240, 100);
    JButton button4 = new JButton("Main Menu");
    button4.setBounds(xcent - 100, ycent + 100, 200, 100);

    //creating border
    Border border = BorderFactory.createLineBorder(Color.BLACK, 4);

    //creating labels
    JLabel labelresult = new JLabel("");//label for win or losing game
    labelresult.setBounds(400, 400, 400, 40);
    JLabel labelhang = new JLabel();//label for hangman images
    labelhang.setBounds(450, 375, 677, 620);
    JLabel label3 = new JLabel("Hello");
    label3.setBounds(200, 260, 500, 40);
    JLabel label4 = new JLabel("Hello");
    label4.setBounds(440, 1300, 800, 40);
    JLabel label5 = new JLabel("Hello");
    label5.setBounds(590, 1300, 800, 40);
    JLabel label6 = new JLabel("Game Over");
    label6.setBounds(380, 250, 200, 40);
    JLabel lettersw = new JLabel();
    JLabel label7 = new JLabel("How To Play");
    label7.setBounds(500, 50, 200, 40);
    JLabel label8 = new JLabel("Error");
    label8.setBounds(590, 1300, 800, 40);
    label8.setText("You can only enter one letter at a time.");
    JLabel label9 = new JLabel("Error");
    label9.setBounds(674, 1300, 800, 40);
    label9.setText("You must enter a letter");
    JLabel label10 = new JLabel(wordbank);
    label10.setBounds(xcent2 - 200, 220, 400, 40);
    JLabel label11 = new JLabel("You have already entered this letter.");
    label11.setBounds(608, 1300, 800, 40);
    JLabel label12 = new JLabel("You must exit game to guess.");
    label12.setBounds(639, 1300, 800, 40);


    //creating text area and setting properties
    JTextArea texta1 = new JTextArea();
    texta1.setOpaque(false);
    texta1.setLineWrap(true);
    texta1.setWrapStyleWord(true);
    texta1.setBounds(100, 100, 1000, 600);
    texta1.setText(Instructions);


    //adding items to frames
    frame1.add(button1);
    frame1.add(button3);
    frame2.add(button2);
    frame2.add(labelhang);
    frame3.add(label6);
    frame2.add(label4);
    frame2.add(label5);
    frame3.add(label6);
    frame1.add(label7);
    frame1.add(texta1);
    frame1.add(button4);
    frame2.add(label8);
    frame2.add(label9);
    frame2.add(label10);
    frame2.add(label11);
    frame2.add(label12);

    //set item properties
    labelresult.setVisible(false);
    button2.setVisible(false);
    labelhang.setIcon(hanginit);
    label4.setVisible(false);
    label5.setVisible(false);
    label7.setVisible(false);
    texta1.setVisible(false);
    button4.setVisible(false);
    label8.setVisible(false);
    label9.setVisible(false);
    label10.setBorder(border);
    label11.setVisible(false);
    label12.setVisible(false);

    //set frame properties
    frame1.setLayout(null);
    frame1.setVisible(true);//makes the frame visible to the user
    frame3.setLayout(null);

    //When End Game button is pressed
    button2.addActionListener(new ActionListener(){

        @Override
        public void actionPerformed(ActionEvent e){

            //end of game conditions
            label5.setVisible(false);
            label4.setVisible(false);
            label12.setVisible(false);
            button2.setVisible(false);
            frame2.setVisible(false);
            wordbank = "   Letter Bank:";
            badguess = 0;
            amountc = 0;
            if(counter == wordcount){
                frame3.setVisible(true);//frame after all words gone through
            }
            else{
                labelhang.setIcon(hanginit);
                frame1.setVisible(true);
            }
        }
    });

    //When Instructions button is pressed
    button3.addActionListener(new ActionListener(){

        @Override
        public void actionPerformed(ActionEvent e){
            button1.setVisible(false);
            button3.setVisible(false);
            label7.setVisible(true);
            texta1.setVisible(true);
            button4.setVisible(true);
        }
    });

    //When Main Menu is pressed
    button4.addActionListener(new ActionListener(){

        @Override
        public void actionPerformed(ActionEvent e){
            button1.setVisible(true);
            button4.setVisible(false);
            button2.setVisible(true);
            label7.setVisible(false);
            texta1.setVisible(false);
            button3.setVisible(true);
        }
    });

    //When New Game is press
    button1.addActionListener(new ActionListener(){

        @Override
        public void actionPerformed(ActionEvent e){

            //set item properties
            frame2.setLayout(null);
            frame2.setVisible(true);
            frame1.setVisible(false);
            button2.setVisible(false);
            label8.setVisible(false);
            label9.setVisible(false);
            wordbank = "   Letter Bank:";
            label10.setText(wordbank);

            //initializes labels and word
            for(int i=0; i<20; i++){
                labels[i].setText(" ");
            }
            String currentword = randwords[counter];
            counter++;

            //initializing previos guesses
            for(int i=0; i<26; i++){
                guesses[i] = ' ';
            }
            nguesses = 0;

            //creating panel and panel components always create panels and all components in the same place that they are being added
            JButton send = new JButton("Send");
            JButton clear = new JButton("clear");
            JTextField tf = new JTextField(1);
            JLabel label = new JLabel("Enter Guess");
            JPanel panel = new JPanel();
            panel.add(label);
            panel.add(tf);
            panel.add(send);
            panel.add(clear);
            panel.setBounds(xcent2 - 250, ylim2 - 102, 500, 40);
            frame2.add(panel);

            //placing labels for letters
            int letters = currentword.length();
            int spacing2 = 800-(int)(letters*12.5);
            for (int i=0; i<letters; i++){
                labels[i].setText("_");
                int spacing = 25 * i;
                labels[i].setBounds(spacing2 + spacing, 1100, 25, 40);
                frame2.add(labels[i]);
            }

            //when clear button is pressed
            clear.addActionListener(new ActionListener(){

                @Override
                public void actionPerformed(ActionEvent e){
                    tf.setText("");
                }
            });

            //when send button is pressed
            send.addActionListener(new ActionListener(){

                int amountc1 = 0;//keeps track of correctly guessed amount of words
                int counter2 = 0;//keeps track of amount of correct letter guesses for each word
                int letters2 = 0;

                @Override
                public void actionPerformed(ActionEvent e){

                    //initialize word and user guess
                    String currentword = randwords[counter-1];
                    letters2 = currentword.length();
                    char[] wordcurrent = new char[20];
                    wordcurrent = currentword.toCharArray();
                    String userguess = tf.getText();
                    userguess = userguess.toLowerCase();
                    tf.setText("");

                    //set properties
                    label4.setVisible(false);
                    label5.setVisible(false);
                    label8.setVisible(false);
                    label9.setVisible(false);
                    label11.setVisible(false);

                    //checking guess with word
                    boolean flag2 = false;
                    boolean flag3 = false;

                    //checking if word is already solved and user is entering data
                    System.out.println(badguess);
                    System.out.println(amountc);
                    System.out.println(nguesses);
                    if(nguesses > badguess + amountc){
                        label4.setVisible(false);
                        label5.setVisible(false);
                        label12.setVisible(true);
                        nguesses++;
                        flag2 = true;
                    }
                    else if(userguess.length() > 1){
                        label8.setVisible(true);
                        flag2 = true;
                        nguesses++;
                    }
                    else if(userguess.length() < 1){
                        label9.setVisible(true);
                        flag2 = true;
                        nguesses++;
                    }
                    else{
                        char[] guessuser = userguess.toCharArray();
                        char guessedchar = guessuser[0];
                        int charval = (int)guessedchar;//97-122 lowercase, 65-90 for uppercase

                        //checks for previous guesses
                        for(int t=0; t<=nguesses; t++){
                            if(guessedchar == guesses[t]){
                                flag3 = true;
                                break;
                            }
                        }
                        nguesses++;

                        //checking word against guess
                        for(int i=0; i<letters2; i++){
                            if(!flag3){
                                if(((charval>96 & charval<123))){
                                    guesses[nguesses] = guessedchar;
                                    if(wordcurrent[i] == guessedchar){
                                        labels[i].setText(userguess);
                                        labels[i].setVisible(true);
                                        flag2 = true;
                                        counter2++;
                                        nguesses++;
                                        amountc++;
                                    }
                                }
                                else{
                                    label9.setVisible(true);
                                    flag2 = true;
                                }
                            }
                            else{
                                label11.setVisible(true);
                                flag2 = true;
                            }
                        }
                    }

                    //checks if full word is guessed correctly
                    if(counter2 == letters2){
                        this.amountc1++;
                        nguesses++;
                        button2.setVisible(true);
                        String correctword = "Well done! You have solved " + amountc1 + " out of " + counter;
                        label5.setText(correctword);
                        label5.setVisible(true);
                        counter2 = 0;
                        if(counter == wordcount){
                            label3.setText(correctword);
                        }
                    }

                    //checks for wrong guess and changes hangman picture accordingly
                    if (flag2 == false){
                        badguess++;
                        switch(badguess){
                            case 1:
                                wordbank += " " + userguess;
                                label10.setText(wordbank);
                                labelhang.setIcon(hang1);
                                break;
                            case 2:
                                wordbank += ", " + userguess;
                                label10.setText(wordbank);
                                labelhang.setIcon(hang2);
                                break;
                            case 3: 
                                wordbank += ", " + userguess;
                                label10.setText(wordbank);
                                labelhang.setIcon(hang3);
                                break;
                            case 4: 
                                wordbank += ", " + userguess;
                                label10.setText(wordbank);
                                labelhang.setIcon(hang4);
                                break;
                            case 5:
                                wordbank += ", " + userguess;
                                label10.setText(wordbank);
                                labelhang.setIcon(hang5);
                                break;
                            case 6:
                                nguesses++;
                                wordbank += ", " + userguess;
                                label10.setText(wordbank);
                                labelhang.setIcon(hang6);
                                button2.setVisible(true);
                                String incorrectword = "Sorry, The correct word was " + currentword + " You have solved " + amountc1 + " out of " + counter;
                                label4.setText(incorrectword);
                                label4.setVisible(true);
                                this.counter2 = 0;
                                if(counter == wordcount){
                                    label3.setText(incorrectword);
                                }
                                break;
                            default:
                                break;
                        }
                    }
                    else{
                        nguesses--;
                    }
                }
            });
        }
    });   
}
}

Answer:

To focus text field after setText(""); method you can use the following,

textFieldName.requestFocus();

To center the text field you can use this code,

textFieldName.setHorizontalAlignment(JTextField.CENTER);

Question:

enter image description here

How can I make it like that? 1) If user opens that program, you don't have to click on textfield to receive focus, instead, if you switch to that program, it immediatetly gives you a focus to write instead of clicking for focus.

2) If user writes a ID number or item name to textfield, textarea responds to textfield and shows that ID or name to the user, like, pops up.

3) How to make textarea smaller in case, that even panel shows out in corners? I'd like to make a textarea a little bit smaller like a box and outside a box, its just a gray color.

In order to fully help me, I'll gladly give out the code.

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingConstants;

public abstract class Itemlist extends JFrame implements ActionListener, FocusListener {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;


    public static void main(String args[]) {
        // create JFrame
        JFrame frame = new JFrame("small project");
        frame.setDefaultCloseOperation(2);
        frame.setPreferredSize(new Dimension(400, 600));
        frame.setLayout(new BorderLayout());
        frame.setResizable(false);


        JPanel panel = new JPanel(new FlowLayout(SwingConstants.LEADING, 10, 10));
        frame.add(panel);
        panel.setPreferredSize(new Dimension(100, 50));

        JTextField tf = new JTextField(25);
        tf.setPreferredSize(new Dimension(100, 35));
        Font f = new Font("Times New Roman", Font.BOLD, 18);
        tf.setFont(f);
        panel.add(tf);
        frame.add(tf, BorderLayout.PAGE_END);

        tf.addFocusListener(new FocusListener() {

            @Override
            public void focusGained(FocusEvent e) {
                tf.getText();

            }

            @Override
            public void focusLost(FocusEvent e) {
                tf.setText("");

            }

        });

        JTextArea ta = new JTextArea();
        frame.add(ta);
        Font font = new Font("Times New Roman", Font.PLAIN, 16);
        ta.setEditable(false);
        ta.setFont(font);

        JScrollPane scrollPane = new JScrollPane(ta);
        scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        frame.add(scrollPane);

        BufferedReader br;
        String contents;

        try {
            br = new BufferedReader(new FileReader("C:/ItemList.txt"));
            contents = br.readLine();

            while ((contents = br.readLine()) != null) {


                ta.read(br, null);
            }
            br.close();
        } catch (IOException e) {

        }


        frame.pack();
        // frame.setLocationRelativeTo(null);
        frame.setVisible(true);

    }

    @Override
    public void actionPerformed(ActionEvent arg0) {

    }
}

*All help is appreciated. Have been stuck on it.


Answer:

  1. I suspect you want to consider using a WindowListener and monitor for the windowActivated event, at which time you can call requestFocusInWindow on the JTextField to transfer focus to it automatically. Focus management is a little bit of a black art, as it tends to work slightly differently on different platforms
  2. I'm not sure entirely what you mean, but I'd look at the ActionListener support. This will require the user to hit the "action" key (typically Enter) to trigger it. If you want real time feedback, the a DocumentListener would be what you're looking for
  3. Make use of the JTextAreas constructor to specify the preferred number of rows and columns. This will define the preferred scrollable size of the component, which will effect the size of the JScrollPane as well
  4. In future, try and constrain you question to single, focused question, they are easier to answer and generally produce more detail

Question:

I need help for converting textfield input into int for validation. The contactnum is from the field textFieldContactnum. I want to convert textFieldContactnum's input into int. I've tried storing the textFieldContactnum.getText() into a String first and use a new int (contactnumber) to parse (Integer.parseInt) in like below the codes..

 private void actionPerformedOk() {
        String username = textFieldUsername.getText();
        String password = passwordField.getText();
        String email = textFieldEmail.getText();
        String securityqn = textFieldSecurityqn.getText();
        String securityanswer = textFieldSecurityanswer.getText();
        contactnumber = textFieldContactnum.getText();
        int contactnum = Integer.parseInt(contactnumber);
        String firstname = textFieldFirstName.getText();
        String lastname = textFieldLastName.getText();
        String gender = genderSelected;
        String nric = textFieldNRIC.getText();
        String address = textFieldAddress.getText();
        postalcode1 = textFieldPostalCode.getText();
        int postalcode = Integer.parseInt(postalcode1);

        String day = dayList.getSelectedItem().toString();
        String month = monthList.getSelectedItem().toString();
        String year = yearList.getSelectedItem().toString();

        if (!day.equals("Day") && !month.equals("Month") && !year.equals("Year")) {
             dateAsString = day + "/" + month + "/" + year;
             SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
             try {
                 Date date = sdf.parse(dateAsString);
                    System.out.println(date);
             } catch (ParseException e1) {}

        }

        dateAsString = day + ("/") + month + ("/") +  year;

        String date = dateAsString;
 // retrieve the user input from the text box/area provided
         if (validateInput()) {
             username = textFieldUsername.getText();

 if (actions.equalsIgnoreCase("Submit")){
signup = new hiroSIGNUP(username, password, email, securityqn, securityanswer, contactnum, firstname, lastname, gender, nric, address, postalcode, date);
 actionPerformedCreate();
 }

 else{ 
 // update the values of the current expense object 
     //update empty to some fields
 signup.setUsername(username);
 signup.setPassword(password);
 signup.setEmail(email);
 signup.setSecurityqn(securityqn);
 signup.setSecurityanswer(securityanswer);
 signup.setContactnum(contactnum);
 signup.setFirstname(firstname);
 signup.setLastname(lastname);
 signup.setGender(gender);
 signup.setNric(nric);
 signup.setAddress(address);
 signup.setPostalcode(postalcode);
 signup.setDate(date);
 actionPerformedUpdate();
 }
         }
 }
 /**
 * Purpose: This method updates the expense record
 * in the database.
 * Input: Nil
 * Return: void
 */

 public void actionPerformedUpdate(){
 // Update record in database and check return value
 if (SignupDA.updatehiroSIGNUP(signup)) {
 JOptionPane.showMessageDialog(myFrame,
 "Record updated successfully", "Alert",
 JOptionPane.INFORMATION_MESSAGE);
 // reset text field for next record.
 textFieldUsername.setEditable(false);
 passwordField.setEditable(false);
 textFieldEmail.setEditable(false);
 textFieldSecurityqn.setEditable(false);
 textFieldSecurityanswer.setEditable(false);
 textFieldContactnum.setEditable(false);
 textFieldFirstName.setEditable(false);
textFieldLastName.setEditable(false);
dayList.setEditable(false);
monthList.setEditable(false);
yearList.setEditable(false);
textFieldNRIC.setEditable(false);
textFieldAddress.setEditable(false);
textFieldPostalCode.setEditable(false);
 } 
 else {
 JOptionPane.showMessageDialog(myFrame,
 "Database Error. Record not updated.", "Alert",
 JOptionPane.ERROR_MESSAGE);
 }
 }

 /**
 * Purpose: This method creates the expense record
 * in the database.
 * Input: Nil
 * Return: void
 */
 public void actionPerformedCreate(){
 // insert to database and check return value
 if (SignupDA.createhiroSIGNUP(signup)) {
 JOptionPane.showMessageDialog(myFrame,
 "Record created successfully", "Alert",
 JOptionPane.INFORMATION_MESSAGE);
 // reset text field for next record.
 // reset text field for next record.
 textFieldUsername.setText("");
 passwordField.setText("");
 textFieldEmail.setText("");
 textFieldSecurityqn.setText("");
 textFieldSecurityanswer.setText("");
 textFieldContactnum.setText("");
 textFieldFirstName.setText("");
textFieldLastName.setText("");
group.clearSelection();
textFieldNRIC.setText("");
textFieldAddress.setText("");
textFieldPostalCode.setText("");

 } 
 else
 JOptionPane.showMessageDialog(myFrame,
 "Database Error. Record not created.", "Alert",
 JOptionPane.ERROR_MESSAGE);
 }

 private boolean validateInput() {
 boolean result = false;
 String msg = "";
 int msgType = JOptionPane.ERROR_MESSAGE;
 // retrieve the user input from the text box/area provided
    String username = textFieldUsername.getText();
    String password = passwordField.getText();
    String email = textFieldEmail.getText();
    String securityqn = textFieldSecurityqn.getText();
    String securityanswer = textFieldSecurityanswer.getText();
    int contactnum = Integer.parseInt(contactnumber);
    String firstname = textFieldFirstName.getText();
    String lastname = textFieldLastName.getText();
    String gender = genderSelected;
    //FIND OUT HOW TO VALIDATE GENDER RADIO BUTTON
    String nric = textFieldNRIC.getText();
    String address = textFieldAddress.getText();
    int postalcode = Integer.parseInt(postalcode1);
    String date = dateAsString;



 if (username.length() == 0)
 msg += "Please enter Username.\n";
 if (password.length() == 0)
 msg += "Please enter password.\n";
 if (email.length() == 0)
 msg += "Please enter Email.\n";
 if (securityqn.length() == 0)
 msg += "Please enter Security Question.\n";
 if (securityanswer.length() == 0)
 msg += "Please enter Security Answer\n";
 if (contactnumber.length() == 0)
 msg += "Please enter Contact Number\n";
 if (firstname.length() == 0)
 msg += "Please enter First name\n";
 if (lastname.length() == 0)
 msg += "Please enter Last name\n";
 if (genderSelected.length() == 0)
 msg += "Please enter Gender\n";
 if (nric.length() == 0)
 msg += "Please enter NRIC\n";
 if (address.length() == 0)
 msg += "Please enter Address\n";
 if (postalcode1.length() == 0)
 msg += "Please enter Postal code\n";
 if (date.length() == 0)
     msg += "Please enter Date\n";  

 if (msg.length() == 0)
 result = true;
 else
 JOptionPane.showMessageDialog(myFrame, msg, "Alert", msgType);
 return result;
 }

 /**
 * @wbp.parser.constructor
 */
 public hiroSIGNUPPanel(JFrame mf, String action, hiroSIGNUP s){
 this(mf, action);

//display the current expense information
    signup = s;
    textFieldUsername.setText(s.getUsername());
    passwordField.setText(s.getPassword());
    textFieldEmail.setText(s.getEmail());
    textFieldSecurityqn.setText(s.getSecurityqn());
    textFieldSecurityanswer.setText(s.getSecurityanswer());
    textFieldContactnum.setText(String.valueOf(s.getContactnum()));
 textFieldFirstName.setText(s.getFirstname());
textFieldLastName.setText(s.getLastname());
//textFieldGender.setText(s.getGender());
textFieldNRIC.setText(s.getNric());
textFieldAddress.setText(s.getAddress());
textFieldPostalCode.setText(String.valueOf(s.getPostalcode()));

}

}

and my error is this

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at hiroApp.ui.hiroSIGNUPPanel.actionPerformedOk(hiroSIGNUPPanel.java:781)

Answer:

Before parsing you may try to check

if(contactnumber.trim().length() == 0) {
}

Also you may want to use long as int won't be able to store 10 digit contact number.

Question:

Why can't I switch input language in jtextfield and JOptionPane.showInputDialog()? On my computer I can, but on other computer I can write only system locale language symbols.

Ctrl+Shift or Ctrl+Alt+Shift is not working in application, but it is working when app is not focus

Locale.setDefault(Locale.ENGLISH); //tried it
System.setProperty("user.language", "en"); // and it

private void showPasswordWindow() {

    String pass = JOptionPane.showInputDialog(null, "Enter password", "Secure", JOptionPane.WARNING_MESSAGE);
    if (pass == null)
        System.exit(0);
    if (!pass.contains("somepassword"))
        showPasswordWindow();
}

Not working (( password contain English symbols and I can't to enter password (only Russia symbols working)

JRE 8; PS: I want to enter English symbols, but I can type only Russian symbols...NOT WORKING ONLY DIALOG TEXTFIELDS


Answer:

There are two issues here.

The first is entering the symbols. This isn't really a Java problem, so much as an issue with installing a different language for the keyboard.

The second issue is displaying foreign language symbols. You may need to use a UTF font to display characters that otherwise don't display right

Question:

Why can't I switch input language in jtextfield and JOptionPane.showInputDialog()? On my computer I can, but on other computer I can write only system locale language symbols.

Ctrl+Shift or Ctrl+Alt+Shift is not working in application, but it is working when app is not focus

Locale.setDefault(Locale.ENGLISH); //tried it
System.setProperty("user.language", "en"); // and it

private void showPasswordWindow() {

    String pass = JOptionPane.showInputDialog(null, "Enter password", "Secure", JOptionPane.WARNING_MESSAGE);
    if (pass == null)
        System.exit(0);
    if (!pass.contains("somepassword"))
        showPasswordWindow();
}

Not working (( password contain English symbols and I can't to enter password (only Russia symbols working)

JRE 8; PS: I want to enter English symbols, but I can type only Russian symbols...NOT WORKING ONLY DIALOG TEXTFIELDS


Answer:

There are two issues here.

The first is entering the symbols. This isn't really a Java problem, so much as an issue with installing a different language for the keyboard.

The second issue is displaying foreign language symbols. You may need to use a UTF font to display characters that otherwise don't display right

Question:

I have this code:

    static JFrame inputFrame = new JFrame();
    static JTextField myTextfield = new JTextField();
    static JButton myButton = new JButton("Hi!");

private static void inputGUI() {
    inputFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    inputFrame.setTitle("The INPUT");
    inputFrame.setLayout(new FlowLayout());
    inputFrame.setSize(1366,768);
    inputFrame.setVisible(true);

    inputFrame.add(myTextField);
    inputFrame.add(myButton);

    myButton.setEnabled(false);
    myTextField.addActionListener(myListener);
}
static ActionListener myListener = new ActionListener(){
    public void actionPerformed(ActionEvent e){
        if(e.getSource()==inputFrame){
            //What Do I put here?
        }
    }
}

What I want to do is this: When I type something in myTextField without pressing enter, the button,myButton is enabled( e.g. myButton.setEnabled(true);).


Answer:

The best solution is using DocumentFilter . so it can check when your JTextField contains something then your can trigger your button to be active.

Here, I remodified your codes :

  import java.awt.*;
  import javax.swing.*;
  import javax.swing.text.AbstractDocument;
  import javax.swing.text.AttributeSet;
  import javax.swing.text.BadLocationException;
  import javax.swing.text.DocumentFilter;

class checkText extends DocumentFilter {
public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text,
        AttributeSet attrs) throws BadLocationException {
        super.replace(fb, offset, length, text, attrs);
       GuiTest.enableButton();
       }
      }

 public class GuiTest extends JFrame {
static JFrame inputFrame = new JFrame();
static JTextField myTextfield = new JTextField(10);
static JButton myButton = new JButton("Hi!");

public GuiTest() {
    inputGUI();
}

private static void inputGUI() {
    inputFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    inputFrame.setTitle("The INPUT");
    inputFrame.setLayout(new FlowLayout());
    inputFrame.setSize(1366, 768);
    inputFrame.setVisible(true);

    inputFrame.add(myButton);

    DocumentFilter filter = new checkText();
    ((AbstractDocument) myTextfield.getDocument()).setDocumentFilter(filter);
    inputFrame.add(myTextfield);
    myButton.setEnabled(false);
}

public static void enableButton() {
    myButton.setEnabled(true);
}

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

before :

after :

Question:

I recently built and completed the first stage of a program in java that worked with IDE using System.out.println(); and what not. Now, I want to give this program a GUI and I ran into an issue. Here is my MCV example (or at least I think it is, let me know if it is not).

import java.net.*;
import java.net.UnknownHostException;
import java.net.NoRouteToHostException;
import java.io.*;
import net.sf.json.*;
import org.apache.commons.lang.exception.*;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.BoxLayout;
import javax.swing.JOptionPane;
import java.awt.Component;
import java.awt.Container;
import java.util.Scanner;


public class WOT_PlayerComp_V2
{

   public static JFrame f;
   public static JLabel resultLabel;
   public static JPanel p;
   public static JTextField t;
   public static String comparisonResults = "";
   public static String holder = "";
   public static String playerName = "";
   public boolean gameIsStillRunning = true;

   public static void testGUI()
   {
      f = new JFrame();

      addComponentsToPane(f.getContentPane());



      f.setSize(300, 400);
      f.setLocation(200, 200);
      // f.setResizable(false);
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      f.setVisible(true);

   }

   public static void addComponentsToPane(Container c)
   {
      c.setLayout(new BoxLayout(c, BoxLayout.Y_AXIS));

      p = new JPanel();
      t = new JTextField(15);
      //t.setDocument(new JTextField_wLimit(50));
      //You can ignore this line, it is what I used to limit the input of my textfield
      resultLabel = new JLabel();


      //html makes the br have purpose, p makes it wrap
      resultLabel.setHorizontalAlignment(SwingConstants.CENTER);
      resultLabel.setVerticalAlignment(SwingConstants.TOP);
      resultLabel.setSize(50, 50);

      c.add(t);
      c.add(resultLabel);


   }

   public WOT_PlayerComp_V2()
   {

      testGUI();

   //... Lots of irrelevant code

      resultLabel.setText("Enter your username.");

      while(gameIsStillRunning)
      {

      //irrelevant code

         playerName = t.getText();//scans user input
         t.setText("");

      //more irrelevant code
      }

      //if(playerName == null || playerName.equals(""))
      //^^ it shouldn't go into here, I want my while loop to wait 
      //for user input like it did when i was using a Scanner object
      //

   }

   public static void main(String[] args)
   {

      WOT_PlayerComp_V2 w = new WOT_PlayerComp_V2();

   }

}

Basically, prior to me using a JTextField object, I was using a Scanner object. The Scanner object would actually stop my while loop and run that method, then continue. I want to know if this is possible with a JTextField. I want to be able to stop the for loop in the middle and wait for the user input. It doesn't seem as big a problem with the MCV example I have above, but the code I am using is based heavily on input and will respond to a user entering null or empty strings. As a result, it will do what it was meant to do, respond to correct user input, and this will only last for one iteration, then it will keep taking input from the JTextField, since it is in a while loop. That's my problem.


Answer:

GUI programs don't work like this, as they do in console programs. There is no "waiting for user input" like using Scanner. With Swing, events are fired by different interations from the user. It is your job, as the programmer to listen for these events by adding the appropriate listener to the component that fires the event you want to listen for. For instance, you can listen for an ActionEvent on the text field (the event is fired when the user hits enter. You add an ActionListener to the text field that will listener for those events. You can do then do some processing when that event occurs.

final JTextField field = new JTextField(20);
field.addActionListener(new ActionListener(){
    @Override
    public void actionPerformed(ActionEvent e) {
        String text = field.getText();
        System.out.println(text);
        field.setText(text);
    }
});

Please take some time to go over Writing Event Listeners

Question:


Answer:

you can just do textfieldname.setText("");

Question:

Could you help me with this little problem? I'm trying to make a menu system which shows the options in a JEditorPane, it's something like this:

Welcome

Select an option. 1.) New register. 2.) New input. 3.) Exit.

the options are chosen by the user through a JTextField, when "1" is entered it shows another menu:

New register

1.) Option X. 2.) Option Y. 3.) Back.

and so on, the problem is that I don't know how I can capture the user's input, advance to the next menu, and re-capture the user's input all in a JTextField.

textField.addActionListener(new ActionListener () {

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

            cap = textField.getText();

            switch(cap) {

            case "1":
                paintEditorPane("Welcome");

                    // here is my problem, I don't know how to re-capture JTextField input
                 switch(cap){

                 case "1":
                       paintEditorPane("NewRegister");
                       break;
                    }
            break;
            }
        }
    });

Answer:

Here's Basic. Now you have to make many cases to judge states.

public static class MainPanel extends JPanel{
    private JTextArea textArea;

    public MainPanel() {
        this.setLayout(new BorderLayout());
        this.textArea = new JTextArea();// you can use constructor to set Text but I like use method "setText".
        this.textArea.addKeyListener(new keyHandler());
        this.textArea.setText("Welcome\r\nSelect an option. 1.) New register. 2.) New input. 3.) Exit.\r\n");
        this.textArea.setCaretPosition(this.textArea.getText().length());// move caret to last
        this.add(this.textArea, BorderLayout.CENTER);
    }

    public void addText(String text) {textArea.setText(textArea.getText() + "\r\n" + text +"\r\n");}

    public class keyHandler extends KeyAdapter{
        @Override
        public void keyReleased(KeyEvent e) {
            switch(e.getKeyCode()){
            case KeyEvent.VK_1 : addText("New register"); break;
            case KeyEvent.VK_2 : addText("New input"); break;
            case KeyEvent.VK_3 : addText("Exit"); break;
            }
        }
    }
}

Question:

I got a JTextfield a GetText method, and an array to store the numbers logged on the Jtextfield.

JTextField tf1 = new JTextField();
frame.add(tf1);

String tfone = tf1.getText();
int one = Integer.parseInt(tfone);

int[][] array = new int[4][5]; 
array[0][0] = one;
array[0][1] = otherValues...

The problem here is, that code execute all, so no wait for a user input into the JtextField. How can i make the jtextfield wait, until an user log in something. To latter on execute the Integer.Parseint ?

I can no change JtextField by another method cuz I'm working with GUI (Graphic User Environment.)


Answer:

You may try adding Button and then perform it's ActionListener and then enter the input and pressing the button will load the code of doing the stuff you want.

Question:

I'm attempting to make an application for a small game, and I'm currently having an issue of getting my code to work. It should be displaying a window with a text field, a jbutton, and an uneditable text field. I need to get it to read what I put into the first text field. However when I run it all I receive is this:

Exception in thread "main" java.lang.NumberFormatException: For input
string: "Enter Command"

at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1222)
at java.lang.Double.parseDouble(Double.java:510)
at TextAdv.<init>(TextAdv.java:16)
at TextAdv.main(TextAdv.java:43)

I'm not exactly great at reading errors and I've been trying to figure this out for an hour or so. If someone could please help me fix this issue, it would be greatly appreciated. Thank you.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class TextAdv {

    JFrame jtfMainFrame;
    JButton jbnButton2;
    JTextField jtfInput, jtfCommand;
    JPanel jplPanel, jplPanel2;
    public TextAdv() {
        jtfMainFrame = new JFrame("TextAdv");
        jbnButton2 = new JButton("Quit (LEAVES GAME)");
        jtfInput = new JTextField(55);
        jtfCommand = new JTextField("Enter Command", 40);
        double command = Double.parseDouble(jtfCommand.getText());
        jplPanel = new JPanel();
        jplPanel2 = new JPanel();
        jbnButton2.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });

        jtfInput.setEditable(false);
        jplPanel.setLayout(new FlowLayout());
        jplPanel.add(jtfCommand);
        jplPanel.add(jbnButton2);
        jplPanel2.add(jtfInput);
        jtfMainFrame.getContentPane().add(jplPanel2, BorderLayout.SOUTH);
        jtfMainFrame.getContentPane().add(jplPanel, BorderLayout.CENTER);
        jtfMainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jtfMainFrame.pack();
        jtfMainFrame.setVisible(true);
    }

    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel(UIManager
                    .getCrossPlatformLookAndFeelClassName());
        } catch (Exception e) {
        }
        TextAdv application = new TextAdv();
    }
}

Answer:

You are trying to parse value of the jtfCommand field which is "Enter Command":

double command = Double.parseDouble(jtfCommand.getText());

This line throws NumberFormatException if jtfCommand.getText() returns a String that is not a number.

You should be aware that the following line of code creates JTextField instance with the text value initialized to the first argument (Source Code ):

jtfCommand = new JTextField("Enter Command", 40);

And when you are calling jtfCommand.getText() it returns "Enter Command" that is obviously not a number.

Question:

How can I limit a value (int) into a jtextfield in Java? Without Jbutton or something like that, I want do this in the input of the textfield. I have tried use evt.getkeychar but this gives me only the value of a single character.


Answer:

You can add key listener to the JTextField and override the keyreleased method. In the method, check if the there are non-digit characters in the text, if there are, get rid of them.

public class LimitInputValue {
    public static void main(String[] args) {
        JFrame jframe = new JFrame();

        final JTextField jTextField = new JTextField();

        jframe.add(jTextField);
        jframe.pack();
        jframe.setVisible(true);

        jTextField.addKeyListener(new KeyAdapter() {
            @Override
            public void keyReleased(KeyEvent e) {
                String value = jTextField.getText();
                if (value == null || value.isEmpty()) return;
                String newValue = "";
                for (int i = 0; i < value.length(); ++i) {
                    if (Character.isDigit(value.charAt(i))) {
                        newValue += value.charAt(i);

                    }
                }
                jTextField.setText(newValue);
            }
        });
    }
}