Hot questions for Using JTextField in settext

Question:

I want to figure out a way to set the text for multiple JTextfields in just a few lines (preferable one line) of code rather than a new line for every textfield.

I am looking for a way to invoke the setText method on multiple JTextfield values. My code works correctly, but I do not want to write out someField.setText("0.00"); for each JTextfield.

Here is code with the repeated calls that I want to shorten:

JButton btnNewButton_1 = new JButton("Clear");
    btnNewButton_1.setBounds(367, 533, 86, 32);
    btnNewButton_1.setFont(new Font("Tahoma", Font.PLAIN, 11));
    btnNewButton_1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            textIncome.setText("0.00");
            textGrossSalary.setText("0.00");
            textGrossSalary.setText("0.00");
            textHousehold.setText("0.00");
            textFood.setText("0.00");
            textChildren.setText("0.00");
            textBills.setText("0.00");
            textIncidentals.setText("0.00");
            textCredit.setText("0.00");
            textHome.setText("0.00");
            textInvestings.setText("0.00");
            textPets.setText("0.00");
            textTransport.setText("0.00");
            textLifestyle.setText("0.00");
            textTax.setText("0.00");
            textDisposable.setText("0.00");
            textHealthFitness.setText("0.00");
            textGiftsDonations.setText("0.00");

        }

    });

Answer:

Put them in a List or an array and iterate over them

For example, create an instance field array which contains the fields which you want to set (to the same value)

private JTextField fields[] = new JTextField[]{
        textIncome,
        textGrossSalary,
        textGrossSalary,
        textHousehold,
        textFood,
        textChildren,
        textBills,
        textIncidentals,
        textCredit,
        textHome,
        textInvestings,
        textPets,
        textTransport,
        textLifestyle,
        textTax,
        textDisposable,
        textHealthFitness,
        textGiftsDonations};

Then when the ActionListener is triggered, iterate over it...

btnNewButton_1.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        for (JTextField field : fields) {
            field.setText("0.00");
        }
    }
});

Based on btnNewButton_1.setBounds(367, 533, 86, 32);, I'd advise avoiding using null layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify

Question:

I am creating a game similar to the star wars game sabacc. I am trying to create a Jtextfield that has three card suites already on the screen. The user will press a button and depending on the button they press the card suit will change to a different suit. If they get three of the same suites they win. I am having trouble getting text onto the screen though. As of right now I keep getting an error saying non static method can not be referenced by a static content.

Here is my code for the main application :

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

public class CardApp extends JFrame implements ActionListener {

    private JButton oneButton, 
                    twoButton, 
                    threeButton;  
    private int width = 25;
    private int height = 15;



    public CardApp() {
        //JPanel boardPanel = new JPanel(new GridLayout(height,width));
        JPanel buttonPanel = new JPanel(new GridLayout(1, 3));
        JTextField TextField = new JTextField(30); 

        Hand settingTheText = new Hand();

        TextField.setText(settingTheText.ListOfCards());

        oneButton = new JButton("1");
        twoButton = new JButton("2");
        threeButton = new JButton("3");


        // Listen for events on each button
        oneButton.addActionListener(this);
        twoButton.addActionListener(this);
        threeButton.addActionListener(this);

        // Add each to the panel of buttons
        buttonPanel.add(oneButton); 
        buttonPanel.add(twoButton); 
        buttonPanel.add(threeButton); 
       // Add everything to a main panel attached to the content pane
        JPanel mainPanel = new JPanel(new BorderLayout());
        getContentPane().add(mainPanel);
        mainPanel.add(TextField, BorderLayout.CENTER);
        mainPanel.add(buttonPanel, BorderLayout.SOUTH);

        setTitle("Sabacc Example by Angela Rucci");
        setSize(375, 200);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }


    public void actionPerformed(ActionEvent e) {
                int pressed = 0;
                if (e.getSource() == oneButton){
                        pressed = 1;}
                if (e.getSource() == twoButton){
                        pressed = 2;}
                if (e.getSource() == threeButton){
                        pressed = 3;}
                 Hand handObject = new Hand();

///This IS WHERE IM GETTING MY ERROR!//

                String screenText = handObject.ListOfCards();
                TextField.setText(screenText);
    }


public static void main(String[] args) {

    CardApp c = new CardApp();


}

}

This is the other file where i am getting my list of suits

package cardapp;
import java.util.Random;
import javax.swing.JOptionPane;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Hand {
String [] Suits = {"C", "H", "S", "D"};
String [] probability = {"C","H","R","D"};
Random randomInt = new Random ();
String RandomSuit;
String RandomShuffle;
String ThreeSuits;
String LeftSuit;
String MiddleSuit;
String RightSuit;
int pressed = 0;



       public int Discards(int pressedNumber){

              return pressed;

             }



       public void Randomizer (){

           int RandomSuitNumber = randomInt.nextInt(4);//this is generator a random number

           //------------------Decide what hand to randomize --------------------------//
           if (pressed==1){
                  LeftSuit= Suits[RandomSuitNumber];
                  }

              if (pressed==2){
                 MiddleSuit=Suits[RandomSuitNumber];
                  }

              if (pressed==3){
                  RightSuit=Suits[RandomSuitNumber];
                    }
          //----------------20% chance of new random set------------------------------------//
            int ProabilityRandomNum = randomInt.nextInt(5);//this will create a random number for probability array
            RandomShuffle= probability[ProabilityRandomNum];//this will pick a random letter in proability array


          //------------If proability array equals R then change all of the suits----------//  
            if (RandomShuffle.equals("R")){
                JOptionPane.showMessageDialog(null, "Randomized Hand!");
                int leftNumber = randomInt.nextInt(4);
                int middleNumber = randomInt.nextInt(4);
                int rightNumber = randomInt.nextInt(4);
                LeftSuit= Suits[leftNumber];
                MiddleSuit= Suits[middleNumber];
                RightSuit= Suits[rightNumber];}

            ThreeSuits = (LeftSuit + MiddleSuit + RightSuit); 
       }


       public String ListOfCards (){
              return ThreeSuits;
             }




         public void GameOver(){
                  if (LeftSuit == MiddleSuit && MiddleSuit == RightSuit &&    


    RightSuit== LeftSuit){
                      JOptionPane.showMessageDialog(null, "WINNER!!");
                     }
             }
    }

Answer:

The variables are local to the method. the JTextField TextField is visible to the CardApp() only. if you want it to be available to the whole class, put it as a private class member :

public class CardApp extends JFrame implements ActionListener {

    private JButton oneButton, 
                    twoButton, 
                    threeButton;  
    private int width = 25;
    private private int height = 15;
    // available to all methods
    // better naming convention was JTextfield tf = new JTextField(30);
    // even stackoverflow thinks its a class name :)
    // see the color highlighting
    private JTextField TextField = new JTextField(30);

    public CardApp() {
        //JPanel boardPanel = new JPanel(new GridLayout(height,width));
        JPanel buttonPanel = new JPanel(new GridLayout(1, 3));
        //JTextField TextField = new JTextField(30); 

        Hand settingTheText = new Hand();

        TextField.setText(settingTheText.ListOfCards());
     }
     //
     // code continues here ...
     //
}

Question:

I want to update jlabel and jtextfield with setText() method but it is not working. However, rest of the code is working. The code is below;

btnDosyaSe.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                JFileChooser jfc = new JFileChooser();
                jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

                int kullaniciSecimi = jfc.showOpenDialog(null);
                if (kullaniciSecimi == JFileChooser.APPROVE_OPTION) {
                    File fileName = jfc.getSelectedFile();
                    textField.setText(fileName.getPath());
                    islemSureci.setText("Veriler Okunuyor...");

                    try {

                        ArrayList<ArrayList<String>> tumYazılar = rwd.readTXT(fileName.getPath());
                        String[] yazarlar = rwd.yazarlar(fileName.getPath());
                        islemSureci.setText("Veriler Okundu! Öznitelik çıkarımına başlandı...");

                        oznitelikler = oc.oznitelikleriBul(tumYazılar, yazarlar);
                        islemSureci.setText("Öznitelikler Çıkarılmıştır!");
                        //String text = readTXT(fileName);

                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        });

In here, islemSureci is JLabel and textFiled is JTextField. When they are set, it is not working. After all the work finish in the code, they appear. Please can you tell what is the reasons?


Answer:

Your long running task is executed in Event Dispatcher Thread which locks the thread where update should be performed. Thus the real update is perfomed only after the task is finished.

Run it in SwingWorker

See e.g.

http://www.javacreed.com/swing-worker-example/

or

How do I use SwingWorker in Java?

Question:

The Picture show the problem setting dialog. The dialog's first JTextfield works fine with setText(String t) method when change the first JComboBox selected Item, but the second JTextfield's setText(String t) method doesn't change the content of itself's when change the second JComboBox seleted item.

The source's code is attached below. The two JTextField are construct in the same way. But I don't know why the second one's setText(String) method doesn't work.

package ztio.gui.updateGUI;

import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.TitledBorder;



public class SimpleSettingDialog extends JDialog {
    private final int MAX_THRES_NUM = 10;
    private final int MAX_VALUE_THRES_NUM = 10;
    private JPanel dialogPane;
    private JComboBox testCaseCombo;
    private JComboBox testCaseItemCombo;
    private JComboBox[] judgeOperationComboArray = new JComboBox[MAX_THRES_NUM];
    private JComboBox[] thresTypeComboArray = new JComboBox[MAX_THRES_NUM];
    private String[] judgeOperationStrings;
    private String[] thresTypeStrings;
    private List<JButton> testBtnList;
    private JTextField showTargetChoice;
    private JTextField showTestCase;


    public SimpleSettingDialog(JFrame parent, boolean isModal) {
        // TODO Auto-generated constructor stub
        super(parent, isModal);
        String[] judges = {">", "<", "="};
        String[] types = {"int", "float", "string"};
        judgeOperationStrings = judges;
        thresTypeStrings = types;


        dialogPane = (JPanel) getContentPane();
        dialogPane.setLayout(new GridBagLayout());
        TitledBorder titled = BorderFactory.createTitledBorder("Config Thresholds");
        dialogPane.setBorder(titled);

        JPanel testCasePanel = createTestCasePanel();
         GridBagConstraints c = new GridBagConstraints();
         c.fill = GridBagConstraints.HORIZONTAL;
        c.ipady = 0;
        c.weightx = 1.0;
        c.weighty = 0.0;
        c.gridwidth = 1;
        c.gridx = 0;
        c.gridy = 0;
        dialogPane.add(testCasePanel, c);
        c.fill = GridBagConstraints.BOTH;
        c.ipady = 0;
        c.weightx = 1.0;
        c.weighty = 1.0;
        c.gridwidth = 1;
        c.gridx = 0;
        c.gridy = 1;

        JPanel testItemPanel = createTestCaseItemPanel();

        JPanel debug = new JPanel();
        dialogPane.add(debug, c);
    }

    private JPanel createThresListPanel() {
        JPanel thresListPanel = new JPanel();
        thresListPanel.setLayout(new BoxLayout(thresListPanel, BoxLayout.Y_AXIS));
        for(int i = 0; i < 2; ++i){
            JPanel thresPanel = createThresPanel(i);
            thresListPanel.add(thresPanel);
        }
        return thresListPanel;
    }

    private JPanel createThresPanel(int i) {
        // TODO Auto-generated method stub
        JPanel thresPanel = new JPanel(new GridBagLayout());
        TitledBorder titled = BorderFactory.createTitledBorder("The " + (((i+1)==1)?"1st":((i+1)==2?"2nd":((i+1==3?"3rd":((i+1)+"th"))))) + " Threshold" );
        thresPanel.setBorder(titled);
        JComboBox thresTypeCombo = new JComboBox(thresTypeStrings);
        thresTypeComboArray[i] = thresTypeCombo;
        thresTypeCombo.setSelectedItem("string");
        JComboBox judgeOperationCombo = new JComboBox(judgeOperationStrings);
        judgeOperationComboArray[i] = judgeOperationCombo;
        judgeOperationCombo.setSelectedItem("=");
        JLabel label1 = new JLabel("Threshold's type:");
        JLabel label2 = new JLabel("Judge Operation:");

        GridBagConstraints c = new GridBagConstraints();
        c.fill = GridBagConstraints.HORIZONTAL;
        c.ipady = 0;
        c.weightx = 0.0;
        c.gridwidth = 1;
        c.gridx = 0;
        c.gridy = 0;
        thresPanel.add(label1, c);

        c.fill = GridBagConstraints.HORIZONTAL;
        c.ipady = 0;
        c.weightx = 1.0;
        c.gridwidth = 1;
        c.gridx = 1;
        c.gridy = 0;
        thresPanel.add(thresTypeCombo, c);

        c.fill = GridBagConstraints.HORIZONTAL;
        c.ipady = 0;
        c.weightx = 0.0;
        c.gridwidth = 1;
        c.gridx = 0;
        c.gridy = 1;
        thresPanel.add(label2, c);

        c.fill = GridBagConstraints.HORIZONTAL;
        c.ipady = 0;
        c.weightx = 1.0;
        c.gridwidth = 1;
        c.gridx = 1;
        c.gridy = 1;
        thresPanel.add(judgeOperationCombo, c);

        return thresPanel;
    }

    private JPanel createTestCaseItemPanel() {
        // TODO Auto-generated method stub
        String[] testItemNameArray = {"volume", "brightness"};
        testCaseItemCombo = new JComboBox(testItemNameArray);

        testCaseItemCombo.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub
                JComboBox cb = (JComboBox)e.getSource();
                String caseItemName = (String)cb.getSelectedItem();
                String caseName = (String)testCaseCombo.getSelectedItem();
                String targetString = caseName + "->" + caseItemName;
                System.out.println(targetString);
                System.out.println("target text field: " + showTargetChoice.getText());
                showTargetChoice.setText(targetString);
            }
        });

        TitledBorder titled;

        titled = BorderFactory.createTitledBorder("Test Case Item");
        JPanel comp = new JPanel(new GridBagLayout());
        comp.setBorder(titled);

        JButton btnAddTestCaseItem = new JButton("ADD");
        btnAddTestCaseItem.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub

            }
        });

        JButton btnDelTestCaseItem = new JButton("DEL");
        btnDelTestCaseItem.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub

            }
        });



         GridBagConstraints c = new GridBagConstraints();
         c.fill = GridBagConstraints.HORIZONTAL;
        c.ipady = 0;
        c.weightx = 0.0;
        c.gridwidth = 1;
        c.gridx = 0;
        c.gridy = 0;
        comp.add(testCaseItemCombo, c);

        c.fill = GridBagConstraints.HORIZONTAL;
        c.ipady = 0;
        c.weightx = 0.0;
        c.gridwidth = 1;
        c.gridx = 1;
        c.gridy = 0;
        comp.add(btnAddTestCaseItem, c);

        c.fill = GridBagConstraints.HORIZONTAL;
        c.ipady = 0;
        c.weightx = 0.0;
        c.gridwidth = 1;
        c.gridx = 2;
        c.gridy = 0;
        comp.add(btnDelTestCaseItem, c);

        c.fill = GridBagConstraints.HORIZONTAL;
        c.ipady = 0;
        c.weightx = 1.0;
        c.gridwidth = 1;
        c.gridx = 3;
        c.gridy = 0;
        comp.add(new JPanel(), c);

        //Row 2
        JLabel labelRegexp = new JLabel("target string:");
        showTargetChoice = new JTextField();
        c.fill = GridBagConstraints.HORIZONTAL;
        c.ipady = 0;
        c.weightx = 0.0;
        c.gridwidth = 1;
        c.gridx = 0;
        c.gridy = 1;
        comp.add(labelRegexp, c);

        c.fill = GridBagConstraints.HORIZONTAL;
        c.ipady = 0;
        c.weightx = 0.0;
        c.gridwidth = 3;
        c.gridx = 1;
        c.gridy = 1;
        comp.add(showTargetChoice, c);

        JPanel thresListPanel = createThresListPanel();
        c.fill = GridBagConstraints.HORIZONTAL;
        c.ipady = 0;
        c.weightx = 0.0;
        c.gridwidth = 4;
        c.gridx = 0;
        c.gridy = 2;
        comp.add(thresListPanel, c);

        return comp;
    }

    private JPanel createTestCasePanel() {
        // TODO Auto-generated method stub
        String[] testCaseArray = {"Light", "Voice"};
        testCaseCombo = new JComboBox(testCaseArray);
        testCaseCombo.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub
                JComboBox cb = (JComboBox)e.getSource();
                String caseName = (String)cb.getSelectedItem();
                System.out.println(caseName);
                showTestCase.setText(caseName);
            }
        });
        TitledBorder titled;

        titled = BorderFactory.createTitledBorder("Test Case");
        JPanel comp = new JPanel(new GridBagLayout());
        comp.setBorder(titled);

        JButton btnAddTestCase = new JButton("ADD");
        btnAddTestCase.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub
            }
        });

        JButton btnDelTestCase = new JButton("DEL");
        btnDelTestCase.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub

            }
        });

         GridBagConstraints c = new GridBagConstraints();
         c.fill = GridBagConstraints.HORIZONTAL;
        c.ipady = 0;
        c.weightx = 0.0;
        c.gridwidth = 1;
        c.gridx = 0;
        c.gridy = 0;
        comp.add(testCaseCombo, c);

        c.fill = GridBagConstraints.HORIZONTAL;
        c.ipady = 0;
        c.weightx = 0.0;
        c.gridwidth = 1;
        c.gridx = 1;
        c.gridy = 0;
        comp.add(btnAddTestCase, c);

        c.fill = GridBagConstraints.HORIZONTAL;
        c.ipady = 0;
        c.weightx = 0.0;
        c.gridwidth = 1;
        c.gridx = 2;
        c.gridy = 0;
        comp.add(btnDelTestCase, c);

        c.fill = GridBagConstraints.HORIZONTAL;
        c.ipady = 0;
        c.weightx = 1.0;
        c.gridwidth = 1;
        c.gridx = 3;
        c.gridy = 0;
        comp.add(new JPanel(), c);

        JLabel label = new JLabel("selected test case:");
        showTestCase = new JTextField();
        c.fill = GridBagConstraints.HORIZONTAL;
        c.ipady = 0;
        c.weightx = 0.0;
        c.gridwidth = 1;
        c.gridx = 0;
        c.gridy = 1;
        comp.add(label, c);

        c.fill = GridBagConstraints.HORIZONTAL;
        c.ipady = 0;
        c.weightx = 1.0;
        c.gridwidth = 3;
        c.gridx = 1;
        c.gridy = 1;
        comp.add(showTestCase, c);

        JPanel testCaseItemPanel = createTestCaseItemPanel();
        c.fill = GridBagConstraints.HORIZONTAL;
        c.ipady = 0;
        c.weightx = 0.0;
        c.gridwidth = 4;
        c.gridx = 0;
        c.gridy = 2;
        comp.add(testCaseItemPanel, c);



        return comp;
    }

    private static void createAndShowGUI() {
        JFrame frame = new JFrame("SimpleSettingDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JButton btn = new JButton("open setting dialog");
        btn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub
                SimpleSettingDialog simpleSettingDialog = new SimpleSettingDialog(frame, true);
                simpleSettingDialog.pack();
                simpleSettingDialog.setVisible(true);
            }
        });
        frame.getContentPane().add(btn);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnsupportedLookAndFeelException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });

    }
}

Answer:

createTestCaseItemPanel() is executed twice. Once it is executed from createTestCasePanel(). The second time at this line in the constructor:

JPanel testItemPanel = createTestCaseItemPanel();

This second call creates a local variable testItemPanel which is not used. This however overrides some of the members, one of them is showTargetChoice, which now points to a field that is not visible.

To fix the issue just get rid of that second call.

Question:

new Java programmer here so I might have a basic question here. I am making an array of JTextFields. I want to use setText outside of the class in a public method but it does not work. However, I am able to use setText in the class (not in a method). I am not sure why. Here is some code as a SSCCE to show what I am experiencing. import java.awt.BorderLayout; import javax.swing.*;

public class testSetText extends JFrame 
{
    private JPanel          panel;
    private JTextField[]    arrayField;
    private JTextField      singleField;

    public testSetText()
    {
        // Specify an action for close button
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Make a panel
        panel = new JPanel();

        // Make array of JTextField components
        JTextField[] arrayField = new JTextField[2];
        for (int i = 0; i < 2; i++)
        {
            arrayField[i] = new JTextField(10);
            arrayField[i].setEditable(false);
            arrayField[i].setText("<>!");
            panel.add(arrayField[i]);
        }

        // Make just one JTextField component
        singleField = new JTextField(10);
        singleField.setText("Works here");
        panel.add(singleField);

        // Add to panel to frame
        add(panel);

        // Pack the contents of the window and display it
        pack();
        setVisible(true);

        // This will work!
        arrayField[0].setText("Array index in class");

        // This won't? Why?
        setInMethodWithArray();

        // Is this a problem with JTextField itself? Let me try a single element
        setInMethodWithSingleElement(); 

        // Hmmm so an element in an array of JTextFields can be addressed with setText in a class but not 
        // in a method in same class with same statement. But a single JTextField can be used in a method
        // by that same class. Why do arrays behave so differently?

        // EDIT: So I misunderstood, it does not work with a non array as well either!!
    }

    public void setInMethodWithArray()
    {
        arrayField[1].setText("This text will never show up");
    }

    public void setInMethodWithSingleElement()
    {
        //singleField.setText("Works here as non-array"); <--- before edit
        singleField.setText("nevermind, it does not work here either");
    }

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

Answer:

you should declare arrayField[] in class area so array Field is accessible from setInMethodWithArray() method.

JTextField[] arrayField = new JTextField[2]; //class area

in constructor initial it

 arrayField[i]= new JTextField(10);
 arrayField[i].setEditable(false);


yes this is work

arrayField[0].setText("Array index in class");

because arrayField in the constructor scope ..and you are accessing arrayField Within constructor .so it works..

This won't? Why?

setInMethodWithArray();

because method setInMethodWithArray() can't access arrayField[] because it's not in method scope or in class scope.that's because you have declare it in the constructor so after constructor code block execute arrayField doesn't exist .it's reference lost because it's local variable ..

public void setInMethodWithArray()
{
    arrayField[1].setText("This text will never show up");
}

now set can access arratField[] so now your code will work

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

public class testSetText extends JFrame 
{
    private JPanel          panel;
    private JTextField      singleField;
    // Make array of JTextField components
    private JTextField[] arrayField = new JTextField[2];

    public testSetText()
    {
        // Specify an action for close button
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Make a panel
        panel = new JPanel();

        for (int i = 0; i < 2; i++)
        {
            arrayField[i] = new JTextField(10);
            arrayField[i].setEditable(false);
            arrayField[i].setText("<>!");
            panel.add(arrayField[i]);
        }

        // Make just one JTextField component
        singleField = new JTextField(10);
        singleField.setText("Works here");
        panel.add(singleField);

        // Add to panel to frame
        add(panel);

        // Pack the contents of the window and display it
        pack();
        setVisible(true);

        // This will work!
        arrayField[0].setText("Array index in class");

        // This won't? Why?
        setInMethodWithArray();

        // Is this a problem with JTextField itself? Let me try a single element
        setInMethodWithArray(); 

        // Hmmm so an element in an array of JTextFields can be addressed with setText in a class but not 
        // in a method in same class with same statement. But a single JTextField can be used in a method
        // by that same class. Why do arrays behave so differently?
    }

    public void setInMethodWithArray()
    {
        arrayField[1].setText("This text will never show up");
    }

    public void setInMethodWithSingleElement()
    {
        singleField.setText("Works here as non-array");
    }

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

output>>

Question:

So, i am making a calculator. I was trying to display the equation in a JTextField, but the equation doesn't print correctly if it starts with a negative sign.

textfield.setText("-3+3");

gives output = 3+3-

but the same equation when in

System.out.println("-3+3");

gives output in the correct order

sorry if it is some noob mistake.

EDIT:

package practice;

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

import java.awt.event.*;

public class fun extends JFrame implements ActionListener , FocusListener{


public static void main(String[] args){

    new fun();
}

JTextField display2 = new JTextField(20);

JTextField display = new JTextField(20);

JButton btnSol = new JButton("=");

public fun(){

    JFrame fr = new JFrame();

    fr.setSize(450,450);

    fr.setLocationRelativeTo(null);

    fr.setResizable(false);

    fr.setTitle("Calculator");

    JPanel pnl = new JPanel();


    display.setEditable(false);
    display2.setEditable(false)

    pnl.add(display);

    pnl.add(display2);

    pnl.add(btnSol);

    btnSol.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String x = display2.getText();
            System.out.println(x);
            display.setText(x);
            int sum = 0;
            String[] arrOfStr = x.split("\\+");                   
            for (String a : arrOfStr) {
                System.out.println(a);

            sum += Integer.parseInt(a);
            display2.setText(Integer.toString(sum));
            }

        }
    });

    fr.add(pnl);
    fr.setVisible(true);


}

Answer:

That happens because you've set

textField.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);

Pretty simple. That's usually used for Arabic text (?), which I suppose is inverted.

Question:

How can I set text to JTextField when I click off from the component? Whenever I click it, it will clear the text like this:

// Clears the "Enter text here..." when clicked
    commandLine.addMouseListener(new MouseAdapter(){
        @Override
        public void mouseClicked(MouseEvent e){
            commandLine.setText("");
        }
    });  

But, when I click off the textfield, how can I reset it? I tried FocusEvent but it did not work as I wanted.


Answer:

I think you just need to add a FocusListener to the textField. Here there is a class I've written that works as you want.

class CustomPlaceholderTextField extends JTextField implements FocusListener {

private static final long serialVersionUID = 1L;
private boolean changedText = false;
private final String placeholder;


public CustomPlaceholderTextField(String placeholder){
    super();
    this.placeholder = Objects.requireNonNull(placeholder);
    this.addFocusListener(this);
    super.setText(placeholder);

}

@Override
public String getText() {
    if (this.changedText) {
        return super.getText();
    } else {
        return "";
    }
}

@Override
public void setText(String t) {
    if (t == null || t.isEmpty()) {
        super.setText(this.placeholder);
        this.changedText = false;
    } else {
        super.setText(t);
        this.changedText = true;
    }
}

@Override
public void focusGained(FocusEvent e) {
    if (!this.changedText) {
        super.setText("");
        this.changedText = true;
    }
}

@Override
public void focusLost(FocusEvent e) {
    if (this.getText().isEmpty()) {
        super.setText(this.placeholder);
        this.changedText = false;
    } else {
        this.changedText = true;
    }
}

}