1
import javax.swing.*;
import java.awt.event.*;
import java.util.Scanner;

@SuppressWarnings("unused")
public class Fun {
    @SuppressWarnings({"static-access", "resource"})
    public static void main(String[] args) {
        JFrame f = new JFrame("The Gamer Zone");
        //set size and location of frame
        f.setSize(390, 300);
        f.setLocation(100, 150);
        //make sure it quits when x is clicked
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //set look and feel
        f.setDefaultLookAndFeelDecorated(true);
        JLabel labelM = new JLabel("Are you an epic gamer? (true,false) ");
        labelM.setBounds(50, 50, 250, 30);
        JTextField Text = new JTextField();
        //set size of the text box
        Text.setBounds(50, 100, 200, 30);
        //add elements to the frame
        f.add(labelM);
        f.add(Text);
        f.setLayout(null);
        f.setVisible(true);
        String answer1 = Text.getText();
        Scanner sc = new Scanner(answer1);
        int x = 0;
        while (x < 1) {
            try {
                if (sc.next() == "true") {
                    f.remove(labelM);
                    x++;
                }
            } catch (Exception e) {
                System.out.println("Something went wrong");
            }
        }
    }
}

I am trying to get it to remove LabelM when the input in the jtext field is "true." I am just trying to learn how JFrames work, and this is my first time working with one. Is there a better way to scan from a JFrame?

David Kroukamp
  • 36,155
  • 13
  • 81
  • 138
  • 1
    In Java you done use `==` to compare objects rather use `.equals` see [here](https://stackoverflow.com/questions/7520432/what-is-the-difference-between-and-equals-in-java) for more – David Kroukamp Dec 10 '20 at 17:07
  • `if (sc.next() == "true")` -> [How do I compare strings in Java?](https://stackoverflow.com/q/513832) – Pshemo Dec 10 '20 at 17:10
  • Usually, there's a submit JButton on the JPanel. The submit button lets the application know that the user is finished typing. The ActionListener of the submit button gets the text from the JTextFields and processes the information. The Oracle tutorial, [Creating a GUI With JFC/Swing](https://docs.oracle.com/javase/tutorial/uiswing/index.html) will take you through all the steps of creating Swing GUIs. Skip the Netbeans section. – Gilbert Le Blanc Dec 10 '20 at 17:11
  • @GilbertLeBlanc *Usually, there's a submit JButton on the JPanel* I think thats up to how somebody want to implement their UI as opposed to a rule – David Kroukamp Dec 10 '20 at 17:27
  • 1
    Thank you for all of the help with solving this problem!! – ARRON STANLEY Dec 10 '20 at 19:34
  • @ARRONSTANLEY glad to be of help if my answer has solved your problem dont forget to mark it as solved by checking the tick next to the answer to show others it is solved. Read [What should I do when someone answers my question?](https://stackoverflow.com/help/someone-answers) for more information – David Kroukamp Dec 10 '20 at 19:53

1 Answers1

0

You would want to use a DocumentListener which will fire off methods whenever the text of the field is changed. Currently your example gets the text once (after showing the JFrame and that will never change as well as you are using the wrong method/operator to compare string objects in java you should use equals, or a variant like contains etc see here or here for more.

Also some other points (I probably sound like a broken record):

  1. Don't use a null/AbsoluteLayout rather use an appropriate LayoutManager
  2. Don't call setBounds() or setSize() on components, if you use a correct layout manager this will be handled for you
  3. Call JFrame#pack() before setting the frame to visible when using a LayoutManager
  4. All Swing components should be called on the EDT via SwingUtilities.invokeLater

Here is an example which simply hides or shows the JLabel when the word true is found or not found regardless of case in the JTextField:

enter image description here

TestApp.java:

import java.awt.BorderLayout;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

public class TestApp {

    public TestApp() {
        createAndShowGui();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(TestApp::new);
    }

    private void createAndShowGui() {
        JFrame frame = new JFrame("TestApp");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
        panel.setBorder(new EmptyBorder(20, 20, 20, 20));
        JLabel labelM = new JLabel("Are you an epic gamer? (true,false) ");
        JTextField textField = new JTextField();
        
        textField.getDocument().addDocumentListener(new DocumentListener() {
            @Override
            public void changedUpdate(DocumentEvent e) {
                checkForInput();
            }

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

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

            public void checkForInput() {
                if (textField.getText().toLowerCase().equals("true")) {
                    labelM.setVisible(false);
                } else {
                    labelM.setVisible(true);
                }
            }
        });

        panel.add(labelM, BorderLayout.NORTH);
        panel.add(textField, BorderLayout.CENTER);

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

}

The magic happens in the checkForInput called by the DocumentListener which is attached to the JTextField

public void checkForInput() {
    if (textField.getText().toLowerCase().contains("true")) {
        labelM.setVisible(false);
    } else {
        labelM.setVisible(true);
    }
}

If you wanted to add or remove the label as opposed to setting its visibility simply switch it out with panel.remove(labelM) or panel.add(labelM) respectively

David Kroukamp
  • 36,155
  • 13
  • 81
  • 138