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.
Related
I'm trying to add a .gif image to a JButton, but can't seem to get the image to load when i run the code. I've included a screenshot. Included is the frame that's created. I'd really appreciate any help that can be provided. Stack is telling me I can't enter images yet, so it created a link for it. I'm also going to enclose the actual code here:
package java21days;
import javax.swing.*;
import java.awt.*;
public class ButtonsIcons extends JFrame {
JButton load, save, subscribe, unsubscribe;
public ButtonsIcons() {
super("Icon Frame");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
//Icons
ImageIcon loadIcon = new ImageIcon("load.gif");
ImageIcon saveIcon = new ImageIcon("save.gif");
ImageIcon subscribeIcon = new ImageIcon("subscribe.gif");
ImageIcon unsubscribeIcon = new ImageIcon("unsubscribe.gif");
//Buttons
load = new JButton("Load", loadIcon);
save = new JButton("Save", saveIcon);
subscribe = new JButton("Subscribe", subscribeIcon);
unsubscribe = new JButton("Unsubscribe", unsubscribeIcon);
//Buttons To Panel
panel.add(load);
panel.add(save);
panel.add(subscribe);
panel.add(unsubscribe);
//Panel To A Frame
add(panel);
pack();
setVisible(true);
} //end ButtonsIcon Constructor
public static void main(String[] arguments) {
ButtonsIcons ike = new ButtonsIcons();
}
} //end ButtonsIcon Class
enter image description here
The easiest way is.
Label or Jbutton and what ever else supports HTML 3.5
JLabel a = new JLabel("");
add that to your container.
Haven't figured out how to enter code sorry
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);
}
}
I know this question has been asked before but i cant seem to implement any of the other answers to my project. So i have my paint method in my player class here.
public void paintComponent(Graphics g)
{
//makes player(placeholder for real art)
super.paintComponent(g);
g.setColor(Color.GREEN);
g.fillRect(x,y,50,30);
}
Then I have my main class here.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
/**
* Write a description of class Main here.
*
* #author Richard Zins
* #V01
*/
public class Main extends JFrame
{
public static void main(String[]args)
{
Player p1 = new Player();
Main m = new Main(p1);
}
public Main(Player p1)
{
JFrame ar = new JFrame();
JLabel background = new JLabel(new ImageIcon("/Users/rizins/Desktop/PacManTestBackGround.jpg"));
ar.setTitle("Runner Maze");
ar.setSize(800,600);
ar.add(background);
ar.setVisible(true);
ar.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ar.add(p1);
}
}
Now I cant seem to get my player object to paint over my background any help would be appreciated!
There are a couple of mistakes...
JPanel by default is opaque, so you need to change it to be transparent
JFrame uses a BorderLayout by default, so only one component will be shown at the (default) center position, in this case, the last thing you add.
You should call setVisible last
Instead, set a layout manager for the JLabel and add your player class to it. Instead of adding the JLabel to the frame, you should make the label the contentPane for the frame, for example...
p1.setOpaque(false);
JFrame ar = new JFrame();
ar.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel background = new JLabel(new ImageIcon("/Users/rizins/Desktop/PacManTestBackGround.jpg"));
ar.setTitle("Runner Maze");
ar.setContentPane(background);
ar.setLayout(new BorderLayout());
ar.add(p1);
ar.pack();
ar.setVisible(true);
I should point out that using a JLabel to display a background image like this could cause you problems, as the JLabel only uses the text and icon properties to calculate its preferred size, this could cause some child components to be laid out beyond its visible range.
See How to set a background picture in JPanel for more details and a possible solution
You can make the JPanel transparent by setting the opaque to false. e.g:
panel.setOpaque(false)
Try is if this work for you.
Use a JLayeredPane and add your background at the index 0 (indexed with an Integer not an int). Then you add another JPanel that is not opaque (like in #Bahramdun Adil 's answer) and add your player to that.
This way you can have a background and display your player at the same time.
I am just starting to make a simple mp3 player, I am creating the play, forward, back, etc... Button but for some reason only the first button appears and to make the second button appear I have to go and scroll over it. If you could help me fix that, that would be great. And I am using a two images one named play.jpg and another named next.png.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Graphic extends JPanel{
JFrame f = new JFrame();
JPanel p = new JPanel(new GridBagLayout());
public Graphic(){
gui();
}
public void gui(){
f.setVisible(true);
f.setSize(1600,900);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(p);
ppr(75,26,25,25,"pics/play.jpg");
//above is the play button
ppr(40,26,25,25,"pics/next.png");
// above is the button that wont appear until it is scrolled over (it is just to the left of the button above
}
public void ppr(int x, int y, int width, int height, String file){
p.setLayout(null);
Toolkit tool = Toolkit.getDefaultToolkit();
Image player = tool.getImage(file);
ImageIcon playbutton = new ImageIcon(player);
JButton play = new JButton(playbutton);
play.setBounds(x, y, width, height);
p.add(play);
// ********************** above is the the method that makes a button
}
public static void main(String args[]) {
new Graphic();
}
}
Don't use setBounds. Use GridBagLayout
you specified while initialising the panel and specify GridBagConstraints
The setVisible(true) method should be invoked AFTER all the components have been added to the GUI.
I also agree with the other suggestions for better GUI design.
Run the GUI in a different thread, not the main thread.
http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
All UI code should be run in the event dispatch thread for Swing.
public class MinesweeperMenu extends MinesweeperPanel{
private JPanel picture = new JPanel();
private JButton play = new JButton("Play");
private JButton highScores = new JButton("High Score and \nStatistics");
private JButton changeMap = new JButton("Create Custom \nor Change Map");
private JButton difficulty = new JButton("Custom or\nChange Difficulty");
private JButton user = new JButton("Change User");
Image img;
public MinesweeperMenu()
{
// Set Layout for the menu
LayoutManager menuLayout = new BoxLayout(menu, BoxLayout.Y_AXIS);
menu.setLayout(menuLayout);
// Set Layout for the window
LayoutManager windowLayout = new BorderLayout();
window.setLayout(windowLayout);
// Add buttons to the panels
menu.add(play);
menu.add(highScores);
menu.add(changeMap);
menu.add(difficulty);
menu.add(user);
// Add picture to the frame
try{
File input = new File("./setup/images/MineMenuPicture.jpg");
img = ImageIO.read(input);
}
catch(IOException ie)
{
System.out.println(ie.getMessage());
}
// Add action listeners
changeMap.addActionListener(new ChangeMapListener());
}
public void paintComponent(Graphics g)
{
// POSITION OF THE PICTURE
int x = 650;
int y = 585;
g.drawImage(img, x, y, null);
}
public void displayFrame()
{
// Display Frame
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
}
public static void main(String[] args)
{
MinesweeperMenu menu = new MinesweeperMenu();
window.pack();
menu.displayFrame();
window.repaint();
}
}
public class MinesweeperPanel extends JFrame{
public static final Color COLOR_KEY = new Color(220, 110, 0);
// Initialize all the objects
public static JFrame window = new JFrame("Minesweeper++");
public static JPanel menu = new JPanel();
// Close the current window
public static void close()
{
window.setVisible(false);
window.dispose();
}
}
I can't get my image to display in the frame. I've tried everything, but I'm getting the impression it's a mistake that I'm not realizing since I am new to Java Swing. Any help would be greatly appreciated.
You're making things difficult for yourself by having a very confusing program structure, and I suggest that you simplify things a lot.
For one, there's no need for your current MinesweeperMenu class to extend MinesweeperPanel, and for the latter class to extend JFrame. Then you have a static JFrame somewhere else -- that's too many JFrames, and to boot, you're trying to display your image in one JFrame but showing the other one that doesn't have the picture. Your program needs just one JFrame and it should probably be created, stuffed with its contents, packed and displayed in one place, not scattered here and there as you're doing.
You're trying to display the picture in a paintComponent override, but this method will never get called since your class extends JFrame (eventually) and JFrame doesn't have this method. You're using the right method, but the class should be extending JPanel, and you should have an #Override annotation above the paintComponent method block to be sure that you're actually overriding a parent method.
You should get rid of all static everything in this program. The only thing static here should be the main method and perhaps some constants, but that's it.
There are more errors here, and I have too little time to go over all of them. Consider starting from the beginning, starting small, getting small bits to work, and then adding them together.
For instance, first create a very small program that tries to read in an image into an Image object, place it in a ImageIcon, place the ImageIcon into a JLabel, and display the JLabel in a JOptionPane, that simple, just to see if you can read in images OK, for example, something like this:
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
public class TestImages {
// *** your image path will be different *****
private static final String IMG_PATH = "src/images/image01.jpg";
public static void main(String[] args) {
try {
BufferedImage img = ImageIO.read(new File(IMG_PATH));
ImageIcon icon = new ImageIcon(img);
JLabel label = new JLabel(icon);
JOptionPane.showMessageDialog(null, label);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Then when you've done this, see if you can now create a JPanel that shows the same Image in its paintComponent method, and display this JPanel in a JOptionPane.
Then create a JFrame and display the image-holding JPanel in the JFrame.
Through successive iterations you'll be testing concepts, correcting mistakes and building your program.
File input = new File("./setup/images/MineMenuPicture.jpg");
If MineMenuPicture.jpg is an application resource, it should be in a Jar and accessed by URL obtained from Class.getResource(String).