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!
Problem #1...
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);
}
});
}
Problem #2...
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)
Suggestions...
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
Related
This question already has answers here:
Using Java pack() method
(3 answers)
Closed 7 years ago.
I was messing with some code and came across the pack method which is suppose to find the "optimum" size for a window. But when I tried to out it simply made a window as small as possible even though I drew a circle before calling pack(). Why is that? What elements does pack() look for? I also frequently have found code that uses both pack() and setSize() which Oracle explicitly says not to do. What is the point since they both set size?
Here is that part of the code incase it was me who did something wrong:
public void paint(Graphics g) {
super.paint(g);
g.fillOval(x, y, 30, 30);
}
public static void main(String[] args) throws InterruptedException {
JFrame frame = new JFrame("Extreme Pong");
Game game = new Game();
frame.add(game);
frame.pack();
}
Edit:
Apparently I either was not clear to most of you since the linked answer to the "duplicate" did not answer my question. The mad programmer did answer my question, so thank you to you.
pack makes use of the layout manager API and "asks" the frame's contentPane for it's preferredSize, this allows pack to "pack" the windows decorations around the content. You have to remember, a windows size includes the windows decorations, so a window of 800x600 will have a viewable which is noticeably smaller
If you add a component to the frame whose size is undefined (in the case of JComponent and JPanel which return a preferredSize of 0x0, the frame will be packed to its smallest possible size, not really what you want.
So, for example, something like...
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.fillOval(10, 10, 30, 30);
g2d.dispose();
}
}
}
generates a window of 200x222 on my Mac, but the TestPane will be 200x200
You might also like to have a look at Laying Out Components Within a Container, Painting in AWT and Swing and Performing Custom Painting for some more details
Using .pack() and .setSize() no make sense, all depend which one is last one in the code but i recommendable use:
frame.setMinimumSize(new Dimension(x,y));
And please do not forget to add :
frame.setVisible(true);
I want to create menu buttons in Screen class and add menu to frame then. I don't know what is wrong with it. How to create buttons in other class and add it to to the frame?
My frame class:
import java.awt.*;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;
public class Start extends JFrame {
public static String title = "Bozenka";
public static Dimension size = new Dimension(700,500);
public static String backgroundPath = "/home/alpha_coder/Eclipse/Bozenka/images/bg.jpg";
public Start(){
setTitle(title);
setSize(size);
setLayout(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setLayout(null);
setResizable(false);
initialization();
}
public void initialization(){
Screen screen = new Screen();
screen.setBounds(20, 20, 660, 60);
add(screen);
try {
setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File(backgroundPath)))));
setBackground(Color.WHITE);
} catch (IOException e) {
System.out.println("Image doesn't exist");
}
setVisible(true);
}
public static void main(String[] args){
Start start = new Start();
}
}
The class where I want to create a menu:
import java.awt.*;
import javax.swing.*;
public class Screen extends JPanel{
public JButton test;
public Screen(){
setBackground(Color.pink);
test = new JButton("test");
test.setBounds(2, 2, 40, 10);
}
}
Most important: get rid of setLayout(null) and setBounds(...) as that will lead to an extremely difficult to create and adjust GUI. Learn and use the layout managers.
Create your JButtons in your new class, Screen
add them to this, the Screen JPanel but first give it a decent layout manager, such as a GridLayout,
In another class, create an instance of your JFrame class and an instance of the Screen object, and add the Screen JPanel to your JFrame's contentPane in whatever desired location you want, be it BorderLayout.CENTER or one of the other locations.
Again, most important: google and study the layout manager tutorial. Here's the link.
Note, a major problem with your current code is that you add your JButton to nothing. It needs to be added to Screen, to this for your code to work in any way.
I want to show JLabel but want to hide JFrame border and other lower level containers like JPanel.
It just JLabel displayed on the screen.
I tried window transparency but following piece of code hides everything if trying to work with window opacity.
On decreasing windowOpacity , even JLabel becomes blurred. I tried with JPanel as well but couldn't get exact output.
I want this behaviour in jdk1.6 only
I want the JLabel content to be visible properly without any opacity impact but backbround must be purely transparent.
public class TEST {
public static void main(String[] args) {
JFrame frame = new JFrame("Sanjaal Corps - Windows On Top Demo!");
frame.setSize(400, 100);
frame.setLocation(100, 150);
com.sun.awt.AWTUtilities.setWindowOpacity(frame,0.4f);
frame.setUndecorated(true);
frame.add(new JLabel("TESTING"));
frame.setAlwaysOnTop(true);
frame.setVisible(true);
}
}
I tried with solution provided
http://www.dreamincode.net/forums/topic/140041-make-a-jpanel-transparent-to-see-the-desktop-behind/
But the problem here is if we minimize or maximize the window , then a constant color being set, So found its not the best solution or may say the Perfect one.
Assuming I understand your requirements correctly...
I typically add a transparent panel to the Window. This means that, generally, the transparency properties of the Window don't then effect the child components, for example...
Generally speaking, there are now two ways to make a window transparent.
Under Java 7, you simply make it's background color transparent.
Under Java 6 (update 10+), you need to use the unofficial com.sun.AWTUtilities class
...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Window;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.lang.reflect.Method;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.LineBorder;
public class TransparentWindow02 {
public static void main(String[] args) {
new TransparentWindow02();
}
public TransparentWindow02() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setUndecorated(true);
setOpaque(frame, false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setOpaque(false);
setLayout(new BorderLayout());
setBorder(new LineBorder(Color.RED));
JLabel label = new JLabel("Click me if you can see me");
label.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
SwingUtilities.windowForComponent(TestPane.this).dispose();
}
});
add(label);
}
}
public static void setOpaque(Window window, boolean opaque) {
String version = System.getProperty("java.runtime.version");
if (version.startsWith("1.7")) {
window.setBackground(new Color(0, 0, 0, 0));
} else {
try {
Class<?> awtUtilsClass = Class.forName("com.sun.awt.AWTUtilities");
if (awtUtilsClass != null) {
Method method = awtUtilsClass.getMethod("setWindowOpaque", Window.class, boolean.class);
method.invoke(null, window, opaque);
}
} catch (Exception exp) {
exp.printStackTrace();
}
}
}
}
Assuming you want to show the foreground, of the label (nothing else) that is its text/icon, you would set the frame's opacity to false:
com.sun.awt.AWTUtilities.setWindowOpaque(frame, false);
The usual caveat against using com.sun.** classes, which unfortunately is the only way to reach transparent windows prior to java7
I would like to create a simple GUI in Java. I know the basics of creating JLabel, etc. However, I cannot find why my JLabel is not displayed on the screen. Here is my code:
package test;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.*;
import javax.swing.*;
public class A1Panel extends JPanel implements ActionListener {
JLabel firstInt;
public void init() {
makeComponents();
makeLayout();
}
private void makeComponents() {
firstInt = new JLabel("First argument");
firstInt.setFont(new Font("Helvetica", Font.BOLD, 16));
firstInt.setBackground(Color.lightGray);
firstInt.setVisible(true);
firstInt.setHorizontalAlignment(SwingConstants.CENTER);
}
private void makeLayout() {
add(firstInt);
}
public void actionPerformed(ActionEvent e) {
}
}
I then add my JPanel to my JFrame using a different class called GUI:
import test.A1Panel;
public class GUI {
public static void main(String[] args) {
JFrame frame = new JFrame("Testing GUI");
frame.setLayout( new GridLayout(1,3));
JPanel panel = new A1Panel();
panel.setBorder( BorderFactory.createRaisedBevelBorder() );
frame.add( panel);
frame.setSize(800,600);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.pack();
}
}
When I hit compile, what I get is a simple frame with three empty panels. I do not understand why my JLabel is not in the first panel since I have added it to my frame. Am I missing something?
The frame is not empty, the panel is. Nowhere in your code do I see a call to the methods init() or makeComponents(). In fact, I would turn your init() method into a constructor, like so:
public A1Panel() {
makeComponents();
makeLayout();
}
Another alternative to this would be to call panel.init() after declaring JPanel panel = new A1Panel()
After you instance A1Panel, you haven't called A1Panel.init()
I would suggest removing init() and adding all the code to the constructor of A1Panel. If, however, you wanted to keep the init() function, you would want to call it after JPanel panel = new A1Panel()
The code to add the label was not actually called in the main, was it? So look carefully, when is init actually called?
Look at the
private void makeLayout()
method.
If I replace public void init() by A1Panel(), it does the job. Thank you for your help.
I am trying to learn java and i am practicing with a simple program with 2 simple buttons. Here is my code :
import javax.swing.*;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("Askhsh 3");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ColorJPanel application = new ColorJPanel();
frame.add(application);
frame.setSize(500,500);
frame.setVisible(true);
}
}
And the class ColorJPanel:
import java.awt.*;
import javax.swing.*;
public class ColorJPanel extends JPanel{
public void paintComponent(Graphics g)
{
super.paintComponent(g);
this.setBackground(Color.WHITE);
JButton arxikopoihsh = new JButton("Αρχικοποίκηση");
JButton klhrwsh = new JButton("Κλήρωση");
add(arxikopoihsh);
add(klhrwsh);
this.revalidate();
this.repaint();
}
}
As you can see the only thing i want to do for now is to place 2 simple buttons that do nothing! Here is my output:
http://imageshack.us/photo/my-images/847/efarmogh.jpg/
When i am running the application i am seeing the buttons filling the window!
Note that if i remove the "this.revalidate();" command i have to resize the window to see the buttons !
Thanks very much for your time :)
Don't add components in paintComponent. This method is for painting only, not for program logic or to build GUI's. Know that this method gets called many times, often by the JVM and most of the time this is out of your control, and also know that when you ask for it to be called via the repaint() method, this is only a suggestion and the paint manager may sometimes choose to ignore your request. The paintComponent method must be lean and fast as anything that slows it down will slow down the perceived responsiveness of your application.
In your current code, I don't even see a need to have a paintComponent method override, so unless you need it (if doing for instance custom painting of the component), I suggest that you get rid of this method (and the calls to repaint and revalidate). Instead, add your components in the class's constructor and make sure to pack your top level container after adding components and before calling setVisible(true). Most important -- read the Swing tutorials as this is all covered there.
e.g.,
Main.java
import javax.swing.*;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("Askhsh 3");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ColorJPanel application = new ColorJPanel();
frame.add(application);
frame.pack();
frame.setVisible(true);
}
}
ColorJPanel.Java
import java.awt.*;
import javax.swing.*;
public class ColorJPanel extends JPanel{
public static final int CJP_WIDTH = 500;
public static final int CJP_HEIGHT = 500;
public ColorJPanel() {
this.setBackground(Color.WHITE);
JButton arxikopoihsh = new JButton("Αρχικοποίκηση");
JButton klhrwsh = new JButton("Κλήρωση");
add(arxikopoihsh);
add(klhrwsh);
}
// let the component size itself
public Dimension getPreferredSize() {
return new Dimension(CJP_WIDTH, CJP_HEIGHT);
}
}