Hot questions for Using JTextField in jpanel

Question:

I'm trying to make a basic UI with Swing. I want to have a JFrame with a JTabbedPane with multiple Tabs. If I only make 1 JPanel with a JTextField it works fine, but as soon as I want to add another JPanel with a JTextField it just shows nothing. What am I doing wrong here?

Here is a quick example:

import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;

public class SwingUI {

    private final JFrame frame;
    private final JTabbedPane tabbedPane;

    public SwingUI(){

        frame = new JFrame("Test");
        frame.setSize(1000, 1000);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(new GridLayout(1, 1));

        tabbedPane = new JTabbedPane();
        tabbedPane.addTab("Login", makeLoginPanel());
        tabbedPane.addTab("Login2", makeLoginPanel());  //if this is left out it works
        frame.getContentPane().add(tabbedPane);

    }

    private JPanel makeLoginPanel(){
        JPanel p = new JPanel();
        p.setLayout(null);

        JLabel lblName = new JLabel("Name:");
        lblName.setBounds(50,50,100,30);
        p.add(lblName);

        JTextField x = new JTextField("text");
        x.setBounds(200,200,200,200);
        p.add(x);

        return p;
    }
}

Answer:

The frame should be made visible AFTER the components have been added to the frame.

So:

frame.setVisible( true );

should be the last statement in your constructor.

Also:

frame.setSize(1000, 1000);

Don't hardcode sizes. You don't know what resolution other people may be using.

Instead use:

frame.setExtendedState(JFrame.MAXIMIZED_BOTH);

and the frame will open maximized on your screen.

Also,

frame.getContentPane().setLayout(new GridLayout(1, 1));

Don't use a GridLayout. The default layout is the BorderLayout which will allow you to add a component to the CENTER by default and the component will fill the entire space of the frame.

Question:

I have a JFrame with a JButton , this button open a new JFrame where there should be a text box ( JTextField ) that I will use for a search , the problem is that I don't know how to insert it . I came up with this :

N.B I'm a beginner, sorry in advance for the easy question :)

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.JPanel;
import javax.swing.JTextField;


public class MainWindow {




// Seconda Finestra
public static void NuovaFinestra (JPanel panel) {

    panel.setLayout(null);



    JButton Ricerca = new JButton("Ricerca");
    Ricerca.setBounds(100, 100, 200, 50);
    panel.add(Ricerca);


    Ricerca.addActionListener(new ActionListener(){
         public void actionPerformed(ActionEvent e) {
             JFrame FinestradiRicerca = new JFrame("Finestra di Ricerca");
             FinestradiRicerca.setBounds(300, 300, 500, 500);

             FinestradiRicerca.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             JPanel riquadroRicerca = new JPanel();
             FinestradiRicerca.add(riquadroRicerca);
             FinestradiRicerca.setVisible(true);
             JTextField ciao;
                ciao = new JTextField ();
                 }
    });

}




//Main  
public static void main(String[] args) {

    //Finestra Principale
    JFrame finestra = new JFrame("Finestra principale");
    finestra.setSize(500, 500);
    finestra.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


//JPanel della finestra principale
    JPanel riquadro = new JPanel();
    finestra.add(riquadro);
    finestra.setVisible(true);

    NuovaFinestra(riquadro);

}





}

Answer:

You needed to add your new elements to riquadroRicerca BEFORE adding the Panel to FinestradiRicerca, I recommend you NOT to use null layout but a Layout Manager or combinations of them. If you insist on keeping null layout then see below example. But for this kind of app I'd suggest a CardLayout.

I also suggest not using multiple JFrames since they will open multiple windows on task bar which is user unfriendly. See: Use of multiple JFrames, Good / Bad Practice

As an aside note, follow Java naming conventions. For example you called a JFrame as FinestradiRicerca instead rename it to: finestradiRicerca (1st letter of a variable in lowercase).

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.JPanel;
import javax.swing.JTextField;

public class MainWindow {
    // Seconda Finestra
    public static void NuovaFinestra (JPanel panel) {
        panel.setLayout(null);
        JButton Ricerca = new JButton("Ricerca");
        Ricerca.setBounds(100, 100, 200, 50);
        panel.add(Ricerca);
        Ricerca.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                JFrame FinestradiRicerca = new JFrame("Finestra di Ricerca");
                FinestradiRicerca.setBounds(300, 300, 500, 500);
                //If you don't want to close whole app when closing this windo change it to: JFrame.DISPOSE_ON_CLOSE
                FinestradiRicerca.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                JPanel riquadroRicerca = new JPanel();
                JTextField ciao;
                JLabel myLabel = new JLabel("Here goes your label text");
                ciao = new JTextField ();
                ciao.setColumns(20);
                riquadroRicerca.add(myLabel);
                riquadroRicerca.add(ciao);
                FinestradiRicerca.add(riquadroRicerca);
                FinestradiRicerca.setVisible(true);
            }
        });
    }

    //Main  
    public static void main(String[] args) {
        //Finestra Principale
        JFrame finestra = new JFrame("Finestra principale");
        finestra.setSize(500, 500);
        finestra.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //JPanel della finestra principale
        JPanel riquadro = new JPanel();
        finestra.add(riquadro);
        finestra.setVisible(true);
        NuovaFinestra(riquadro);
    }
}

So, your code after a few modifications, to make JLabel and JTextField visible gives the following output:

However, please follow my above recomendations.

Question:


Answer:

In order to read a float from a text field you can do it two ways.

String a=text.getText();//Create a string to store the incoming data
float f = Float.parseFloat(a);// to cast the data

Else

float f = Float.parseFloat(text.getText);

Question:

For my assignment I have to create a frame-based application that allows the user to specify RGB values in three text fields, and, when a button is pressed, displays my name and registration number in the chosen colour. I believe all my code is correct so far however it appears that there is an issue in the part that changes the colour.

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



public class ex1 extends JFrame {
JLabel label;
JTextField r, g, b;

public ex1() {
    //panels to hold information
    JPanel bottomPanel = new JPanel();
    JPanel upperPanel = new JPanel();

    //fields that will hold the colour values
    r = new JTextField("Red", 10);
    g = new JTextField("Green", 10);
    b = new JTextField("Blue", 10);

    //add to frame
    bottomPanel.add(r);
    bottomPanel.add(g);
    bottomPanel.add(b);
    add(bottomPanel, BorderLayout.SOUTH);
    add(upperPanel, BorderLayout.CENTER);
    label = new JLabel("CE203 Assignment 1, submitted by:");
    label.setForeground(new Color(255, 0, 0));
    JButton button = new JButton("Enter");
    upperPanel.add(label);
    bottomPanel.add(button);
    button.addActionListener(new ButtonHandler(this));
}

public JLabel getLabel() {
    return label;
}

class ButtonHandler implements ActionListener {
    private ex1 assignment1;
    public ButtonHandler(ex1 assignment1) {
        this.assignment1 = assignment1;
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        int r1 = Integer.parseInt(assignment1.r.getText());
        int g1 = Integer.parseInt(assignment1.g.getText());
        int b1 = Integer.parseInt(assignment1.b.getText());
        assignment1.getLabel().setForground(new Color(r1, g1, b1));
    }
}

public static void main(String[] args) {
    JFrame frame = new ex1();
    frame.setSize(400, 400);
    frame.setDefaultCloseOperation(ex1.EXIT_ON_CLOSE);
    frame.setVisible(true);
}
}

If anyone could show me what is going wrong and how I can fix it, it would be greatly appreciated.


Answer:

Don't ignore the IDE when it is reporting compilation errors!

assignment1.getLabel().setForground(new Color(r1, g1, b1));

Should be:

assignment1.getLabel().setForeground(new Color(r1, g1, b1));
Other tips
  1. Instead of:

    frame.setSize(400, 400); // random guess at required size
    

    have:

    frame.pack(); // calculates the required size
    
  2. In real world programming, the user would lynch a programmer for offering 3 text fields when one JColorChooser is vastly superior.

Question:

(A general Question)

I have an assignment in which I have to build a sudoku and I thought about the classes/logic to build it and thought I could use an advice.

I want to use a JFrame and build on it a JPanel with TextFields (the user is supposed to "solve" the sudoku).

I have a class called "DrawSudoku" which draws an empty board. I have to draw an empty board first, so the "user" can type numbers in it. On that board I have to check some logic. So I have to access the textFields themselves.

So far that's all I've done. Now I am thinking about building another class with the "logic" behind the board.

But I've encountered a problem How do I get the JTextFields that exists on the JPanel, from another class?

Can I have separate classes for the Drawing and Logic Behind it? Thanks!


Answer:

On that board I have to check some logic. So I have to access the textFields themselves.

Not necessarily

How do I get the JTextFields that exists on the JPanel, from another class?

How do you assess the state of any object from another object -- via an accessor or "getter" method.

Can I have separate classes for the Drawing and Logic Behind it?

Not only can you, you absolutely should.

If this were my project I would consider doing the following:

  • First and foremost, create a non-GUI Sudoku model class. This could include:
    • SudokuCellValue enum (name it what you want), an enum that can hold a value from 1 to 9 as well as possibly an EMPTY value (although you could use null to represent this)
    • SudokuCell objects, ones that have boolean editable, and holds a single value to the above enum.
    • SudokuGrid object, a 9 x 9 grid of SudokuCells.
    • A mechanism to hook listeners into the model so that they are notified of changes in state -- i.e., changes in the SudokuCellValue held by one or more SudokuCell objects. The View (the GUI) will be one of the major listeners to this model, and will change its display when the model's state changers.
  • I'd create a View class, meaning the GUI,
    • One that holds a reference to its model (see above)
    • and one that has attached listeners to its model -- I like to use PropertyChangeListeners for this
    • I'd hook it up with a grid of JTextFields,
    • These text fields would use a DocumentFilter to allow the user to either clear the field or enter only 1 through 9 single digit numeric text.
    • Would be enabled for input (or perhaps better -- focusable for input), based on the editable state of the corresponding model cell.
  • I'd create a Controller that would control some of the communication between the view and model.

With this type of set up, outside classes could listen for changes to the model and wouldn't have to have any access directly to the JTextFields of the view.

Question:

I am currently learning how to use Swing in Java. When adding JTextFields, JLabels, or JButtons to a JPanel I usually do so in 4 lines such as this:

gbc.gridx = 0;
gbc.gridy = 0;
JTextField example = new JTextField("", 6);
p.add(example, gbc);

However I am trying to condense my code by making a method such as this:

public static void addTextField (JPanel p, GridBagConstraints gbc, String str, int x, int y, int len) {
gbc.gridx = x;
gbc.gridy = y;
JTextField tempTF = new JTextField(str, len);
p.add(tempTF, gbc);
}

and calling addTextField() in the main method such as this:

ClassName.addTextField(p2, gbc, "", 1, 1, 6);

The issue that I have is how to retrieve the text in the JTextField. Something like,

String str = example.getText();

or

String str2 = tempTF.getText();

which normally works, doesn't work anymore.

Any ideas on how I could solve this?

This is the full code I am working with before any answers:

/**
* This program creates two windows.
* Window #1 displays Hello World
* WIndow #2 prompts users to input information
*/

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

public class MessingWithSwing extends JFrame{

  //Main Method
  public static void main(String[] args) { 
    //makes the first window
    MessingWithSwing window1 = new MessingWithSwing("Window #1", 300, 300);
    //makes the second window with minimum dimensions
    MessingWithSwing window2 = new MessingWithSwing("Window #2", 450, 300, 300, 300);

    //GridBagConstraints allows the objects in each panel to be positioned in grid cordinates
    GridBagConstraints gbc = new GridBagConstraints();
    //sets the spaces between each grid position
    gbc.insets = new Insets(10, 10, 10, 10);

    //creates a JPanel that uses a grid layout
    JPanel p1 = new JPanel(new GridBagLayout());
    //adds the panel in the center of window1
    window1.add(p1, BorderLayout.CENTER);
    //sets the panel visible so it can correctly display the labels, textfields, and buttons
    p1.setVisible(false);

    //uses the method created below to add JLabels to p1
    MessingWithSwing.addLabel(p1, gbc, "Hello", 0, 0);
    MessingWithSwing.addLabel(p1, gbc, "World", 0, 1);

    p1.setVisible(true);

    //creates a second JPanel that also uses a grid layout
    JPanel p2 = new JPanel(new GridBagLayout());
    //adds the panel at the top of window2
    window2.add(p2, BorderLayout.NORTH);
    //sets the panel visible so it can correctly display the labels, textfields, and buttons
    p2.setVisible(false);

    //uses the method created below to add JLabels to p2
    MessingWithSwing.addLabel(p2, gbc, "Please Enter The Following", 0, 0);
    MessingWithSwing.addLabel(p2, gbc, "Name: ", 0, 1);
    MessingWithSwing.addLabel(p2, gbc, "Age: ", 0, 2);

    //uses the method created below to add JTextFields to p2
    MessingWithSwing.addTextField(p2, gbc, "", 1, 1, 6);
    MessingWithSwing.addTextField(p2, gbc, "<age>", 1, 2, 6);

    //uses the method created below to add a JButton to p2
    MessingWithSwing.addButton(p2, gbc, "Enter", 0, 3);

    p2.setVisible(true);

    /* Issue:
     * The someting like the line below would not work
     * How would you access the text inputted into each JTextField?
     */
//    String str = tempTF.getText();

  } //end of Main Method

  //first constructor makes a window that is completely resizable
  public MessingWithSwing(String title, int sizeX, int sizeY) {
    super(title);
    setSize(sizeX, sizeY);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setVisible(true);
  }

  //second constructor makes a window that is resizable but has minimum dimensions
  public MessingWithSwing(String title, int sizeX, int sizeY, int minSizeX, int minSizeY) { 
    super(title);
    setSize(sizeX, sizeY);
    setMinimumSize(new Dimension(minSizeX, minSizeY));
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setVisible(true);
  }

  //This method adds a JLabel with an indicated text, at an indicated GridBagConstraints location, to an indicated JPanel
  public static void addLabel(JPanel p, GridBagConstraints gbc, String str, int x, int y) {
    gbc.gridx = x;
    gbc.gridy = y;
    JLabel tempLabel = new JLabel(str);
    p.add(tempLabel, gbc);
  }

  //This method adds a JTextField with an indicated length and text, at an indicated GridBagConstraints location, to an indicated JPanel
  public static void addTextField (JPanel p, GridBagConstraints gbc, String str, int x, int y, int len) {
    gbc.gridx = x;
    gbc.gridy = y;
    JTextField tempTF = new JTextField(str, len);
    p.add(tempTF, gbc);
  }

  //This method adds a JButton with an indicated text, at an indicated GridBagConstraints location, to an indicated JPanel
  public static void addButton (JPanel p, GridBagConstraints gbc, String str, int x, int y) {
    gbc.gridx = x;
    gbc.gridy = y;
    JButton tempB = new JButton(str);
    p.add(tempB, gbc);
  }

}

So if I understand Kequiang Li correctly it would look something like:

public static JTextField addTextField (JPanel p, GridBagConstraints gbc, String str, int x, int y, int len) {
    gbc.gridx = x;
    gbc.gridy = y;
    JTextField tempTF = new JTextField(str, len);
    p.add(tempTF, gbc);
    return tempTF;
  }

Then:

ArrayList<JTextField> tfList = new ArrayList<JTextField>();
tfList.add(ClassName.addTextField(p1,gbc,text,0,0,8));
String str = tfList.get(0).getText();

Answer:

How to get the text inside your text fields totally depends on where and when you want to get the text.

Let's say you want to retrieve the text whenever you want, then you can make your addTextField returns the text field it has added. This way, you can keep track of all the text fields in a list, an array, or even a map, and just call getText on these text fields.

In another situation, you might want the text only when user presses the enter key in the text field, then you can bind listener to the text field. When the event occurs, you can have access to the source of the event, which is the text field and then retrieve the text.

Question:

I'm trying to set the border of a JPanel by using a child textfield. I've tried using getParent(), but the option for setting the border does't exist. What is the reason for this?


Answer:

The getParent() method returns a Container object.

The setBorder(...) method is only defined for JComponent objects.

So you need to cast the parent Container to a JPanel. Something like:

Container parent = textField.getParent();
JPanel panel = (JPanel)parent;
panel.setBorder( new LineBorder(Color.RED) );

Question:

I have recently started working with Java+Swing building an UI and I currently have an issue with JTextField placed on JPanel with FlowLayout.

In my example I have a window, containing panel with button. Clicking the button adds a component derived from JPanel and containing JTextField.

The problem is that when I type in JTextField it does not get updated (does not get resized). However when I resize the window or do anything else which forces window/panel redraw, the text field being resized (just what I expect to happen automatically).

When I change base class from JPanel to JTextField it works in the way I try to achieve, but I need to have JPanel as the base class so that I can take advantages of putting child components to it.

I have checked different questions here as well as I have Googled trying to find the solution, however it did not work for me. I have tried validate/invalidate/revalidate/repaint in different combinations and for different components, as well as trying to enforce revalidation for each typed character, which does not sound as the right way for me. So far I understoon that it is something to do with Layout Managers.

Could anyone please help me with understanding how that works and what should I read about how Swing UI, layout management and redrawing is working?

Also, I would be glad if someone could help me with my particular issue with my code.

Thanks in advance!

Here is my code below:

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


class TagVisual extends JPanel /*JTextField*/ {

    private JTextField editField;

    public TagVisual() {

        FlowLayout layout = new FlowLayout();
        layout.setHgap(0);
        layout.setVgap(0);
        setLayout(layout);

        editField = new JTextField();
        editField.setBackground(Color.RED);

        editField.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                editField.setSize(editField.getSize());
                editField.revalidate();
                remove(editField);
                add(editField);
                revalidate();
                repaint();
            }
        });

        add(editField, FlowLayout.LEFT);
    }

    public void place(JPanel panel) {
        panel.add(this);

        editField.grabFocus();
    }
}

public class MainWindow {

    private JPanel mainPanel;
    private JButton btnPlace;
    private JFrame frame;

    public MainWindow(JFrame frame) {

        mainPanel = new JPanel(new FlowLayout());
        btnPlace = new JButton();
        btnPlace.setText("Place");
        mainPanel.add(btnPlace);

        this.frame = frame;
        btnPlace.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                TagVisual v = new TagVisual();
                v.place(mainPanel);
                mainPanel.revalidate();
                mainPanel.repaint();
                mainPanel.updateUI();
                frame.revalidate();
                frame.repaint();
            }
        });
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("TextFieldUpdateIssue");

        frame.setContentPane(new MainWindow(frame).mainPanel);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }
}

Answer:

If i were you, i would not try to resize the textfields when the user enters some text.

I suggest you to give them a fixed size using JTextField (int columns) constructor, this will allow you to create some textfields which are "wide enough".

If you still want to make them wider when some text is entered, you can't use an ActionListener, since it will fire an event when the user presses ENTER key, not based on the text entered.

For this purpose you can register a Document Listener on your textfield's document.

You also could override getPreferredSize () method to calculate and return an appropriate size. In the example below i use a JLabel for convenience to calculate the preferred width, but you could use FontMetrics.

If you are adding multiple tags to your panel, you should also consider using a JScrollPane in order to make scrollbars appear when your panel needs more space.

See this example (i changed a bit your code because it would not compile and the general design was bad, now i think it is better, but not still good) :

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class MainWindow
{
    public static void main (String [] a) {
        SwingUtilities.invokeLater (new Runnable () {
            @Override public void run () {
                try {
                    UIManager.setLookAndFeel (UIManager.getSystemLookAndFeelClassName ());
                    createAndShowGUI ();
                }
                catch (Exception e) {
                    JOptionPane.showMessageDialog (null, "An unexpected error occurred: " + e.getClass ().getSimpleName (), "Error", JOptionPane.ERROR_MESSAGE);
                }
            }
        });
    }
    private static void createAndShowGUI () {
        JFrame frame = new JFrame ("TextFieldUpdateIssue");
        frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
        frame.setContentPane (new MainPanel ());
        frame.setExtendedState (JFrame.MAXIMIZED_BOTH);
        frame.setLocationRelativeTo (null);
        frame.setVisible (true);
    }
}
class MainPanel extends JPanel
{
    private JPanel tagsPanel;

    public MainPanel () {
        super (new BorderLayout (0, 10));
        add (new JButton (new AbstractAction ("Add tag") {
             @Override public void actionPerformed(ActionEvent e) {
                addNewTag ();
            }
        }), BorderLayout.NORTH);
        tagsPanel = new JPanel ();
        tagsPanel.setLayout (new FlowLayout (FlowLayout.CENTER, 10, 0));
        add (tagsPanel, BorderLayout.CENTER);
    }
    private void addNewTag () {
        TagVisual v = new TagVisual ();
        tagsPanel.add (v);
        v.grabFocusOnField ();
        revalidate ();
    }
}
class TagVisual extends JPanel
{
    private JTextField editField;

    public TagVisual() {
        super (new FlowLayout (FlowLayout.CENTER, 0, 0));
        add (editField = createNewTextField (null), FlowLayout.LEFT);
    }
    private JTextField createNewTextField (String text) {
        JTextField textField = new JTextField (text) {
            @Override public Dimension getPreferredSize () {
                Dimension d = super.getPreferredSize ();
                return new Dimension (new JLabel (getText ()).getPreferredSize ().width + 10, d.height);
            }
        };
        textField.setBackground (Color.RED);
        textField.getDocument ().addDocumentListener (new DocumentListener () {
            @Override public void changedUpdate (DocumentEvent e) {
                revalidate ();
            }
            @Override public void insertUpdate (DocumentEvent e) {
                revalidate ();
            }
            @Override public void removeUpdate (DocumentEvent e) {
                revalidate ();
            }
        });
        return textField;
    }
    public void grabFocusOnField () {
        editField.grabFocus ();
        editField.setCaretPosition (editField.getText ().length ());
    }
}

Screenshot (short text):

Screenshot (Longer text):

Question:

I just got started learning JFrame and is trying to create a frame containing JLabels and JTextFields frame using grouplayout, but the contents inside my panel aren't appearing when I run the program. All help is appreciated.

    package practice;

import java.awt.*;

import javax.swing.*;


public class Boxc {
    public static void main(String[] args){
        JFrame frame = new JFrame("---------------------(-_-)---------------------"); 
        JLabel headText = new JLabel("Teach Me"); 

        //head text
        headText.setVerticalAlignment(JLabel.TOP);
        headText.setHorizontalAlignment(JLabel.CENTER);
        headText.setFont(headText.getFont().deriveFont(20f));




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

        frame.setLocationRelativeTo(null); //Center start position
        frame.add(headText);

        //panel 1
        JPanel panel1 = new JPanel();
        GroupLayout layout = new GroupLayout(panel1);
        panel1.setLayout(layout);
        layout.setAutoCreateGaps(true);
        layout.setAutoCreateContainerGaps(true);


        JLabel uInput = new JLabel("When You Type:");
        JTextField uText = new JTextField("Enter Here");
        JLabel iReply = new JLabel("I Reply:");
        JTextField iText = new JTextField("Enter Here");

        GroupLayout.SequentialGroup hGroup = layout.createSequentialGroup();
        hGroup.addGroup(layout.createParallelGroup().
                addComponent(uInput).addComponent(iText));
        hGroup.addGroup(layout.createParallelGroup().
                addComponent(uText).addComponent(iText));
       layout.setHorizontalGroup(hGroup);





        frame.add(panel1);
    }}

Answer:

Java is weird.

It all has to do with the ordering of your JFrame methods. You must ALWAYS do frame.setVisible(true); at the end, preferably as the last line of code in whatever you're using to initiate the JFrame. In that case,

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

    frame.setLocationRelativeTo(null); //Center start position
    frame.add(headText);

would be changed to

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(700, 500);
    frame.setResizable(false);

    frame.setLocationRelativeTo(null); //Center start position
    frame.add(headText);
    frame.setVisible(true); 

Hope this helps.

EDIT: ignore the changing from/to. Put the frame.setVisible(true); after frame.add(panel1);.

Question:

I want to set location and size of my JTextField, how can I do it ? My code doesn't work.

public static void main(String[] args) {

    JTextField txt1;


    JFrame frame = new JFrame("Hangman");
    frame.setSize(1100, 600);
    frame.getContentPane().setLayout(new FlowLayout());
    frame.setResizable(false);
    frame.getContentPane().setBackground(Color.BLACK);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    txt1 = new JTextField(50);
    txt1.setSize(200, 199);
    txt1.setLocation(400, 200);
    frame.add(txt1);
    frame.setVisible(true);
}

txt1.setSize and txt1.setLocaiton doesn't work.

Output


Answer:

Absolute positioning doesn't work with a layout manager.

If you really need it, you will have to set null as a layout manager, i.e :

frame.getContentPane().setLayout(null);

Question:

I have looked around and found various bits and pieces of information that have helped me so far but I am currently stuck with the following problems:

  1. My JTextFields do not change to 0 if they're outside of the range of (0-255).

  2. The JPanel does not change colors based off what is typed in the JTextFields until one of the buttons is clicked.

This is the code that I currently have:

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

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

public class App1 extends JFrame implements ActionListener
    {
            JPanel upperBase, lowerBase, jpRed, jpGreen, jpBlue, jpChanging;
            JLabel jLRed, jLGreen, jLBlue;
            JTextField jtf_red, jtf_green, jtf_blue;
            JButton rP, rM, gP, gM, bP, bM;

        public static void main(String[] args) 
    {
        App1 app = new App1();
    } 

    App1()
{
    // Creates Container
    // Sets Layout for Container
    Container cp = this.getContentPane();
    cp.setLayout(new BoxLayout (cp, BoxLayout.Y_AXIS));

     // Sets Window Title and Size
     // Exits Application on Close
    this.setTitle("Application 1");
    this.setSize(800, 600);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // Creates 6 JPanels
    upperBase = new JPanel();
    lowerBase = new JPanel();
    jpRed = new JPanel();
    jpGreen = new JPanel();
    jpBlue = new JPanel();
    jpChanging =  new JPanel();

    // Adds upper/lowerBase to Container
    cp.add(upperBase);
    cp.add(lowerBase);

    // Sets Layout for upper/lowerBase
    upperBase.setLayout(new GridLayout(1,3));
    lowerBase.setLayout(new GridLayout(1,1));

    // Sets Color for jpRed/Green/Blue
    jpRed.setBackground(Color.RED);
    jpGreen.setBackground(Color.GREEN);
    jpBlue.setBackground(Color.BLUE);
    jpChanging.setBackground(Color.BLACK);

    // Adds jpRed/Green/Blue to upperBase & adds jpChanging to lowerBase
    upperBase.add(jpRed);
    upperBase.add(jpGreen);
    upperBase.add(jpBlue);
    lowerBase.add(jpChanging);

    // Setup for Red JPanel (jpRed)
    jLRed = new JLabel("Red");
    jtf_red = new JTextField("0", 10);

    rP = new JButton("+");
    rM = new JButton("-");
    rP.addActionListener(this);
    rM.addActionListener(this);
    rP.setPreferredSize(new Dimension(25, 25));
    rM.setPreferredSize(new Dimension(25, 25));

    jpRed.add(jLRed);
    jpRed.add(rP);
    jpRed.add(jtf_red);
    jpRed.add(rM);


    // Setup for Green JPanel (jpGreen)
    jLGreen = new JLabel("Green");
    jtf_green = new JTextField("0", 10);

    gP = new JButton("+");
    gM = new JButton("-");
    gP.addActionListener(this);
    gM.addActionListener(this);
    gP.setPreferredSize(new Dimension(25, 25));
    gM.setPreferredSize(new Dimension(25, 25));

    jpGreen.add(jLGreen);
    jpGreen.add(gP);
    jpGreen.add(jtf_green);
    jpGreen.add(gM);

    // Setup for Blue JPanel (jpBlue)
    jLBlue = new JLabel("Blue");
    jtf_blue = new JTextField("0", 10);

    bP = new JButton("+");
    bM = new JButton("-");
    bP.addActionListener(this);
    bM.addActionListener(this);
    bP.setPreferredSize(new Dimension(25, 25));
    bM.setPreferredSize(new Dimension(25, 25));

    jpBlue.add(jLBlue);
    jpBlue.add(bP);
    jpBlue.add(jtf_blue);
    jpBlue.add(bM);

    // Visibility
    this.setVisible(true);
}

public void actionPerformed(ActionEvent e) {
    int red = Integer.parseInt(jtf_red.getText());
    int green = Integer.parseInt(jtf_green.getText());
    int blue = Integer.parseInt(jtf_blue.getText());

    // PLUS & MINUS, NO DECREMENTS PAST 0 and INCREMENTS PAST 255
    if(e.getSource() == rP)
    {
        red++;
        jtf_red.setText("" + red);

        if (red > 255)
        {
            jtf_red.setText("" + 255);
        }
    }
    else if(e.getSource()  == rM)
    {
        red--;
        jtf_red.setText("" + red);

        if (red < 0)
        {
            jtf_red.setText("" + 0);

        }
    }

    if(e.getSource() == gP)
    {
        green++;
        jtf_green.setText("" + green);

        if (green > 255)
        {
            jtf_green.setText("" + 255);
        }
    }
    else if(e.getSource()  == gM)
    {
        green--;
        jtf_green.setText("" + green);

        if (green < 0)
        {
            jtf_green.setText("" + 0);
        }
    }

    if(e.getSource() == bP)
    {
        blue++;
        jtf_blue.setText("" + blue);

        if (blue > 255)
        {
            jtf_blue.setText("" + 255);
        }
    }
    else if(e.getSource()  == bM)
    {
        blue--;
        jtf_blue.setText("" + blue);

        if (blue < 0)
        {
            jtf_blue.setText("" + 0);
        }
    }       

    // LIMITS (0-255)
    if (red < 0)
    {
        jtf_red.setText("" + 0);
    }
    else if (red > 255)
    {
        jtf_red.setText("" + 255);
    }

    if (green < 0)
    {
        jtf_green.setText("" + 0);
    }
    else if (green > 255)
    {
        jtf_green.setText("" + 255);
    }

    if (blue < 0)
    {
        jtf_blue.setText("" + 0);
    }
    else if (blue > 255)
    {
         jtf_blue.setText("" + 255);
    }

    jpChanging.setBackground(new Color(red, green, blue));
}

}

Any help would be greatly appreciated!

If more context/instruction is required, I have attached my assignment's guidelines. As well as what the program is supposed to look like (my program looks like it and I'm more worried about functionality than the program looking exactly alike).

This is my first time posting so I hope I did everything right! Thank you for your time!


Answer:

I asked classmates how they went about it and I figured it out.

For one, my buttons, my code is bad (I put a segment of it below to highlight my point). I don't know how to go about explaining it but

if(e.getSource() == rP)
    {
        red++;
        jtf_red.setText("" + red);

        if (red < 255)
        {
            jtf_red.setText("" + 255);
        }
    }
    else if(e.getSource()  == rM)
    {
        red--;
        jtf_red.setText("" + red);

        if (red < 0)
        {
            jtf_red.setText("" + 0);

        }

Red gets incremented in the red++; line but then does not check if it is over 255.

The proper way would have been to move the red++; to the if statement inside of

if(e.getSource() == rP)
  {
    if (red < 255)
    {
       red++;
       ...
    }
   }

and so on and so forth for the other buttons.

The solution to my first problem

My JTextFields do not change to 0 if they're outside of the range of (0-255).

I needed to add the ActionListener to the JTextFields after having coded the if statements that would set the JTextFields to 0 if values were entered that weren't inside the range.

The solution to my second problem

The JPanel does not change colors based off what is typed in the JTextFields until one of the buttons is clicked.

With the ActionListener added to both buttons and JTextFields, I created an if statement that checked if the source were the buttons or JTextFields to change the background.

Question:

I need a text field on a label but when i run this code there is no text field on the screen. How can i fix it.

JFrame jf = new JFrame() ;

JPanel panel = new JPanel() ;

JLabel label = new JLabel() ;

JTextField tField = new JTextField("asd" , 10) ;

label.add( tField ) ;
panel.add( label ) ;

jf.setSize( 500,400 ) ;
jf.add( panel ) ;
jf.setVisible(true) ;

Answer:

JLabel's have no default layout manager, and so while your JTextField is being added tot he JLabel, it's not showing because the label has no idea how to show it.

There can be several ways to solve this depending on what you're trying to achieve:

  • Give the JLabel a layout manager, and then add the JTextField to it: but then the JTextField covers the JLabel, its text (if it has any) and its icon (if it has one), not good.
  • Create a JPanel to hold both, and give it an appropriate layout manager: probably a good bet.
  • Add them both to the same JPanel, using a layout manager that can easily place them in association: another good bet. GridBagLayout works well for this.

Don't forget to also call the JLabel's setLabelFor(...) method to associate it tightly with the JTextField, as per the JLabel Tutorial

For example:

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.KeyEvent;
import java.util.HashMap;
import java.util.Map;
import javax.swing.*;

public class GridBagEg {
    private static void createAndShowGui() {
        PlayerEditorPanel playerEditorPane = new PlayerEditorPanel();

        int result = JOptionPane.showConfirmDialog(null, playerEditorPane, "Edit Player",
                JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
        if (result == JOptionPane.OK_OPTION) {
            // TODO: do something with info

            for (PlayerEditorPanel.FieldTitle fieldTitle : PlayerEditorPanel.FieldTitle.values()) {
                System.out.printf("%10s: %s%n", fieldTitle.getTitle(),
                        playerEditorPane.getFieldText(fieldTitle));
            }
        }
    }

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

@SuppressWarnings("serial")
class PlayerEditorPanel extends JPanel {
    enum FieldTitle {
        NAME("Name", KeyEvent.VK_N), SPEED("Speed", KeyEvent.VK_P), STRENGTH("Strength", KeyEvent.VK_T);
        private String title;
        private int mnemonic;

        private FieldTitle(String title, int mnemonic) {
            this.title = title;
            this.mnemonic = mnemonic;
        }

        public String getTitle() {
            return title;
        }

        public int getMnemonic() {
            return mnemonic;
        }
    };

    private static final Insets WEST_INSETS = new Insets(5, 0, 5, 5);
    private static final Insets EAST_INSETS = new Insets(5, 5, 5, 0);
    private Map<FieldTitle, JTextField> fieldMap = new HashMap<FieldTitle, JTextField>();

    public PlayerEditorPanel() {
        setLayout(new GridBagLayout());
        setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createTitledBorder("Player Editor"),
                BorderFactory.createEmptyBorder(5, 5, 5, 5)));
        GridBagConstraints gbc;
        for (int i = 0; i < FieldTitle.values().length; i++) {
            FieldTitle fieldTitle = FieldTitle.values()[i];
            JLabel label = new JLabel(fieldTitle.getTitle() + ":", JLabel.LEFT);
            JTextField textField = new JTextField(10);
            label.setDisplayedMnemonic(fieldTitle.getMnemonic());
            label.setLabelFor(textField);
            gbc = createGbc(0, i);
            add(label, gbc);
            gbc = createGbc(1, i);
            add(textField, gbc);

            fieldMap.put(fieldTitle, textField);
        }
    }

    private GridBagConstraints createGbc(int x, int y) {
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = x;
        gbc.gridy = y;
        gbc.gridwidth = 1;
        gbc.gridheight = 1;

        gbc.anchor = (x == 0) ? GridBagConstraints.WEST : GridBagConstraints.EAST;
        gbc.fill = (x == 0) ? GridBagConstraints.BOTH : GridBagConstraints.HORIZONTAL;

        gbc.insets = (x == 0) ? WEST_INSETS : EAST_INSETS;
        gbc.weightx = (x == 0) ? 0.1 : 1.0;
        gbc.weighty = 1.0;
        return gbc;
    }

    public String getFieldText(FieldTitle fieldTitle) {
        return fieldMap.get(fieldTitle).getText();
    }

}

Which displays as

Note that the JLabels have underlines on mnemonic chars, chars that when pressed in alt-key combination will bring the focus to the JTextField that the JLabel was linked to via, setLabelFor(...), and is caused by this code:

FieldTitle fieldTitle = FieldTitle.values()[i]; // an enum that holds label texts
JLabel label = new JLabel(fieldTitle.getTitle() + ":", JLabel.LEFT); // create JLabel
JTextField textField = new JTextField(10);  // create JTextField

// set the label's mnemonic -- brings focus to the linked text field
label.setDisplayedMnemonic(fieldTitle.getMnemonic());   

// *** here we *link* the JLabel with the JTextField
label.setLabelFor(textField);  

Question:

My JTextField isn't showing on, only the paintComponent

public static final int WIDTH = 800;
public static final int HEIGHT = 600;

private JTextField txt;

public Painel(){
    super();
    setFocusable(true);
    setPreferredSize(new Dimension(WIDTH, HEIGHT));
    setLayout(new FlowLayout());
    txt = new JTextField();
    txt.setBounds(400, 300, 50, 20);
}

Answer:

You have to set the number of columns in your text field or give a default text to it. The following code should work for you. I have updated the previous answer to use the Gridbag layout. However still you need to set the number of columns in JTextField to render it.

    public class TestFrame extends JFrame {

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

    private TestFrame() throws HeadlessException {
        super();

        this.setLocationByPlatform(true);
        JPanel contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        GridBagLayout gbl_contentPane = new GridBagLayout();
        gbl_contentPane.columnWidths = new int[] { 100, 0 };
        gbl_contentPane.rowHeights = new int[] { 0, 0, 0 };
        gbl_contentPane.columnWeights = new double[] { 0.0, 1.0, Double.MIN_VALUE };
        gbl_contentPane.rowWeights = new double[] { 0.0, 0.0, Double.MIN_VALUE };
        contentPane.setLayout(gbl_contentPane);

        JTextField textField = new JTextField();
        GridBagConstraints gbc_textField = new GridBagConstraints();
        gbc_textField.insets = new Insets(0, 0, 5, 0);
        gbc_textField.fill = GridBagConstraints.HORIZONTAL;
        gbc_textField.gridx = 1;
        gbc_textField.gridy = 0;
        contentPane.add(textField, gbc_textField);
        textField.setColumns(10);

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

Hope this helps. Happy coding !

Question:


Answer:

You can declare your JTextField globally and then you initialize it inside your constructor. Now you have access to your variable in your methods too.

public class MyGUI extends JPanel
{
  private JTextField betText;

  public MyGUI(){
     //other operations
     betText = new JTextField("");
  }

  public void test(){
     String a = betText.getText();
  }
 }