Hot questions for Using JTextField in jlabel

Question:

I have a login form where a user can enter his credentials to login. I have a JLabel that serves to display the text telling the user that the user name cannot be empty. This label is display after a user click the login button when the text field is empty.

I want that the moment the user starts typing in the text field the label with the information should disappear.How do I achieve this behavior?

Here is the code:

public class JTextFiledDemo {

private JFrame frame;

JTextFiledDemo() {
    frame = new JFrame();
    frame.setVisible(true);
    frame.setSize(300, 300);
    frame.setLayout(new GridLayout(4, 1));
    frame.setLocationRelativeTo(null);
    iniGui();
}

private void iniGui() {

    JLabel error = new JLabel(
            "<html><font color='red'> Username cannot be empty!<></html>");

    error.setVisible(false);
    JButton login = new JButton("login");
    JTextField userName = new JTextField(10);

    frame.add(userName);
    frame.add(error);
    frame.add(login);
    frame.pack();

    login.addActionListener((ActionEvent) -> {
        if (userName.getText().equals("")) {
            error.setVisible(true);
        }
    });

}

public static void main(String[] args) {

    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            JTextFiledDemo tf = new JTextFiledDemo();
        }
    });
 }
}

Answer:

You have to create DocumentListener:

    DocumentListener dl = new DocumentListener()
    {
        @Override
        public void insertUpdate(DocumentEvent de)
        {
            error.setVisible(false);
        }

        @Override
        public void removeUpdate(DocumentEvent de)
        {
            //
        }

        @Override
        public void changedUpdate(DocumentEvent de)
        {
            error.setVisible(false);
        }
    };

then for your text fields:

login.getDocument().addDocumentListener(dl);

Question:

I have this code:

button2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                panel.add(label, BorderLayout.LINE_START);
                panel.add(label2, BorderLayout.LINE_START);
                panel.add(textfield, BorderLayout.LINE_END);
                panel.add(textfield2, BorderLayout.LINE_END);
                panel.add(button5);
                panel.revalidate();
                panel.repaint();
                label.setText("Geef de basis van de driehoek in cm: ");
                label2.setText("Geef de hoogte van de driehoek in cm: ");
            }
        });

Which corresponds with this screenshot:

I want it to actually look like this:

I'm new to Java and I know this is probably a dumb question, but I can't figure it out with information on the Internet.

Thanks in advance!


Answer:

Adding to the answer of Roan: I am not sure what layout manager you are using. Panel has a FlowLayout as default layout manager, and that one puts all components on 1 line. I think you have to use a GridLayout,or a GridbagLayout, and then your components will appear one above the other

Question:

I'm a newbie to java, i just want to make a simple JFrame which takes two numbers as input through JtextFields, sum them and return the answer through JLabel... but it simply doesn't do it what it suppose to do, here is my code:

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.util.*;
public class gUi extends JFrame {
    private JLabel lbl;
    private JLabel lbl2;
    private JLabel lbl3;
    private JTextField tb;
    private JTextField tb1;
    private int num1;
    private int num2;
        public gUi(){
        super("Sum Dialog");
        setLayout(new FlowLayout());
        lbl = new JLabel("1st Number:");
        add(lbl);
        tb = new JTextField(15);
        add(tb);
        tb.addActionListener(new ActionListener()
        {
        public void actionPerformed(ActionEvent event){
         num1 = Integer.parseInt(tb.getText());
        }
        });
        lbl2 = new JLabel("2nd Number");
        add(lbl2);
        tb1= new JTextField(15);
        tb1.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent event ){
                num2= Integer.parseInt(tb1.getText());
            }
        });

        add(tb1);
        int sum= num1+num2;
        String ssum = Integer.toString(sum);
        lbl3 = new JLabel();
        lbl3.setText(ssum);
        add(lbl3);      
    }
    }

import java.awt.*;
import javax.swing.*;
public class Main {

    public static void main(String[] args) {
        gUi g =new gUi();
        g.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        g.setVisible(true);
        g.setSize(180, 160);


    }

}

It Compiles Alright but not showing sum through JLabel when I put some intergers through Textfields... I am having this problem for a week and tried different things that I know so far but problem persists...


Answer:

Have a look at the code below(includes comments):

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

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

/**
 * Shows a Stage that has two text Fields
 *
 */
@SuppressWarnings("serial")
public class UserInterface extends JFrame {

    private JLabel label1;
    private JLabel label2;
    private JLabel label3;
    private JTextField textField1;
    private JTextField textField2;

    /**
     * Constructor
     */
    public UserInterface() {
        super("Sum Dialog");

        // Layout
        setLayout(new FlowLayout());

        // 1st JLabel
        label1 = new JLabel("1st Number:");
        add(label1);
        textField1 = new JTextField(15);
        add(textField1);

        // 2 second JLabel
        label2 = new JLabel("2nd Number");
        add(label2);
        textField2 = new JTextField(15);
        add(textField2);

        // 3 third label
        label3 = new JLabel();
        label3.setSize(200, 30);
        add(label3);

        JButton button = new JButton("Calculate");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                // calculate the sum when the Button is pressed
                int sum = Integer.parseInt(textField2.getText()) + Integer.parseInt(textField2.getText());
                label3.setText(Integer.toString(sum));
            }
        });
        add(button);

    }

    /**
     * Main method of the application
     * 
     * @param args
     */
    public static void main(String[] args) {
        UserInterface main = new UserInterface();
        main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        main.setVisible(true);
        main.setSize(180, 160);

    }

}

Question:

I 'm working on code that takes a string from a JTextField and puts it on a JLabel.

But my problem is always the string shown is missing the last character.

 private void jTextField1KeyTyped(java.awt.event.KeyEvent evt)     {
      String  ch=jTextField1.getText();
      jLabel1.setText(ch);
} 


Answer:

It's better to use a DocumentListener to check for changes in the jTextField. Not only will that notify you after the changes of the additional character are incorporated, but you will also be notified about changes unrelated to keyboard events (e.g. pasting text).

Question:

I've got a piece of code that sometimes runs fine and sometimes doesn't. I'm literally not changing anything but sometimes the text field will appear and sometimes it won't appear. How can code possibly run differently every time? It makes no sense to me. I'm reasonably new to java but I certainly didn't think this was possible...

If anyone can help me, could you include the fix, but also why this is happening? Because I'd like to understand the problem fully.

Here is my code:

import javax.swing.*;

public class Window {
    JFrame frame;
    JPanel panel;

    public Window(int x, int y, String t, boolean isHomePage){

        int xSize = x;
        int ySize = y;
        String title = t;

        frame = new JFrame();
        frame.setSize(xSize, ySize);
        frame.setLocationRelativeTo(null);
        frame.setTitle(title);
        frame.setVisible(true);
        frame.setResizable(false);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


        panel = new JPanel();
        frame.add(panel);
        panel.setLayout(null);
        panel.setVisible(true);

        if (isHomePage){
            homePage();
        }


    }

    public void homePage(){

        JLabel usernameLabel = new JLabel();
        usernameLabel.setText("Please enter your username:");
        usernameLabel.setBounds(0,100,300,20);
        panel.add(usernameLabel);
        usernameLabel.setVisible(true);

        JTextField textbox = new JTextField();
        textbox.setVisible(true);
        textbox.setBounds(280,100,400,20);
        panel.add(textbox);

    }


}

Answer:

As Reimeus states --

  1. Use a layout manager not null layout. While null layouts and setBounds() might seem to Swing newbies like the easiest and best way to create complex GUI's, the more Swing GUI'S you create the more serious difficulties you will run into when using them. They won't resize your components when the GUI resizes, they are a royal witch to enhance or maintain, they fail completely when placed in scrollpanes, they look gawd-awful when viewed on all platforms or screen resolutions that are different from the original one.
  2. Also call setVisible(true) on the JFrame after adding all components to the GUI, not before.

Note that you're confused on how setVisible(true) works. Yes, you're calling it on your sub components, but they've already get their visible property as true by default, and so calling this on the sub components has no effect. Your problem is when you're calling setVisible on the JFrame. You're calling it before adding the JPanel with the text field on it, and so this will cause it to appear occasionally. Prove it for yourself. Minimize and restore your GUI if the texzt field isn't visible, and it should now show.

Myself, if I wanted to swap views as you're trying to do above, I'd use a CardLayout.

Question:

This is my code for JButton. I am facing problem in setting background color for this Login button

JButton btnlogin = new JButton("Log in");
    btnlogin.setFont(new Font("Lucida Grande", Font.BOLD, 14));
    btnlogin.setAlignmentX(Component.CENTER_ALIGNMENT);
    btnlogin.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            EmailValidator emailValidator = new EmailValidator();
            if(!emailValidator.validate(txtEmail.getText().trim())) {
                System.out.print("Invalid Email ID");
                validationtext.setText("Invalid Email");
            }
        }
    });
    btnlogin.setBounds(210, 432, 200, 48);
    btnlogin.setBackground(new Color(66, 185, 217));
    frame.getContentPane().add(btnlogin);

I have already tried setting opaque value as true, but still not working.


Answer:

You just need to add two lines before setting background color to get your expected result:

  1. Set opaque value as true by writing this : btnlogin.setOpaque(true);
  2. By default a border is set in JFrame, you have to change it according to your wish. Here I am using example of MatteBorder : btnlogin.setBorder(new MatteBorder(1, 1, 1, 1, (Color) new Color(0, 0, 0)));

Then after you will get your expected result.

Question:

I am a newbie to Java and GUI programming. I have the following question.

In my GUI, I have a JTextField with a JLabel which reads "Radius". Now I want to put an icon next to the JTextField with a question mark which on clicked explains in details what the JLabel means. For instance, in this case, it should pop up a message explaining "The radius of the circle to be drawn on the image". The message should disapper when the mouse is moved Below is a pictorial description of what I am trying to implement.

My question is very basic. I want to know which Swing Component can I use to implement this? I tried looking it up on the web but I did not know which component to look for. Any help and suggestions would be appreciated.


Answer:

You can do it very easily. All you need to do is just use a JLabel and place no text on it. Rather, place an image on it

This code let's you set the Image to the JLabel

import java.awt.FlowLayout;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class AddingIconJLabel {
  public static void main(String[] args) {
    JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame frame = new JFrame();
    frame.setTitle("JLabel Test");
    frame.setLayout(new FlowLayout());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    ImageIcon imageIcon = new ImageIcon("yourFile.gif");
    JLabel label = new JLabel(imageIcon);

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

Secondly, Place the ToolTip on the JLabel to make your text appear on when you over on the Image

Here'e the helpful code hint for that

JLabel label = new JLabel("Username");
label.setToolTipText("Enter your username");

Question:

I've looked around but nothing seems to help me out. Basically I'm writing a multithreaded chat program with a gui. The user inputs his name in a textfield in a Login class and hits the login button which directs him to a ClientGUI class. In the client GUI class theres a JLabel at the top that says

"Welcome to the ChatSystem (Username)"

. So what the user input in the textfield in the login class should appear in the JLabel after "Welcome to the ChatSystem" but I can't figure out why it doesn't work. Here's my code:

Login Class:

loginB = new JButton("Login");
main.add(loginB);
loginB.addActionListener(new ActionListener(){
    @Override
    public void actionPerformed(ActionEvent e) {
        ClientGUI clientgui = new ClientGUI();
        clientgui.setVisible(true);
    }
}

ClientGUI class:

public ClientGUI(){
    Login login = new Login();
    String username = login.usernameTF.getText();
    welcome = new JLabel("Welcome to ChatSystem "+username, SwingConstants.CENTER);

}

I understand that username should really by a JLabel and not a String but I have tried many ways to do this and I can't seem to get my head around this.


Answer:

That is not going to work like that because login.usernameTF.getText(); is actually a new created object in the ClientGUI constructor...

what I would suggest to do is to overload the constructor and to pass the name as parameter...

Example:
 loginB.addActionListener(new ActionListener(){
     @Override
     public void actionPerformed(ActionEvent e) {
     ClientGUI clientgui = new ClientGUI(getTheNameAndpassItHere);
     clientgui.setVisible(true);
            }
        }

and then ClientGUI class:

public ClientGUI(String username){

    //Login login = new Login();
   // String username = login.usernameTF.getText();

    welcome = new JLabel("Welcome to ChatSystem "+username, SwingConstants.CENTER);

}

Question:

So I'm trying to make a very basic app that counts(adds a number to 0 every second) when you hit a button then displays it in a label and a text field. Since I'm using doubles the text output looks like this, for example: 2.34555555555555. I want it to display only 2 number after the dot. How could I do that?

Here's my code, as I said just a button, label and textfield alongside with a small timer thingy:

public class Frame1 {

    private JFrame frame;
    private JTextField txtbox1;
    double fiz = 1500;
    double mpfiz = fiz/60/60;
    int secondsPassed = 0;
    double penz = 0;
    Timer timer = new Timer();

    TimerTask task = new TimerTask() {
        public void run() {
            secondsPassed++;
            penz += mpfiz;
            lbpenz.setText("Ennyi: "+ penz);
            txtbox1.setText("Ennyi: " + penz);
        }};
        private JLabel lbpenz;


        public void start() {
            timer.scheduleAtFixedRate(task, 1000, 1000);
        }

        public static void main(String[] args) {
            Frame1 peldany = new Frame1();
            peldany.start();

            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    try {
                        Frame1 window = new Frame1();
                        window.frame.setVisible(true);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        /**
         * Create the application.
         */
        public Frame1() {
            initialize();
        }

        /**
         * Initialize the contents of the frame.
         */
        private void initialize() {

            JButton btnStart = new JButton("Start!");
            btnStart.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent arg0) {
                    start();
                }
            });
        }
}

Thanks in advance.


Answer:

Try the following code

public void run() {
    DecimalFormat df = new DecimalFormat(".##");

    secondsPassed++;
    penz += mpfiz;
    lbpenz.setText("Ennyi: "+ df.format(penz));
    txtbox1.setText("Ennyi: " + df.format(penz));
}};

Question:

The situation is that the JButton1 corresponds to JLabel1, JButton2 to JLabel2 and so on. However I want to disable the JButton# when the value of Jlabel returns on the TextField and reenable them when it is gone.

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

public class qwerty {

ArrayList<JTextField> tfs = new ArrayList<JTextField>();
ArrayList<JButton> bts = new ArrayList<JButton>();


int counter = 0;
String answer;
JLabel j1 = new JLabel("Mark");
JLabel j2 = new JLabel("Joe");
JLabel j3 = new JLabel("John");
JLabel j4 = new JLabel("Ray");

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

    JFrame frame = new JFrame();
    frame.getContentPane().setLayout(new FlowLayout());

    // Add new buttons to bts
    bts.add(new JButton("Button1"));
    bts.add(new JButton("Button2"));
    bts.add(new JButton("Button3"));
    bts.add(new JButton("Button4"));

   // Add new textfields to tfs
   tfs.add(new JTextField());
   tfs.add(new JTextField());
   tfs.add(new JTextField());



   j1.setPreferredSize(new Dimension(100, 25));
   j2.setPreferredSize(new Dimension(100, 25));
   j3.setPreferredSize(new Dimension(100, 25));
   j4.setPreferredSize(new Dimension(100, 25));


    for (JButton b : bts) {
        b.addActionListener(new ButtonActionListener());
        b.setPreferredSize(new Dimension(100, 25));
        frame.getContentPane().add(b);
    }

        frame.getContentPane().add(j1);
        frame.getContentPane().add(j2);
        frame.getContentPane().add(j3);
        frame.getContentPane().add(j4);



    for (JTextField tf : tfs) {
        tf.setPreferredSize(new Dimension(100, 25));
        tf.setEditable(false);
        frame.getContentPane().add(tf);
    }


    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(500, 500);
    frame.setVisible(true);

}

public class ButtonActionListener implements ActionListener {


    @Override
    public void actionPerformed(ActionEvent e) {
        if (counter >= tfs.size()) {
            counter = 0;
        }

        String a = ((AbstractButton) e.getSource()).getText();
        if (a == "Button1"){
        tfs.get(counter).setText(j1.getText());
        }   

        if (a == "Button2"){
        tfs.get(counter).setText(j2.getText());
        }

        if (a == "Button3"){
        tfs.get(counter).setText(j3.getText());
        } 

        if (a == "Button4"){
        tfs.get(counter).setText(j4.getText());
        } 

        counter++;
    }


}

}


Answer:

You would use a DocumentListener to monitor the change in the text field and then set the state of the button.

Here is some code that allows you to associate 1 (or more) text fields with a button.

import java.awt.*;
import java.awt.event.*;
import java.util.List;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.event.*;

public class DataEntered implements DocumentListener
{
    private JButton button;
    private List<JTextField> textFields = new ArrayList<JTextField>();

    public DataEntered(JButton button)
    {
        this.button = button;
    }

    public void addTextField(JTextField textField)
    {
        textFields.add( textField );
        textField.getDocument().addDocumentListener( this );
    }

    public boolean isDataEntered()
    {
        for (JTextField textField : textFields)
        {
            if (textField.getText().trim().length() == 0)
                return false;
        }

        return true;
    }

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

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

    @Override
    public void changedUpdate(DocumentEvent e) {}

    private void checkData()
    {
        button.setEnabled( isDataEntered() );
    }

    private static void createAndShowUI()
    {
        JButton submit = new JButton( "Submit" );
        submit.setEnabled( false );

        JTextField textField1 = new JTextField(10);
        JTextField textField2 = new JTextField(10);

        DataEntered de = new DataEntered( submit );
        de.addTextField( textField1 );
        de.addTextField( textField2 );

        JFrame frame = new JFrame("SSCCE");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(textField1, BorderLayout.WEST);
        frame.add(textField2, BorderLayout.EAST);
        frame.add(submit, BorderLayout.SOUTH);
        frame.pack();
        frame.setLocationByPlatform( true );
        frame.setVisible( true );
    }

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

Text must be entered in all text field in order to enable the button.

In your case you have a one-to-one mapping of text field to button, so you only need to enter text in one text field in order to enable the related button.

Question:

So,I have a JLabel and a JTextField,it's there a possible way to add the JTextField to JLabel,can you give me some examples? I know there are lots of alternatives but I want to do it this way.

JTextField text=new JTextField();
text.setText("this is textfield");
text.setBounds(20,0,100,20);
//now the jlabel
JLabel label=new JLabel();
label.setOpaque(true);
label.setBackground(Color.blue);
label.add(text);//this is what I tryed

Answer:

I would suggest a JPanel instead of a JLabel. If you are up to create a GUI it is the easiest way, to cut everything into smaller panels you can finaly join.

JTextField text=new JTextField();
text.setText("this is textfield");
text.setBounds(20,0,100,20);
JPanel panel=new JPanel();
panel.addLayout(new FlowLayout());
panel.setBackground(Color.blue);
panel.add(text);

this should work fine I hope

Question:

Link to code pastiebin

I have a JTextField on my first GUI window. Later in the program I open another GUI and go to display the value of the JTextField but in the program I get an error of invalid layout. I'm not sure what I need to change to get it to display the correct value.

Picture for reference


Answer:

JLabel supfirst = new JLabel("Supervisors First Name :" + firstvalue.getText());

.getText() is probably what you're missing.

This is what displays the content from the input field.

Question:

I have an application calculating clock-in hours of all seven days in a week. What I plan, is to let users introduce entry and leaving hours/minutes of every day, and thus collect these data to do calculation.

The UI part should be like:

Monday:     mondayEntryHour   :   mondayEntryMinutes       mondayLeaveHour   :   mondayLeaveMinutes        
Tuesday:   tuesdayEntryHour   :   tuesdayEntryMinutes     tuesdayLeaveHour   :   tuesdayLeaveMinutes
....

All where I collect data, are JTextFields, and the : between them, is a JLabel. All 14 labels have same content, same font and style, but I just cannot create a same variable and add it 14 times in all where needed to be, because it is added only the last time.

To prove what I say, I have a SCCEE here:

import java.awt.Cursor;
import java.awt.EventQueue;

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

import net.miginfocom.swing.MigLayout;

public class RepeatedJLabel extends JFrame {
    public RepeatedJLabel() {
        run();

    }

    public void run() {
        JPanel p = new JPanel();
        p.setLayout(new MigLayout("debug, fill", "[grow]", "[]10[]10[]"));

        JLabel label = new JLabel("MY LABEL 1");
        p.add(label, "cell 0 1, grow");
        p.add(label, "cell 0 2, grow");
        p.add(label, "cell 0 3, grow");
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        getContentPane().setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        getContentPane().add(p);

        setVisible(true);
        setLocationRelativeTo(null);
        setResizable(true);
        pack();
    }

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

            @Override
            public void run() {
                RepeatedJLabel test = new RepeatedJLabel();

            }
        });
    }
}

Must I create 14 variables for them? It is stupid. I don't wanna mingle with copy/shallow copy/deep copy of this variable, because it's too simply to mess around. Any idea?


Answer:

  1. Use a factory method to create each JLabel:

    private static JLabel newLabel() {
        return new JLabel("MY LABEL 1");
    }
    
  2. Use a for loop to add the JLabel each time:

    final int amountOfLabels = 3;
    for(int i = 0; i < amountOfLabels; i++) {
        panel.add(newLabel(), "cell 0 " + i + ", grow");
    }