2

This is my code

import javax.swing.*;
import java.awt.*;
import java.awt.Graphics;
public class Test extends JFrame{
    private JButton by;
    private JButton bn;
    JLabel startQuestion;

    public Test() {
        JPanel p = new JPanel();
        by = new JButton("Yes");
        bn = new JButton("No");
        startQuestion = new JLabel("Would you like to start?");
        p.setLayout(null);
        by.setBounds(180, 250, 70, 45);
        bn.setBounds(250, 250, 70, 45);
        startQuestion.setLocation(195, 240);
        p.add(by);
        p.add(bn);
        add(startQuestion);
        add(p);
        setDefaultCloseOperation(3);
        setSize(500, 500);
        setVisible(true);
    }

    public static void main(String...args) {
        new Test();
    }
}

There are no syntax errors, however my Jlabel is not added (the buttons work fine). I do not want to change the layout from null, as I want to be able to define the positions of the buttons and labels. Does anyone know why this isn't working?

Riddhesh Sanghvi
  • 1,218
  • 1
  • 12
  • 22
  • 2
    You have not run your code on the EDT. You must read the [tutorial on writing Swing applications](https://docs.oracle.com/javase/tutorial/uiswing/start/compile.html) and specifically understand what the EDT is and why it is imperative to execute all GUI code on it. – Boris the Spider Oct 12 '15 at 14:54

2 Answers2

2

This question is similar to JLabel won't show with JPanel.setLayout(null). Why?

To answer it here, add a line like this:

    startQuestion.setBounds(150, 150, 200, 20);
Community
  • 1
  • 1
OliCoder
  • 1,370
  • 10
  • 25
  • Sincere apologies for the repetition. I did not realize that the null layout had a default zero size. Thanks a lot! – Rahul Mukherji Oct 12 '15 at 15:09
  • 1
    And I would add as stated in the link you provided, **don't** use `null` layout, instead use a [Layout Manager](http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html) – Frakcool Oct 12 '15 at 15:38
0
import javax.swing.*;
import java.awt.*;
import java.awt.Graphics;
public class Test extends JFrame{
    private JButton by;
    private JButton bn;
    JLabel startQuestion;
        public Test() {
        JPanel p = new JPanel();
        by = new JButton("Yes");
        bn = new JButton("No");
        startQuestion = new JLabel("Would you like to start?");
        //p.setLayout(null);
        by.setBounds(180, 250, 70, 45);
        bn.setBounds(250, 250, 70, 45);
        startQuestion.setLocation(195, 240);
        p.add(by);
        p.add(bn);
        add(startQuestion);
        add(p);
        setDefaultCloseOperation(3);
        setSize(500, 500);
        setVisible(true);
        }
        public static void main(String...args) {
        new Test();
    }
}

Note:

you need to comment setlayout(null);

Kumaresan Perumal
  • 1,926
  • 2
  • 29
  • 35