Search code examples
javaswingjtextfieldlayout-managernull-layout-manager

Can't add a TextField to Interface in Java


I can`t add this TextField to the interface, the resulting window is plain without any details on it , altough I tried a lot to find where the problem is.. here is the code: import java.awt.ComponentOrientation; import java.awt.Font;

import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.UIManager;

public class Calculator extends JFrame {
    private JTextField display;

    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            System.out.println("Could not load system interface\n");
        }
        new Calculator();
    }

    public Calculator() {
        super("Calculator");
        sendDisplay();
        sendUI(this);
    }

    private void sendDisplay() {
        display = new JTextField("0");
        display.setBounds(10, 10, 324, 50);
        display.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
        display.setEditable(false);
        display.setFont(new Font("Arial", Font.PLAIN, 30));
        display.setVisible(true);
        add(display);
    }

    private void sendUI(Calculator app) {
        app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        app.setVisible(true);
        app.setSize(400, 600);
        app.setLayout(null);
        app.setResizable(false);
        app.setLocationRelativeTo(null);
    }
}

I would be grateful if someone could find the problem


Solution

  • Make setVisible(true) is the last statement of your sendUI method

    private void sendUI(Calculator app) {
        app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        app.setSize(400,600);
        app.setLayout(null);
        app.setResizable(false);
        app.setLocationRelativeTo(null);
    
        app.setVisible(true);               
    }
    

    Good Practice

    • Avoid using Absolute Positioning (null layout).