Reputation: 123
I am attempting to write a simple program for now but the actual JButton is not appearing for some reason, here is my code below.
import javax.swing.*;
import java.awt.*;
public class Test extends JFrame {
public static void main(String[] args) {
JFrame window = new JFrame("Shoes");
window.setDefaultCloseOperation(EXIT_ON_CLOSE);
window.setResizable(true);
window.setSize(400,500);
window.setVisible(true);
window.setLocationRelativeTo(null);
JButton welcome = new JButton("Click here");
welcome.setLocation(100,100);
welcome.setVisible(true);
// doesn't work, but is there another way to make it so?
//add(welcome);
}
}
Upvotes: 1
Views: 110
Reputation: 1482
you extended JFrame
yet in your code you use another JFrame
that you created JFrame window = new JFrame("Shoes");
, this is why add(welcome);
is not working for you... since its trying to add the JButton
to this
instance of your Test
class
(which is not visible) and not the window
you have created.
You have 2 ways of solving this:
The first one as mentioned by @Hackerdarshi is to add the button to the window
you created. like : window.add(welcome);
The second way is to make use of your extension of the JFrame
class
(otherwhise why extend at all) and call all the methods on the window
using this
instance of your Test
class
:
public Test() {
super("Shoes");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(true);
setSize(400,500);
setVisible(true);
setLocationRelativeTo(null);
JButton welcome = new JButton("Click here");
welcome.setLocation(100,100);
welcome.setVisible(true);
// this will work since `this` instance is set to visible
add(welcome);
}
NOTE that to set the buttons location like: welcome.setLocation(100,100);
you should use a null
Layout
Upvotes: 0
Reputation: 1160
I would also like to mention that the reason the code on your commented out section didnt work, is because you're extending JFrame.
When you extend JFrame, you inherit all of the methods JFrame has. That includes add()
. However, when you use this.add()
you are adding the compononent to you Test Object (which is also a JFrame), not your window
JFrame.
To add to the window you would use window.add(welcome);
To stop these weird confusions in the future I would also change
public class Test extends JFrame
to
public class Test
Upvotes: 2
Reputation: 6077
You created the button, but did not add it.
You have to add it to the window
. Simply using add(welcome)
will add it to your frame, which you extend, but not to the window
in which you want it to show.
Instead of:
add(welcome);
Just do:
window.add(welcome);
Upvotes: 2