0

I tried to put a text field and a button and label using Swing in Java.I successfully added the label and the button but if I try to add the text field, the hole frame is blank, so nothing shows up, not even the button or the label. What I am doing wrong?

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

public class SwingPartOne extends JFrame {

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

public SwingPartOne(){
    this.setSize(800,800);
    this.setLocationRelativeTo(null);
    this.setVisible(true);

    Toolkit tk = Toolkit.getDefaultToolkit();

    Dimension dim = tk.getScreenSize();

    int xPos = (dim.height / 2) - (this.getHeight() / 2);
    int yPos = (dim.width / 2) - (this.getWidth() / 2);

    this.setResizable(false);

    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    this.setTitle("First Jframe");


    JPanel thePanel = new JPanel();

    JLabel label1 = new JLabel("Some random text .");

    label1.setText("New text.");

    label1.setToolTipText("Surprize!");

    JButton thebutton1 = new JButton("BOOM!");

    JTextField textField = new JTextField("Some text" , 15);
    textField.setColumns(5);
    textField.setSize(200,200);
    textField.setText("Some random text");

    thePanel.add(label1);
    thePanel.add(textField);
    thePanel.add(thebutton1);
    this.add(thePanel);






}
}
JohnnyOnPc
  • 386
  • 1
  • 5
  • 18
  • 2
    Call `this.setVisible(true)` at the end of the constructor so it can `validate`. Also, some other notes: 1) `textField.setSize(200,200);` won't do much, override it's `getPreferredSize` method instead (only if you really need to). 2) To center the frame, you can also simply call `setLocationRelativeTo(null)`. There's no need to calculate `xPos` and `yPos` – Lukas Rotter Apr 28 '16 at 14:52
  • [Beware](http://stackoverflow.com/a/12532237/230513) `setResizable(false)`. – trashgod Apr 28 '16 at 15:47

1 Answers1

1

I resolved the problem by putting this.setVisible(true) at the end by the LuxxMiner`s help .

> Call this.setVisible(true) at the end of the constructor so it can validate. Also, some other notes: 1) textField.setSize(200,200); won't do much, override it's getPreferredSize method instead (only if you really need to). 2) To center the frame, you can also simply call setLocationRelativeTo(null). There's no need to calculate xPos and yPose

JohnnyOnPc
  • 386
  • 1
  • 5
  • 18