Reputation: 7571
I am trying to build a window with one picture that covers up the screen. The picture is a JLabel and the window is a JFrame. After trying countless ways and looking up multiple tutorials for hours, I have not figured out how to do this. I agree, this is a very simple question, but I simply do not understand how I can approach this problem. Here is my code I have tried(I commented out some things that I tried earlier):
package Buttons;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.awt.GridLayout;
public class Mewindow extends JFrame {
private JFrame mewindow;
private JLabel mepic = new JLabel(new ImageIcon("me.png"));
public Mewindow() {
super("Here is a picture of ME!");
mewindow.setLayout(new GridLayout(1, 0, 0, 0));
// Icon me = new ImageIcon(getClass().getResource("me.png"));
add(mepic);
mewindow.setVisible(true);
mewindow.setSize(250, 250);
mewindow.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
}
Thank you so much for the time you are taking for reading this, I really appreciate the effort you are putting into helping a fellow programmer!
Upvotes: 0
Views: 36
Reputation: 347334
You have no main method, so unless you're creating the class from another class, it won't run...
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
Mewindow frame = new Mewindow();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
Now, you will run into a NullPointerException
, because mewindow
is not initialised, but, you don't actually need it, because you're using the values within the constructor of the class, so you would end up with a StackOverflowException
if you tried to intiialise it ... but it doesn't make sense to use it anyway...
public class Mewindow extends JFrame {
private JLabel mepic
public Mewindow() {
super("Here is a picture of ME!");
setLayout(new GridLayout(1, 0, 0, 0));
mepic = new JLabel(new ImageIcon(getClass().getResource("me.png")));
add(mepic);
setVisible(true);
setSize(250, 250);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
}
Now your code assumes that me.png
is stored within the same package as the Mewindow
, just beware of that.
And, the resulting code actually running (replace with my own picture)
Don't extend directly from JFrame
, use a JPanel
instead and then add that to an instance of JFrame
, your code will be more re-usable
Upvotes: 2