-1

I have problem with adding Label by constructor, when I make it by method it's no problem

private void addLabel() {
    System.out.println("asd");
    JLabel label = new JLabel("asd");
    label.setBounds(10, 40, 100, 25);
    add(label);
    repaint();
    validate();
    System.out.println("asd2");
}

But when i try to do this same by new class and constructor i doesn't work...

Main frame:

public class Frame extends JFrame {

JButton button = new JButton("new");
AddButton button2 = new AddButton();

public Frame() {
    setLayout(null);
    setSize(400, 500);
    setDefaultCloseOperation(EXIT_ON_CLOSE);

    button.setBounds(40, 10, 50, 25);
    add(button);


    button2.setBounds(40, 40, 100, 25);
    add(button);
}

public static void main(String[] args) {
    Frame ap = new Frame();
    ap.setVisible(true);
}

AddButton class:

public class AddButton extends JPanel {
JLabel label = new JLabel("asd");

public AddButton() {
    label.setBounds(10, 40, 100, 25);
    add(label);
    repaint();
    validate();

  }

}

Ok i got it, I tried to add "button" two times istead button and button2 :D

Gumovvy Steven
  • 101
  • 2
  • 10
  • 1
    `label.setBounds(10, 40, 100, 25);` Java GUIs have to work on different OS', screen size, screen resolution etc. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). – Andrew Thompson Mar 05 '15 at 08:05
  • Add declaration of JLabel to conctructor too. – Anptk Mar 05 '15 at 08:09
  • Please give more code for context. And what does "doesn't work" mean? Please be specific. Do you get an exception? If so, post the stack trace. Please create a [Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve). – dbank Mar 05 '15 at 08:09

2 Answers2

3

Your constructor doesn't make sense, that's not how you should use constructors - constructors are used to create an instance of a class.

When you write

AddButton button2 = new AddButton();

then button2 is of type AddButton, and add doesn't accept this type of object.

Maroun
  • 94,125
  • 30
  • 188
  • 241
0

You can Edit like this

public class AddButton extends JPanel {
JLabel label; 

public AddButton() {
label=new JLabel("asd");
label.setBounds(10, 40, 100, 25);
add(label);
repaint();
validate();

}

}
Anptk
  • 1,125
  • 2
  • 17
  • 28