Hot questions for Using JTextField in awt

Question:

Looks like option up can be caught only with AWT (i.e., adding key listener). Is there a way to do it without having to mess around with AWT?


Answer:

The Mac OS X UI delegate for JTextField does not bind alt↑ to any Action. You are free to bind the combination to any action you choose. As shown in How to Use Key Bindings, the example below binds alt↑ to the existing "caret-begin-line" defined for JTextField, which moves the caret to the beginning of the line.

final JTextField jtf = new JTextField("Test");
jtf.getInputMap().put(
    KeyStroke.getKeyStroke(KeyEvent.VK_UP, KeyEvent.ALT_MASK),
    "caret-begin-line");

More examples may be found here. As shown in the key binding utility cited here, JTextField binds the following WHEN_FOCUSED actions by name to the indicated key(s).

beep
caret-backward                LEFT, KP_LEFT, ctrl B
caret-begin                   ctrl P, meta UP, meta KP_UP, HOME
caret-begin-line              KP_UP, ctrl A, UP, meta KP_LEFT, meta LEFT
caret-begin-paragraph
caret-begin-word
caret-down
caret-end                     ctrl N, END, meta KP_DOWN, ctrl V, meta DOWN
caret-end-line                DOWN, meta KP_RIGHT, ctrl E, meta RIGHT, KP_DOWN
caret-end-paragraph
caret-end-word
caret-forward                 RIGHT, ctrl F, KP_RIGHT
caret-next-word               alt KP_RIGHT, alt RIGHT
caret-previous-word           alt KP_LEFT, alt LEFT
caret-up
copy
copy-to-clipboard             meta C, COPY
cut
cut-to-clipboard              CUT, meta X
default-typed
delete-next                   DELETE, ctrl D
delete-next-word              alt DELETE
delete-previous               BACK_SPACE, ctrl H
delete-previous-word          alt BACK_SPACE, ctrl W
dump-model
insert-break
insert-content
insert-tab
notify-field-accept           ENTER
page-down
page-up
paste
paste-from-clipboard          meta V, PASTE
requestFocus
select-all                    meta A
select-line
select-paragraph
select-word
selection-backward            shift LEFT, shift KP_LEFT
selection-begin               shift meta KP_UP, shift meta UP, shift HOME
selection-begin-line          shift UP, shift meta KP_LEFT, shift KP_UP, shift meta LEFT
selection-begin-paragraph
selection-begin-word
selection-down
selection-end                 shift meta DOWN, shift meta KP_DOWN, shift END
selection-end-line            shift meta KP_RIGHT, shift DOWN, shift KP_DOWN, shift meta RIGHT
selection-end-paragraph
selection-end-word
selection-forward             shift KP_RIGHT, shift RIGHT
selection-next-word           shift alt KP_RIGHT, shift alt RIGHT
selection-page-down           shift PAGE_DOWN
selection-page-left           shift meta PAGE_UP
selection-page-right          shift meta PAGE_DOWN
selection-page-up             shift PAGE_UP
selection-previous-word       shift alt LEFT, shift alt KP_LEFT
selection-up
set-read-only
set-writable
toggle-componentOrientation   shift ctrl O
unselect                      meta BACK_SLASH

Question:

I have a JLabel with the text "Enter mouse" on it. As soon as the user enters the mouse on it I'd like a JTextField to be appeared so the user can search some things. If the mouse is removed then the previous JLabel has to appear again. I use:

import java.awt.CardLayout;

import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

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

public class ML extends JFrame {
    private static final long serialVersionUID = 1L;

    public ML() {
        GridLayout gl = new GridLayout(1, 2);
        setLayout(gl);

        JPanel jp = new JPanel();
        CardLayout cl = new CardLayout();
        jp.setLayout(cl);

        JPanel jp1 = new JPanel();
        JLabel jl = new JLabel("Enter mouse!");
        jp1.add(jl);

        JPanel jp2 = new JPanel();
        JTextField jtf = new JTextField(20);
        jp2.add(jtf);

        jp.add(jp1, "1");
        jp.add(jp2, "2");
        cl.show(jp, "1");


        jp.addMouseListener(new MouseAdapter()
        {
            public void mouseEntered(MouseEvent evt)
            {
                cl.show(jp, "2");
            }
            public void mouseExited(MouseEvent evt)
            {
                cl.show(jp, "1");
            }
        });

        add(jp);

        this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        this.pack();
        this.setVisible(true);

     }


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

Everything is working just fine but when I hover over JLabel "Enter mouse", it somewhat bugs/blinks between this and the JTextField. Why is that so and what can I do to fix it? Ty


Answer:

Even if it didn't glitch, it wouldn't work because the textfield is larger than the label, and you only add the listener to the label. The glitch is caused because only the textfield is being shown, therefore it fires the mouseExited event on the label. To solve this you want the mouseEntered event only on the label, but the mouseExited event only on the textfield.

import java.awt.CardLayout;

import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

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

public class ML extends JFrame {
    private static final long serialVersionUID = 1L;

    public ML() {
        GridLayout gl = new GridLayout(1, 2);
        setLayout(gl);

        JPanel jp = new JPanel();
        CardLayout cl = new CardLayout();
        jp.setLayout(cl);

        JPanel jp1 = new JPanel();
        JLabel jl = new JLabel("Enter mouse!");
        jp1.add(jl);

        JPanel jp2 = new JPanel();
        JTextField jtf = new JTextField(20);
        jp2.add(jtf);

        jp.add(jp1, "1");
        jp.add(jp2, "2");
        cl.show(jp, "1");

        jl.addMouseListener(new MouseAdapter() {
            public void mouseEntered(MouseEvent evt) {
                cl.show(jp, "2");
            }
        });

        jtf.addMouseListener(new MouseAdapter() {
            public void mouseExited(MouseEvent evt) {
                cl.show(jp, "1");
            }
        });

        add(jp);

        this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        this.pack();
        this.setVisible(true);

    }

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

Question:

I'm just starting with Java and I need help please, I want to update my JtextField every 5 seconds, I searched something and I tried with thread.sleep(5000) but its not working (and i don't know why). Here is the code of my JtextField:

    textField_1 = new JTextField();
    textField_1.setText("0656");
    textField_1.setFont(new Font("Verdana", Font.PLAIN, 80));
    textField_1.setToolTipText("");
    textField_1.setHorizontalAlignment(SwingConstants.CENTER);
    textField_1.setBounds(212, 120, 600, 150);
    frame.getContentPane().add(textField_1);
    textField_1.setColumns(10);

Answer:

The easiest way to achieve this is using class Timer.

    Timer t = new Timer();
    t.schedule(new TimerTask() {
        @Override public void run() {
              // textField_t.setText(YOUR TEXT); 
        }
    }, 0L, 5000L);

Question:

I have a JLabel with some text and I would like as soon as the mouse is entered on it, a JTextField to be appeared on the place of the text so that the user can enter some text. If the mouse is not on it, it just displays its text as normal. I use:

JLabel jl = new JLabel("Enter mouse to make a search!")
jl.addMouseListener(new MouseAdapter()
{
     public void mouseEntered(MouseEvent evt)
     {
         JTextField textField = new JTextField(20);
         //????
     }

     public void mouseExited(MouseEvent evt)
     {
                 jl.setText("Enter mouse to make a search!");
     }
});

However, I am having some troubles on how to replace the jlabel with a jtextfield. How could I do that?


Answer:

Use a JPanel that uses a CardLayout to hold both the JLabel and the JTextField, and then swap them using the CardLayout's show(...) method, when desired. Don't forget to transfer the text from the JTextField to the JLabel in the mouseExited method.

For example:

import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

class SwapPanel extends JPanel {
    private static final int COLUMNS = 20;
    public static final String LABEL = "label";
    public static final String TEXT_FIELD = "text field";
    private JLabel label = new JLabel();
    private JTextField textField = new JTextField(COLUMNS);
    private CardLayout cardLayout = new CardLayout();

    public SwapPanel() {
        setLayout(cardLayout);
        add(label, LABEL);
        add(textField, TEXT_FIELD);

        MyMouse myMouse = new MyMouse();

        label.addMouseListener(myMouse);
        textField.addMouseListener(myMouse);
    }

    private class MyMouse extends MouseAdapter {
        @Override
        public void mouseEntered(MouseEvent e) {
            cardLayout.show(SwapPanel.this, TEXT_FIELD);
        }

        @Override
        public void mouseExited(MouseEvent e) {
            label.setText(textField.getText());
            cardLayout.show(SwapPanel.this, LABEL);
        }
    }
}

import javax.swing.*;

public class TestSwapPanel extends JPanel {
    private static final int GAP = 20;
    private SwapPanel swapPanel = new SwapPanel();

    public TestSwapPanel() {
        setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
        add(swapPanel);
    }

    private static void createAndShowGui() {
        TestSwapPanel mainPanel = new TestSwapPanel();

        JFrame frame = new JFrame("Swap Components");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

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

Or if you want to swap back to JLabel on pressing enter, and having the JTextField focused and all text selected on swapping:

import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

class SwapPanel2 extends JPanel {
    private static final long serialVersionUID = 1L;
    private static final int COLUMNS = 20;
    public static final String LABEL = "label";
    public static final String TEXT_FIELD = "text field";
    private JLabel label = new JLabel();
    private JTextField textField = new JTextField(COLUMNS);
    private CardLayout cardLayout = new CardLayout();

    public SwapPanel2() {
        setLayout(cardLayout);
        add(label, LABEL);
        add(textField, TEXT_FIELD);

        MyMouse myMouse = new MyMouse();

        label.addMouseListener(myMouse);
        textField.addMouseListener(myMouse);
        textField.addActionListener(myMouse);
    }

    public void showLabel() {
        label.setText(textField.getText());
        cardLayout.show(SwapPanel2.this, LABEL);
    }

    public void showTextField() {
        textField.selectAll();
        cardLayout.show(SwapPanel2.this, TEXT_FIELD);
        textField.requestFocusInWindow();
    }

    private class MyMouse extends MouseAdapter implements ActionListener {
        @Override
        public void mouseEntered(MouseEvent e) {
            showTextField();
        }

        @Override
        public void mouseExited(MouseEvent e) {
            showLabel();
        }

        @Override
        public void actionPerformed(ActionEvent arg0) {
            showLabel();
        }
    }
}

Question:

We have to make a program which is a little bit like excel. Now I have the problem, in that I want to make a field of 999 columns and 999 rows. I already tried to just at 999*999 JTextField controls but that obviously needs very long and I get an exception that there is no memory left. How could I make that better? Should I try to only render these text fields which are in use or is there a better method to make a table?

Here is my code:

tablePanel = new JPanel();
tablePanel.setLayout(new GridBagLayout());
tablePanel.setSize(100, 30);
tablePanel.setBorder(null);

JScrollPane tableScroll = new JScrollPane(tablePanel, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
//tableScroll.getVerticalScrollBar().setPreferredSize(new Dimension(0,0));
//tableScroll.getVerticalScrollBar().setUnitIncrement(25);
tableScroll.setBounds(0, 30, 30, this.getHeight());
table = new ArrayList<>();
for (int i = 0; i < 999; i++) {
    ArrayList<Component> column = new ArrayList<>();
    for (int j = 0; j < 999; j++) {
        JTextField field = new JTextField();
        field.setPreferredSize(new Dimension(100, 30));
        field.setBorder(null);
        field.setFocusCycleRoot(false);
        field.setFocusable(false);
        gbc.gridy = j;
        gbc.gridx = i;

        column.add(field);
        tablePanel.add(field, gbc);
    }
    table.add(column);
}

Answer:

You can create a javax.swing.JTable like this:

JTable table = new JTable(999,999); // creates a 999*999 table
TableCellEditor tce = table.getCellEditor();
// use tce to follow user

and use tce to follow what the user is doing with what cell.

For a more in-depth tutorial about javax.swing.JTables, see How to Use Tables

Question:

I want to add Capslock label to the status JtextField. Status has got line and column values. I want to add capslock with line and column. I have tried adding updateStatus() method, but it does not work as expected.

Sample code:

public class CapsLock extends javax.swing.JFrame {
    JTextField status;
    int i=0;
    JTextArea textArea;
    JLabel capsLock;
    public CapsLock() {
        initComponents();
        status=new JTextField();
        capsLock=new JLabel();
        updateStatus(1,1);
    }
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        tabbedPane = new javax.swing.JTabbedPane();
        jMenuBar1 = new javax.swing.JMenuBar();
        file = new javax.swing.JMenu();
        newFile = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        file.setText("File");

        newFile.setText("NewFile");
        newFile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newFileActionPerformed(evt);
            }
        });
        file.add(newFile);

        jMenuBar1.add(file);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(tabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 279, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(tabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 279, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        
    private void updateStatus(int linenumber, int columnnumber) {
        status.setText("ln: " + linenumber + " Col: " + columnnumber);
     }
    private void newFileActionPerformed(java.awt.event.ActionEvent evt) {                                        
        final JInternalFrame internalFrame = new JInternalFrame("");
        i++;
        internalFrame.setName("Doc "+i);
        internalFrame.setClosable(true);
        internalFrame.setAutoscrolls(true);
        textArea=new JTextArea();
        textArea.addKeyListener(new KeyListener() {
            @Override
            public void keyTyped(KeyEvent ke) {
            }

            @Override
            public void keyPressed(KeyEvent ke) {
              if(Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_CAPS_LOCK)){
                   capsLock.setText("ON");
              }
              else{
                    capsLock.setText("OFF");
                    status.setText(capsLock.getText());
              }  
            }
            @Override
            public void keyReleased(KeyEvent ke) {
            }
        });
        textArea.addCaretListener(new CaretListener() {
        @Override
        public void caretUpdate(CaretEvent e) {
              JTextArea editArea = (JTextArea)e.getSource();
              int linenum = 1;
              int columnnum = 1;
               try {
                    int caretpos = editArea.getCaretPosition();
                    linenum = editArea.getLineOfOffset(caretpos);
                    columnnum = caretpos - editArea.getLineStartOffset(linenum);
                    linenum += 1;
                }
                catch(Exception ex) { }
                updateStatus(linenum, columnnum);
            }
        });

        status.setBackground(Color.LIGHT_GRAY);
        status.setEditable(false);
        internalFrame.add(textArea);
        internalFrame.add(status,BorderLayout.SOUTH);
        tabbedPane.add(internalFrame);
    }                                       

    public static void main(String args[]) {
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(CapsLock.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(CapsLock.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(CapsLock.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(CapsLock.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }

        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new CapsLock().setVisible(true);
            }
        });
    }

    private javax.swing.JMenu file;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem newFile;
    private javax.swing.JTabbedPane tabbedPane;                
}

I write StatusPanel class as shown below:

public class StatusPanel extends JPanel{

InternalFrame currentFrame;
private JLabel statusLabel;
JLabel capsLabel;
public StatusPanel(){
    statusLabel=new JLabel();
    capsLabel=new JLabel();
    add(statusLabel);
    add(capsLabel);
    updateStatus(1,1);
}
public void setRowColumn(){
    currentFrame.textPane.addCaretListener(new CaretListener() {
        private KeyEvent KeyEvent;
        @Override
        public void caretUpdate(CaretEvent e) {

            int linenum = 1;
            int columnnum = 1;
            try {
                int caretpos = currentFrame.textPane.getCaretPosition();
                linenum=currentFrame.getLineAtCaret()-1;
                columnnum=currentFrame.getColumnAtCaret();
                linenum += 1;
            }
            catch(Exception ex) { }
            updateStatus(linenum, columnnum);
        }
    });      
}
private void updateStatus(int linenumber, int columnnumber) 
{
    statusLabel.setText("Line: " + linenumber +"  "+ " Column: " + columnnumber);
}
public void setCapslock(){
    currentFrame.textPane.addKeyListener(new KeyListener() {
        @Override
        public void keyTyped(KeyEvent ke) {
            //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void keyPressed(KeyEvent ke) {
            if(Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_CAPS_LOCK)){
               capsLabel.setText("    CAPS ON");
    }
            else{
                capsLabel.setText("    CAPS OFF");
            }
        }

        @Override
        public void keyReleased(KeyEvent ke) {
            //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }
    }); 
}
}

Answer:

  1. In the "if" code you have a single statement. In the "else" statement you have 2 statements. Don't you think the code should be the same except for the text?

  2. Also, you should NOT be using a text field to display the text. Instead you should be using a panel with multiple labels. One label for the row/column position. Another label for the Caps Lock status. Then you only update the text for the label that changes.

.Caps lock enable/disable not update the all the opened Documents.

Then you have a couple of solutions:

  1. Your status bar should be common for the frame, not the Document. So the labels will be shared by all Documents. This means that whenever a Document gains focus you would need to update the caret position but the Caps Lock will still be correct from the last Document.

  2. Or, you could create the Caps Lock field as a non-editable JTextField. Then you can share the Document of the text field with all text field. This mean when you update the text field it will be reflected on all documents.

So you would need to pass in the shared text field Document any time you create a new document for your application. Then to create the text field you would use:

JTextField textField = new JTextField( sharedDocument );

Edit:

When you create the component for the frame you would have code something like:

StatusPanel status = new StatusPanel();
frame.add(status, ...);

Then in this custom class you add the components to display the data you want displayed. You also need to add methods like setRowColumn(...) and setCapsLock(...) to display the text you want to see for those components.

Then you need to create another custom class MyInternalFrame that extend JInternalFrame. Then when you create this class you use:

MyInternalFrame internal = new MyInternalFrame(status);

So now your custom internal frame has access to the status bar and you can update the status bar from any Document that your create.

Another Edit:

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

public class Status extends JPanel
{
    public Status()
    {
        setLayout( new BorderLayout() );

        StatusPanel status = new StatusPanel();
        add(status, BorderLayout.SOUTH);

        DocumentPanel document = new DocumentPanel( status );
        add(document, BorderLayout.CENTER);
    }

    class StatusPanel extends JPanel
    {
        JLabel caretStatus = new JLabel("Caret Offset: 0");

        public StatusPanel()
        {
            add( caretStatus );
        }

        public void updateCaretStatus(String status)
        {
            caretStatus.setText( status );
        }
    }

    class DocumentPanel extends JPanel
    {
        private StatusPanel status;
        private JTextArea textArea;

        public DocumentPanel(StatusPanel statusPanel)
        {
            status = statusPanel;

            textArea = new JTextArea(5, 30);
            add( new JScrollPane( textArea ) );

            textArea.addCaretListener( new CaretListener()
            {
                @Override
                public void caretUpdate(CaretEvent e)
                {
                    status.updateCaretStatus( "Caret Offset: " + textArea.getCaretPosition() );
                }
            });
        }
    }

    private static void createAndShowGUI()
    {
        JFrame frame = new JFrame("Status");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add( new Status() );
        frame.setLocationByPlatform( true );
        frame.pack();
        frame.setVisible( true );
    }

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

Question:

I am having some questions regarding JTextField.

  1. Which event has replaced TextChanged Event for JTextField in NetBeans?
  2. When Value in a textField is changed I want its sum to be done and added to Total Fee . For same I'm using this code but its not working.

Code:

private void TutionFeesKeyTyped(java.awt.event.KeyEvent evt) {
   TotalFee.setText(""+Integer.parseInt(TutionFees.getText())+
     Integer.parseInt(LibraryFees.getText())+Integer.parseInt(UDFees.getText())+
     Integer.parseInt(USFees.getText())+Integer.parseInt(OtherFees.getText())+
     Integer.parseInt(SecurityFees.getText())) ;   
     // TODO add your handling code here:
}

Basically I am using:

Integer.parseInt()

To convert text into numerical data so I can add them ..

I am using KeyTyped event , but however its not allowing anything to enter in text field instead.


Answer:

Never use a KeyListener for this sort of thing as it can mess up the basic function of the JTextField. To listen for changes in the JTextField's content as it's being entered, consider instead adding a DocumentListener to the JTextField's Document.

And if you need to restrict the input to numeric or use any other type of restriction, set the Document's filter via a DocumentFilter (remember to cast it to a PlainDocument first), or use a JFormattedTextField, or use (my favorite) a JSpinner.

e.g.,

Document doc = myTextField.getDocument();
doc.addDocumentListener(new DocumentListener() {

        void insertUpdate(DocumentEvent e) {
            // ... code to check document change here
        }

        void removeUpdate(DocumentEvent e){
            // ... code to check document change here
        }

        void changedUpdate(DocumentEvent e){
            // ... code to check document change here
        }

});

For example, use of a DocumentListener and a DocumentFilter together, the first to add numbers, the second to be sure that only numbers are entered.

Edited now to handle 15 JTextFields:

import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.DocumentFilter;
import javax.swing.text.PlainDocument;

@SuppressWarnings("serial")
public class DocListenerEg extends JPanel {
   private static final int FIELD_COUNT = 15;
   private static final int COLS = 6;
   private List<JTextField> fieldList = new ArrayList<>();
   private JTextField sumField = new JTextField(COLS);

   public DocListenerEg() {
      sumField.setFocusable(false);

      DocListener docListener = new DocListener();
      DocFilter docFilter = new DocFilter();
      for (int i = 0; i < FIELD_COUNT; i++) {
         JTextField textField = new JTextField(COLS);
         Document doc = textField.getDocument();
         doc.addDocumentListener(docListener);
         ((PlainDocument) doc).setDocumentFilter(docFilter);
         add(textField);
         fieldList.add(textField);
         String labelText = i < (FIELD_COUNT - 1) ? "+" : "=";
         add(new JLabel(labelText));
      }
      add(sumField);
   }

   private class DocFilter extends DocumentFilter {
      private boolean checkIfIntegerOrEmpty(String text) {
         if (text.isEmpty()) {
            return true;
         } else {
            try {
               Integer.parseInt(text);
               return true;
            } catch (NumberFormatException e) {
            }
         }
         return false;
      }

      @Override
      public void insertString(FilterBypass fb, int offset, String string,
            AttributeSet attr) throws BadLocationException {
         Document doc = fb.getDocument();
         String preText = doc.getText(0, doc.getLength());

         StringBuilder sb = new StringBuilder(preText);
         sb.insert(offset, string);

         if (checkIfIntegerOrEmpty(sb.toString())) {
            super.insertString(fb, offset, string, attr);
         }

      }

      @Override
      public void remove(FilterBypass fb, int offset, int length)
            throws BadLocationException {
         Document doc = fb.getDocument();
         String preText = doc.getText(0, doc.getLength());

         StringBuilder sb = new StringBuilder(preText);
         int end = offset + length;
         sb.replace(offset, end, "");

         if (checkIfIntegerOrEmpty(sb.toString())) {            
            super.remove(fb, offset, length);
         }
      }

      @Override
      public void replace(FilterBypass fb, int offset, int length, String text,
            AttributeSet attrs) throws BadLocationException {
         Document doc = fb.getDocument();
         String preText = doc.getText(0, doc.getLength());

         StringBuilder sb = new StringBuilder(preText);
         int end = offset + length;
         sb.replace(offset, end, text);

         if (checkIfIntegerOrEmpty(sb.toString())) {            
            super.replace(fb, offset, length, text, attrs);
         }
      }
   }

   private class DocListener implements DocumentListener {

      private void textChanged() {
         int sum = 0;
         for (JTextField jTextField : fieldList) {
            String text = jTextField.getText().trim();
            if (!text.isEmpty()) {
               sum += Integer.parseInt(text);
            }
         }
         sumField.setText(String.valueOf(sum));
      }

      @Override
      public void insertUpdate(DocumentEvent e) {
         textChanged();
      }

      @Override
      public void removeUpdate(DocumentEvent e) {
         textChanged();
      }

      @Override
      public void changedUpdate(DocumentEvent e) {
         textChanged();
      }

   }

   private static void createAndShowGui() {
      DocListenerEg mainPanel = new DocListenerEg();

      JFrame frame = new JFrame("DocListenerEg");
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

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

Edit: You state in comment,

Read whole code, much informative , however way too big if i want to implement for more then 30 textfields .. I have solved the problem , now pasting the solution.

OK, so this new code below adds numbers from 100 JTextFields, again with minimal change to original code. To see which solution works best, to see which solution scales best, try to change your current solution to handle something similar:

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.util.ArrayList;
import java.util.List;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.DocumentFilter;
import javax.swing.text.PlainDocument;

@SuppressWarnings("serial")
public class DocListenerEg extends JPanel {
   private static final int COLS = 6;
   private static final int GAP = 5;
   private static final int SIDE = 10;
   private List<JTextField> fieldList = new ArrayList<>();
   private JTextField sumField = new JTextField(COLS);

   public DocListenerEg() {
      sumField.setFocusable(false);

      JPanel additionFieldPanel = new JPanel(new GridLayout(SIDE, SIDE, GAP, GAP));
      additionFieldPanel.setBorder(BorderFactory.createTitledBorder("Numbers To Add"));

      DocListener docListener = new DocListener();
      DocFilter docFilter = new DocFilter();
      for (int i = 0; i < SIDE * SIDE; i++) {
         JTextField textField = new JTextField(COLS);
         Document doc = textField.getDocument();
         doc.addDocumentListener(docListener);
         ((PlainDocument) doc).setDocumentFilter(docFilter);
         fieldList.add(textField);
         additionFieldPanel.add(textField);
      }

      JPanel sumPanel = new JPanel();
      sumPanel.add(new JLabel("Sum Of All Numbers:"));
      sumPanel.add(sumField);

      setLayout(new BorderLayout());
      add(additionFieldPanel, BorderLayout.CENTER);
      add(sumPanel, BorderLayout.PAGE_END);
   }

   private class DocFilter extends DocumentFilter {
      private boolean checkIfIntegerOrEmpty(String text) {
         if (text.isEmpty()) {
            return true;
         } else {
            try {
               Integer.parseInt(text);
               return true;
            } catch (NumberFormatException e) {
            }
         }
         return false;
      }

      @Override
      public void insertString(FilterBypass fb, int offset, String string,
            AttributeSet attr) throws BadLocationException {
         Document doc = fb.getDocument();
         String preText = doc.getText(0, doc.getLength());

         StringBuilder sb = new StringBuilder(preText);
         sb.insert(offset, string);

         if (checkIfIntegerOrEmpty(sb.toString())) {
            super.insertString(fb, offset, string, attr);
         }

      }

      @Override
      public void remove(FilterBypass fb, int offset, int length)
            throws BadLocationException {
         Document doc = fb.getDocument();
         String preText = doc.getText(0, doc.getLength());

         StringBuilder sb = new StringBuilder(preText);
         int end = offset + length;
         sb.replace(offset, end, "");

         if (checkIfIntegerOrEmpty(sb.toString())) {            
            super.remove(fb, offset, length);
         }
      }

      @Override
      public void replace(FilterBypass fb, int offset, int length, String text,
            AttributeSet attrs) throws BadLocationException {
         Document doc = fb.getDocument();
         String preText = doc.getText(0, doc.getLength());

         StringBuilder sb = new StringBuilder(preText);
         int end = offset + length;
         sb.replace(offset, end, text);

         if (checkIfIntegerOrEmpty(sb.toString())) {            
            super.replace(fb, offset, length, text, attrs);
         }
      }
   }

   private class DocListener implements DocumentListener {

      private void textChanged() {
         int sum = 0;
         for (JTextField jTextField : fieldList) {
            String text = jTextField.getText().trim();
            if (!text.isEmpty()) {
               System.out.println(text);
               sum += Integer.parseInt(text);
            }
         }
         sumField.setText(String.valueOf(sum));
      }

      @Override
      public void insertUpdate(DocumentEvent e) {
         textChanged();
      }

      @Override
      public void removeUpdate(DocumentEvent e) {
         textChanged();
      }

      @Override
      public void changedUpdate(DocumentEvent e) {
         textChanged();
      }

   }

   private static void createAndShowGui() {
      DocListenerEg mainPanel = new DocListenerEg();

      JFrame frame = new JFrame("DocListenerEg");
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

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

Question:

my program suppose to ask a user to write a number in JTextField. Then, show the result if the number is negative or positive in another JTextField that should be not enabled. All of that must be done without a button.

import java.awt.*; 

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

public class PositiveOrNegative extends JFrame {

JLabel l1, l2 ;
JTextField t1, t2 ;

public PositiveOrNegative() 
{
    FlowLayout layout = new FlowLayout(); 

    this.setLayout(layout); 

    l1 = new JLabel("Enter a number "); 
    t1 = new JTextField(10) ;
    l2 = new JLabel("The number is  ");
    t2 = new JTextField(10) ;

    this.add(l1); 
    this.add(t1);
    this.add(l2);
    this.add(t2);
    t2.enable(false);
    t2.setBackground(Color.PINK);
}
public void JavaJTextFieldActionListner() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    t1.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            String n = t1.getText() ;
            int number = Integer.parseInt(n) ;

            if (number >= 0)
                t2.setText("POSITIVE") ;
            else
                t2.setText("NEGATIVE") ;
        }
    });

}

public static void main(String[] args) { 
    PositiveOrNegative p = new PositiveOrNegative(); 
    p.setTitle("AWT SIGN"); 
    p.setBounds(300, 300, 300, 120); 
    p.setVisible(true); 
} 

}


Answer:

In your example you've forget to call the method JavaJTextFieldActionListner. I've remove it and move the code into constructor. Also I've added handling of a wrong input. Here is the result:

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

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

public class PositiveOrNegative extends JFrame {

    JLabel l1, l2 ;
    JTextField t1, t2 ;

    public PositiveOrNegative() {
        FlowLayout layout = new FlowLayout(); 

        this.setLayout(layout); 

        l1 = new JLabel("Enter a number "); 
        t1 = new JTextField(10);
        l2 = new JLabel("The number is  ");
        t2 = new JTextField(10);

        this.add(l1); 
        this.add(t1);
        this.add(l2);
        this.add(t2);
        t2.setEditable(false);
        t2.setBackground(Color.PINK);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        t1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String n = t1.getText();
                try {
                    int number = Integer.parseInt(n);

                    if (number >= 0)
                        t2.setText("POSITIVE");
                    else
                        t2.setText("NEGATIVE");
                } catch (Exception ex) {
                    t2.setText("Not an integer");
                }
            }
        });
    }

    public static void main(String[] args) { 
        PositiveOrNegative p = new PositiveOrNegative(); 
        p.setTitle("AWT SIGN"); 
        p.setBounds(300, 300, 300, 120); 
        p.setVisible(true); 
    } 

}

Question:

I am attempting to create a GUI for a text based adventure game I am working on. Something I need to have it do, is that when the button "jButton3" is clicked, it will remove the text of "jText1". I tried adding a ItemListener, but i cannot seem to figure it out. The code is below. For simplicity sake i have left out all of my Imports, as well as my package name, just know that nothing errors out when I attempt to run this program.

I have searched on other posts related to my topic, and could not find exactly what I was looking for, most of them are about replacing the text from the TextField to the JLabel

public class DemoGUI extends javax.swing.JFrame {
    public JLabel jLabel1;
    public JTextField jText1;
    public JButton jButton1;
    public JButton jButton2;
    public JButton jButton3;
    String string1;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                DemoGUI inst = new DemoGUI();
                inst.setLocationRelativeTo(null);
                inst.setVisible(true);
            }
        });
    }
    public DemoGUI() {
        super();
        initGUI();
    }
    private void removeTextWhenClicked(JButton btn, ItemEvent ev) {
        if(ev.getStateChange() == ItemEvent.ITEM_STATE_CHANGED) {
            jText1.setText("");
        }
    }

    public void initGUI() {
        try {
            FlowLayout thisLayout = new FlowLayout();
            getContentPane().setLayout(thisLayout);
            setDefaultCloseOperation(EXIT_ON_CLOSE);

                jLabel1 = new JLabel("Center", SwingConstants.CENTER);
                getContentPane().add(jLabel1);
                jLabel1.setPreferredSize(new Dimension(320, 250));
                jLabel1.setText(string1);
                jLabel1.setBorder(BorderFactory.createLineBorder(Color.BLACK));

                jButton1 = new JButton();
                getContentPane().add(jButton1);
                jButton1.setPreferredSize(new Dimension(100, 50));
                jButton1.setText("Map");

                jButton2 = new JButton();
                getContentPane().add(jButton2);
                jButton2.setPreferredSize(new Dimension(100, 50));
                jButton2.setText("Inventory");

                jText1 = new JTextField();
                getContentPane().add(jText1);
                jText1.setPreferredSize(new Dimension(320, 100));
                jText1.setBorder(BorderFactory.createLineBorder(Color.BLACK));

                jButton3 = new JButton();
                getContentPane().add(jButton3);
                jButton3.setPreferredSize(new Dimension(100, 40));
                jButton3.setText("Submit");
                jButton3.addItemListener(ev -> removeTextWhenClicked(jButton3, ev));

            pack();
            this.setSize(350, 500);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

Answer:

Instead of using addItemListener, use addActionListener

 jButton3.addActionListener(new ActionListener(){  
    public void actionPerformed(ActionEvent e){  

        }  
    });  

You can find the difference at Java: What's the difference between ActionEvent and ItemEvent on a JRadioButton?

ItemListeners are notified when ever the state of the button is changed, whether through a user interacting with the button or programmatically (via the setSelected method).

ActionListeners will be called when a user interacts with the button

Question:

public class AddMult extends JFrame {
    public AddMult() {
    setSize(600, 600);

    txtEnterNum = new JTextField();
    txtEnterNum.setSize(100,50);
    lblEnterNum.setLocation(100, 150);
    add(txtEnterNum);
    txtEnterNum.setVisible(true);


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

} I tried to create a form and a JTextField on it. But the problem is, my location and size doesn't work. The TextField is filling the whole form. How can I fix it?


Answer:

The size is not "working" due to the default layout (FlowLayout) in your JFrame. This layout doesn't let you change the size or location of any object. Try to use your own layout (modify x and y values in order to modify the size and location of your components):

setLayout(new LayoutManager() {
        @Override
        public void addLayoutComponent(String name, Component comp) {



        }

        @Override
        public void removeLayoutComponent(Component comp) {

        }

        @Override
        public Dimension preferredLayoutSize(Container parent) {
            return null;
        }

        @Override
        public Dimension minimumLayoutSize(Container parent) {
            return null;
        }

        @Override
        public void layoutContainer(Container parent) {

        public void layoutContainer(Container parent) {

            float modifierx = Toolkit.getDefaultToolkit().getScreenSize().width/100;

            float Sizemodifier = Toolkit.getDefaultToolkit().getScreenSize().height/50;

            float modifiery = Toolkit.getDefaultToolkit().getScreenSize().height/150;

            int x=(int)(Toolkit.getDefaultToolkit().getScreenSize().width/modifierx);

            int y=(int)(Toolkit.getDefaultToolkit().getScreenSize().height/modifiery);

            int height =(int)(Toolkit.getDefaultToolkit().getScreenSize().height/Sizemodifier);

            int DX =(int)(Toolkit.getDefaultToolkit().getScreenSize().width/modifierx);

            int DY =(int)(Toolkit.getDefaultToolkit().getScreenSize().height/modifiery);

            for(int i = 0; i<parent.getComponentCount();i++){

                if(i%2==0){

                    parent.getComponent(i).setBounds(x,y,x,height);

                    x+= DX;

                }else{

                    parent.getComponent(i).setBounds(x,y,x,height);

                    x=Toolkit.getDefaultToolkit().getScreenSize().width/100;

                    y+=DY;

                }

            }
        }


    });

You have to set the layout in the constructor of the JFrame:

frame() {

    setSize(600, 600);
    setLayout(new LayoutManager() {...}

    txtEnterNum = new JTextField();
    txtEnterNum.setSize(100, 50);
    setLocation(100, 150);
    add(txtEnterNum);
    txtEnterNum.setVisible(true);


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