Displaying a JLabel in front of another JLabel - java

Game(){
JFrame frame = new JFrame("Display Image");
JPanel panel = (JPanel)frame.getContentPane();
frame.setSize(1000,625);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel();
label.setIcon(new ImageIcon("C:/Users/Ragnar/Desktop/GameBoard.png"));
panel.add(label);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
So i have this constructor ,and i want to add some new JLabels with Images,but i want them to be displayed on top of first image which is the image of the first jLabel label.Can anyone guide me how to achieve this please?I tryed to add them as usually but they are displayed behind the label.

If you have a background image and you want to display the JLabel on top of the background image, you can use a JPanel to hold the background image, then add your JLabel.
Usually if you try to let 2 JLabel overlap each other it won't succeed due to the default layout manager used by the container (such as FlowLayout in JPanel or BorderLayout in JFrame).
If you really want to let them over lap, you will have to set the layout as null. But they may introduce new problems as you lose control over the appearance of your components.
Hence, in cases like this I would usually go for custom painting and draw the images you want in any particular order you are interested in.
For example: How to create a background and foreground image which overlaps?

If you are working with eclipse, and you have installed the windowbuilder plugin you can use the graphical editing view.
Within this view use the contextual menu to order the elements.

What worked for me was, when adding the components with the method add(component), adding them in order from front to back. In the following example I add a lot of components to a JFrame, and the last one to be added is the wallpaper, so it stays at the background.
import java.awt.Image;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class LogIn extends JFrame implements ActionListener{
public static JFrame operador;`enter code here`
private JLabel logo, foot, mensaje, wallpaper;
private JTextField fldUser;
private JPasswordField fldPass;
private JButton entrar;
private int ancho =400, largo= 530;
public static String user="", pass="", name;
public LogIn() {
setLayout(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(ancho,largo);
setResizable(false);
setTitle("Acceso al sitema");
setLocationRelativeTo(null);
setIconImage(getIconImage());
fldUser = new JTextField();
fldUser.setHorizontalAlignment(JTextField.CENTER);
fldUser.setBounds(125,320,150,25);
fldUser.setBackground(new Color(50,50,255));
fldUser.setForeground(Color.WHITE);
fldUser.setBorder(new SoftBevelBorder(BevelBorder.LOWERED));
add(fldUser);
fldPass = new JPasswordField();
fldPass.setHorizontalAlignment(JTextField.CENTER);
fldPass.setBounds(125,360,150,25);
fldPass.setBackground(new Color(50,50,255));
fldPass.setForeground(Color.WHITE);
fldPass.setBorder(new SoftBevelBorder(BevelBorder.LOWERED));
add(fldPass);
mensaje= new JLabel();
mensaje.setBounds(0,390,ancho,15);
mensaje.setForeground(Color.RED);
mensaje.setHorizontalAlignment(SwingConstants.CENTER);
add(mensaje);
entrar =new JButton("Entrar");
entrar.setBounds(125,410,150,40);
entrar.setForeground(new Color(50,50,255));
//entrar.setBorder(new SoftBevelBorder(BevelBorder.RAISED));
entrar.addActionListener(this);
add(entrar);
logo = new JLabel();
logo.setBounds(50,0,300,300);
ImageIcon imgLogo= new ImageIcon("src/images/DS.png");
Icon iconoLogo = new ImageIcon(imgLogo.getImage().getScaledInstance(logo.getWidth(),logo.getHeight(), Image.SCALE_DEFAULT));
logo.setIcon(iconoLogo);
foot = new JLabel("Desarrollado por Gabriel Santos");
foot.setBounds((ancho-200)/2,largo-60,200,30);
//When JLabels overlap, the ones that come to the front are the first to be added to the window.
add(foot);
add(logo);
wallpaper = new JLabel();
wallpaper.setBounds(0,0,window.getWidth(),window.getHeight());
ImageIcon img = new ImageIcon("src/images/wallpaperPrincipal.jpg");
Icon icono = new ImageIcon(img.getImage().getScaledInstance(this.getWidth(),this.getHeight(), Image.SCALE_DEFAULT));
wallpaper.setIcon(icono);
add(wallpaper);
setVisible(true);
}
}

Related

setting location of JTextArea not working

I cannot figure out how to set the location of the text area. Here is my code. Not sure what is not working, obviously JTextArea is not as simple as setting the location like a button.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class BackgroundImageJFrame extends JFrame {
JButton b1;
JLabel l1;
public BackgroundImageJFrame() {
setTitle("Background Color for JFrame");
setSize(1000, 1000);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
/*One way-----------------*/
setLayout(new BorderLayout());
JLabel background = new JLabel(new ImageIcon("background-landing.png"));
add(background);
background.setLayout(new FlowLayout());
l1 = new JLabel("Here is a button");
b1 = new JButton("I am a button");
JTextArea t1 = new JTextArea("enter username", 10, 20);
t1.setLocation(30, 30);
background.add(l1);
background.add(b1);
background.add(t1);
}
public static void main(String args[]) {
new BackgroundImageJFrame();
}
}
obviously JTextArea is not as simple as setting the location like a button.
You tried to create a label with the text "Here is a button" and a button with the text "I am a button"
You button is not displayed either so that comment doesn't make sense.
The issue is that you are adding components to a JLabel. By default a JLabel does not display child components since it does not have a layout manager.
You will be able to add components to the label by setting a layout manager:
JLabel background = new JLabel(...);
background.setLayout( new FlowLayout() );
Read the section from the Swing tutorial on Layout Managers for more basics and working example of using layout managers. The tutorial code will also show you how to better structure your class so you follow Swing guidelines.
You can also check out: Background Panel for a possible alternate solution.

Layout Problem in Java - set a 20%opaque Panel on Bottom of JFrame

Well, actually I have a Layout problem in java Swing. I simply want to add a JPanel on the bottom of a Frame - a coding snipplet that might be done with every web based language in about 5 Minutes. Not so in Java. I tried to add a jPanel to a jFrame, that Contains a jContentPane, set the size of the jPanel to what I need and to repaint and revalidate the jFrame, as well as setting the LayOutManager to null.
Java shows me in this case a full-width jPanel, that fills my whole jFrame.
Therefore I tried another approach: I divided my jPanel in a fully transparent jPanel on top and a 20%opaque jPanel on the bottom. Still it didn't work out as expected.
Since then I tried to resize the child jPanels of my new Panel and the Panel as well and tried to repaint and revalidate the jFrame. Without any effect.
Despite of my efforts, java still shows me a full sized 20%opaque jPanel on the whole jFrame, that now contains another 20%opaque jPanel on Top.
I know that this whole problem is caused by the LayoutManager, Java useless per Default. However, it is not an option to set the LayoutManager to null or even change the LayoutManager of our jFrame, because that would lead us to refactor the whole functionality of our tiny app we worked on for several weeks.
public void showUndoPanel() {
System .out.println("Show Undo Panel");
JPanel myPanel = new JPanel(null);
JPanel glassPanel = new JPanel();
JPanel ContentPanel = new JPanel();
JLabel myJLabel = new JLabel("Great Job!");
myPanel.setBackground(new Color(255,122,122,100));
glassPanel.setSize(650, 550);
glassPanel.setBackground(new Color(255,122,122,100));
myPanel.add(glassPanel);
ContentPanel.setSize(650, 30);
ContentPanel.setBackground(new Color(255,122,122,20));
ContentPanel.add(myJLabel);
myPanel.revalidate();
myPanel.repaint();
undoPanel = myPanel;
myJFrame.add(undoPanel);
myJFrame.revalidate();
}
What I expected:
What it actually does:
Well, I solved the problem by using a BoxLayoutManager and a RigidArea. In case if anyone else may encounter that problem again in the future, I decided to provide the code for this simple solution.
public void showUndoPanel() {
System .out.println("Show Undo Panel");
JPanel myPanel = new JPanel(null);
JPanel glassPanel = new JPanel();
JPanel ContentPanel = new JPanel();
JLabel myJLabel = new JLabel("Great Job!");
myPanel.setBackground(new Color(255,255,255,0));
myPanel.setLayout(new BoxLayout(myPanel, BoxLayout.PAGE_AXIS));
glassPanel.setSize(650, 650);
glassPanel.setBounds(0,0,650,550);
glassPanel.setBackground(new Color(255,122,122,0));
myPanel.add(glassPanel);
myPanel.add(Box.createRigidArea(new Dimension(0,450)));
ContentPanel.setSize(650, 30);
ContentPanel.setBounds(0,750,650,30);
ContentPanel.setBackground(new Color(255,122,122,20));
ContentPanel.add(myJLabel);
myPanel.add(ContentPanel);
myPanel.revalidate();
myPanel.repaint();
undoPanel = myPanel;
myJFrame.add(undoPanel);
myJFrame.revalidate();
}
Now it behaves as expected:
BorderLyout would make it easier to implement.
Note the comments in the following mre:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Main {
private static JFrame myJFrame;
public static void main(String[] args) {
myJFrame = new JFrame();
myJFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
myJFrame.setLocationRelativeTo(null);
showUndoPanel();
myJFrame.pack();
myJFrame.setVisible(true);
}
public static void showUndoPanel() {
JPanel myPanel = new JPanel();
myPanel.setBackground(new Color(255,255,255,0));
myPanel.setLayout(new BorderLayout());
JPanel glassPanel = new JPanel(); //uses FlowLayout by default
//glassPanel.setSize(650, 650); //use preferred size
glassPanel.setPreferredSize(new Dimension(650, 650));
//glassPanel.setBounds(0,0,650,550); //no need to set bounds. bounds are set by the layout manager
glassPanel.setBackground(new Color(255,122,122,0));
myPanel.add(glassPanel, BorderLayout.CENTER);
JPanel contentPanel = new JPanel(); //uses FlowLayout by default
//contentPanel.setSize(650, 30);//use preferred size
contentPanel.setPreferredSize(new Dimension(650, 30));
//contentPanel.setBounds(0,750,650,30); //no need to set bounds. bounds are set by the layout manager
contentPanel.setBackground(new Color(255,122,122,20));
JLabel myJLabel = new JLabel("Great Job!");
contentPanel.add(myJLabel);
myPanel.add(contentPanel, BorderLayout.SOUTH);
myJFrame.add(myPanel);
}
}

Place JButton in defined position

I have a problem, i searched on many topics how to place a JButton on a JPanel with a defined position. The most current answer i found is that, i should display layout of JFrame and set it to null, so here is my code. But the thing is that when i'm setting layout to null nothing works anymore.
package loto;
import javax.swing.JFrame;
import javax.swing.JButton;
public class Accueil extends JFrame{
public Accueil(){
this.setTitle("Accueil du loto");
this.setSize(1920,1080);
this.setLocationRelativeTo(null);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
fond pan = new fond();
JButton suivant = new JButton("Commencer le Loto");
pan.setLayout(null);
pan.add(suivant);
suivant.setBounds(1800, 400, 40, 300);
this.setContentPane(pan);
while (true) {
this.repaint();
}
}
}
When you are new to Swing, you have to go by step by step UI,
Ensure the JPanel is added to your JFrame... fond pan = new fond(); Is it a JPanel subclass? you dont need to do this way you can
create JPanel jp = new JPanel();
add this JPanel component to JFrame by calling this.add(jp) in your constructor.
three important properties for every Swing display is a) setVisible b)setLayout c)setContentPane d) add
You have added JButton to Jpanel but you have not added Jpanel to JFrame.
add properties this.add(pan), this.setLayout(new FlowLayout()) in your constructor.
remove the while loop from your constructor.
Using null-Layout, you have to set a size and a location for your JButton like this:
suivant.setSize(120,20);
suivant.setLocation(x,y);

JFrame not displaying button or background color

My JFrame is not displaying the button or background color that is set in the constructor. I am only getting a blank box when I start the program. Not sure what is wrong with the code.
//imports
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;;
public class StartingTheCode{
JButton CalculateButton;
JTextField Ans;
JPanel p;
JFrame f;
public static void main (String[] args){
new StartingTheCode();
}
//constructor
StartingTheCode(){
f = new JFrame("test");
f.setVisible(true);
f.setSize(600,600);
f.setLocationRelativeTo(null);
f.setResizable(false);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
p = new JPanel();
p.setBackground(Color.BLUE); // not displaying blue background
CalculateButton = new JButton("+"); // should display button
CalculateButton.setSize(30,30);
CalculateButton.setLocation(5,5);
}
}
You're not adding your button or your JPanel to anything, and so no JFrame is magically going to display them.
You should add your JButton to your JPanel via its add(...) method, and then add the JPanel to the JFrame via its add(...) method, and do so before setting the JFrame visible.
Most importantly, you should read the Swing tutorials, since I speak from experience when saying you'll get no-where just guessing at this stuff. This is all well explained there.
As an aside, avoid setting the sizes of any components and instead read the tutorial section on use of the layout managers as it will allow you to simplify and empower your code greatly.
You need to add your calculateButton to the JPanel with p.add(calculateButton) and add the panel to the frame with f.add(p)

How to put multiple pictures on a JFrame?

I'm having a problem putting multiple images on a JFrame. I already added a picture on the JFrame as the primary background. But when I try to put another image for the logo of my program, it doesn't show up. Can someone please help me? thanks.
P.S. I'm using the Container class in my JFrame.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.event.*;
import java.io.*;
import java.awt.Container;
public class logIn extends JFrame
{
Random rand = new Random();
int n2 = (int) (1+Math.random()*255);
int n1 = rand.nextInt(n2);
int n3 = rand.nextInt(n2);
int n4 = rand.nextInt(n2);
Color color = new Color(n1,n3,n4);
JLabel image = new JLabel (new ImageIcon("space2.png"));
//JLabel image2 = new JLabel (new ImageIcon("login.png"));
JLabel userName = new JLabel("Username");
JLabel passWord = new JLabel("Password");
JTextField user = new JTextField(10);
JTextField pass = new JTextField(10);
JLabel myDog = new JLabel(new ImageIcon("space.jpeg"));
public static void main (String args[])
{
new logIn();
}
public logIn()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container c = getContentPane();
c.setLayout(null);
c.add(image);
image.setBounds(0,0,1366,768);
JLabel image2 = new JLabel (new ImageIcon("login.png"));
c.add(image2);
image2.setBounds(2000,2000,2000,2000);
//c.add(image2);
//image2.setBounds(10,10,250,250);
//c.add(userName);
//userName.setLayout(null);
//userName.setBounds(50,100,100,50);
setVisible(true);
setSize(1366,768);
setLayout(new BorderLayout());
add(myDog);
myDog.setLayout(null);
}
public void paint (Graphics g)
{
Image a = Toolkit.getDefaultToolkit().getImage("login.png");
g.drawImage(a,0,0,1366,768,this);
super.paint(g);
setVisible(true);
}
}
not sure what you're trying to achieve, but if you want to have multiple images (like a key image besides the password field and an avatar besides the user name, etc) you could create multiple JLabels with the different images and add them to the panel. If this is your purpose, don't override paint.
You need to read a few tutorials on custom painting, layouts, and gui development.
If you want to paint an image you should not load the image every repaint. You need to read that image in ahead of time. You should not be calling set visible in this method either.
Any custom painting needs to be done in paintComponent instead of paint.
Read this: http://docs.oracle.com/javase/tutorial/uiswing/painting/
It sounds like what you really want to do is create a JFrame with a panel that has a background image - and then use swing and layouts to add other components or panels with images on top of that.
So you would have a JPanel as the content pane with paintComponent overridden to only paint an image. Then build new components from there and place them using a layout manager.

Categories