Function: Image in a JFrame - java

I'm trying to right a function that creates a JFrame that contains an image. Problem is I only get an empty JFrame (no errors). Is there a better way to do this?
Here is the class that contains the function:
public class Play extends JFrame
{
protected static ImageIcon icon = new ImageIcon("C:\\Users\\Fadil\\Desktop\\Coding\\civii\\earth.jpg");
protected static JLabel label = new JLabel(icon);
protected static JFrame f = new JFrame("Age Of")
public static void PlayStart()
{
f.getContentPane().add(label);
f.repaint();
f.setVisible(true);
}
}

simply do the following
1- create Panel class and use media tool kit to get image in your class path lie this
class P extends JPanel {
Image bg = null;
P() {
MediaTracker mt = new MediaTracker(this);
bg = Toolkit.getDefaultToolkit().getImage("yourimage");
mt.addImage(bg, 0);
try {
mt.waitForAll();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int imwidth = bgimage.getWidth(null);
int imheight = bgimage.getHeight(null);
g.drawImage(bg, 1, 1, null);
}
}
2- add the panel to your frame to the frame
public class JF extendts JFrame{
public JF(){
add(new P()) ;
sitSize(300,200) ;
}
}

Related

Displaying image over image Java

How do I display an image over another image on either applet or jframe?
I know for one image in applet is this:
Image Bendy;
Bendy = getImage(getDocumentBase(), "Bendy Icon.PNG");
g.drawImage(Bendy, 20, 20, this);
And for jframe:
ImageIcon kh = new ImageIcon("KH3.gif");
JLabel lab = new JLabel(kh);
add(lab);
So how do I add an image over the other for either one?
As mentioned in comments, (Java) Applets are indeed dead and not worth pursuing. The ImagePanel in this answer extends JPanel and could theoretically be displayed in any Java Swing based top-level container (e.g. JFrame, JWindow, JOptionPane..) or in another container like a JPanel.
import java.awt.*;
import java.awt.image.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.util.Random;
import javax.imageio.ImageIO;
import java.net.URL;
public class StackedImages {
private JComponent ui = null;
String path1 = "https://i.stack.imgur.com/F0JHK.png";
String path2 = "https://i.stack.imgur.com/gJmeJ.png";
class ImagePanel extends JPanel {
private final BufferedImage[] images;
private final Random rand = new Random();
private final Dimension prefeSize = new Dimension(400, 400);
ImagePanel(BufferedImage[] images) {
this.images = images;
setBackground(Color.WHITE);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (int ii = 0; ii < 200; ii++) {
int x = rand.nextInt(prefeSize.width);
int y = rand.nextInt(prefeSize.height);
int ind = rand.nextInt(images.length);
g.drawImage(images[ind], x, y, this);
}
}
#Override
public Dimension getPreferredSize() {
return prefeSize;
}
}
StackedImages() {
try {
initUI();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public final void initUI() throws Exception {
if (ui != null) {
return;
}
ui = new JPanel(new BorderLayout(4, 4));
ui.setBorder(new EmptyBorder(4, 4, 4, 4));
BufferedImage[] bi = new BufferedImage[2];
bi[0] = ImageIO.read(new URL(path1));
bi[1] = ImageIO.read(new URL(path2));
ui.add(new ImagePanel(bi));
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = () -> {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
StackedImages o = new StackedImages();
JFrame f = new JFrame(o.getClass().getSimpleName());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
};
SwingUtilities.invokeLater(r);
}
}
As said by people in comments, Applets are dead, you don't actually need them to learn GUI programs.
But still, if you want there are some ways you can do so, like using drawImage() method. Maybe something like this:
try
{
BufferedImage background = ImageIO.read(new File("..."));
BufferedImage logo = ImageIO.read(new File("..."));
Graphics g = background.getGraphics();
g.drawImage(logo, 0, 0, null);
}
catch (Exception e)
{
e.printStackTrace();
}

Image not drawn in JPanel

This is the code i tried to use to paint an image on screen (location of the image is correct), the code runs but nothing is drawn on the screen. My program's getFile() and paintComponent() method:
BufferedImage image;
public void getFile() throws IOException{
image = ImageIO.read(new File("grass.png"));
}
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(image, 0, 0, null);
}
}
You do realise that you never create an instance of DrawImage nor do you actually add it to anything that could display it
public class DrawImage extends JPanel
{
BufferedImage image;
public DrawImage() throws IOException {
getFile();
}
public void getFile() throws IOException
{
image = ImageIO.read(new File("grass.png"));
}
//...
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
DrawImage pane = new DrawImage();
JFrame frame = new JFrame();
frame.add(pane);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setVisible(true);
} catch (IOException exp) {
exp.printStackTrace();
}
}
});
}
Instead of JPanel pane = new JPanel(), you should do DrawImage pane = new DrawImage() and before you do frame.add(pane) call pane.getFile().
Since you always need to call getFile() before drawing the DrawImage, why don't you put it into a constructor of the DrawImage class?
First you didn't use your class that draw the image (DrawImage)
in this line JPanel pane = new JPanel(); so you must change it to DrawImage pane = new DrawImage();
second issue you didn't invoke getFile() method to initialize image object so either use as I mentioned below or invoke this method as your write in class drawImage constructor.
public class DrawImage extends JPanel{
BufferedImage image;
public Image getFile()
{
try {
image = ImageIO.read(new File("grass.png"));
return image;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
System.out.println(image);
g.drawImage(getFile(), 0, 100, null);
}
public static void main(String[] args)
{
DrawImage pane = new DrawImage();
JFrame frame = new JFrame();
frame.add(pane);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setVisible(true);
}
}

How to load two extended JPanel class to one JFrame?

I'm going to make a game with Java, my game will have a menu. the menu is having a background, and 2 JLabel objects. I've make them on separate class, which is passed to one JFrame. And my problem is, I've load 2 of them on a single frame, but one of them always hidden by another.
this is the code:
JFrame class
#SuppressWarnings("serial")
public class Sistem extends JFrame{
private final int lebar=954;
private final int tinggi=540;
private Image bg;
File gbr=new File("res/a.jpg");
public Sistem(){
this.setTitle("Unknown man Unkown power");
this.setSize(new Dimension(lebar,tinggi));
this.setFocusable(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.setContentPane(new Ngrep());
//this.setContentPane(new Menu());
this.setVisible(true);
//loadfont();
//loadbg();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
new Sistem();
}
});
}
}
background class
#SuppressWarnings("serial")
public class Ngrep extends JPanel{
private int l=954;
private int t=540;
private BufferedImage bg;
File gbr=new File("res/a.jpg");
public Ngrep(){
loadbg();
}
private void loadbg() {
// TODO Auto-generated method stub
try {
bg=ImageIO.read(gbr);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void paint(Graphics g) {
// TODO Auto-generated method stub
super.paint(g);
g.drawImage(bg, 0, 0, l, t, null);
}
}
menu class
#SuppressWarnings("serial")
public class Menu extends JPanel implements Runnable,KeyListener{
private int l=954;
private int t=540;
JLabel menu1=new JLabel("MULAI BARU");
JLabel menu2=new JLabel("KELUARRR");
private File fo=new File("res/Mawns.ttf");
JLayeredPane p=new JLayeredPane();
public Menu(){
loadfont();
this.add(menu1);
this.add(menu2);
}
public void loadfont(){
try {
FileInputStream fi=new FileInputStream(fo);
Font f=Font.createFont(Font.TRUETYPE_FONT, fi).deriveFont(Font.TRUETYPE_FONT, 30);
GraphicsEnvironment ge=GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(f);
menu1.setFont(f);
menu2.setFont(f);
} catch (Exception ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
}
p.setLayout(new GridLayout(2, 3));
menu1.setBounds(0, 0, getWidth(), getHeight());
menu2.setBounds(0, 0+menu1.getHeight(), getWidth(), getHeight());
p.add(menu1, 2);
p.add(menu2, 2);
}
}
What I want is the menu is in front of background but background still can be seen. and how to arrange the JLabel that I've created to center down of the screen.
How can I achieve the required layout?
public class Ngrep extends JPanel{
Note that since Ngrep is a JPanel you can add components directly to it, making the Menu class redundant.
Something like seen in this SSCCE.
Note that I ended up making so many changes so fast I could not be bothered explicitly documenting most of them. Look over the code carefully, check it against your original code, check the Java Docs, and if there is any change you do not understand, ask me.
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.URL;
import javax.imageio.ImageIO;
#SuppressWarnings("serial")
public class Sistem extends JFrame {
public Sistem() {
this.setTitle("Unknown man Unkown power");
this.setFocusable(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setContentPane(new Ngrep());
this.setResizable(false);
this.pack();
this.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Sistem();
}
});
}
}
#SuppressWarnings("serial")
class Ngrep extends JPanel {
private int l = 375;
private int t = 150;
private BufferedImage bg;
JLabel menu1 = new JLabel("MULAI BARU");
JLabel menu2 = new JLabel("KELUARRR");
public Ngrep() {
this.add(menu1);
this.add(menu2);
try {
Font f = new Font(Font.MONOSPACED, Font.ITALIC, 30);
menu1.setFont(f);
menu1.setForeground(Color.RED);
menu2.setFont(f);
menu2.setForeground(Color.RED);
URL url = new URL("http://i.stack.imgur.com/OVOg3.jpg");
bg = ImageIO.read(url);
} catch (Exception ex) {
ex.printStackTrace();
}
setLayout(new GridLayout(2, 3));
add(menu1);
add(menu2);
}
public Dimension getPreferredSize() {
return new Dimension(l, t);
}
/*
* For a JComponent, override paintComponent rather than paint
*/
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
// a JPanel IS AN ImageObserver
g.drawImage(bg, 0, 0, getWidth(), getHeight(), this);
}
}
Start by using JFrame#add instead of JFrame#setContentPane, unless you intend to add more components to that (content) pane.
By default JFrame uses a BorderLayout for its LayoutManager. You will need to either change it to something you prefer to use OR add each component to an appropriate position within the BorderLayout
See Laying Out Components Within a Container for more details
solved, because I've found that i use paint() instead of paintComponent().
like this:
#Override
public void paint(Graphics g) {
// TODO Auto-generated method stub
super.paint(g);
g.drawImage(bg, 0, 0, l, t, this);
}
to this :
#Override
public void paintComponent(Graphics g) {
// TODO Auto-generated method stub
super.paintComponents(g);
g.drawImage(bg, 0, 0, l, t, this);
}

Add an Background image to a Panel

I have a JPanel, and i want to add an image as its background. How can i do that ?
frame = new JFrame("Some frame");
panel1 = new JPanel();
panel1.setBorder(new EmptyBorder(5, 5, 5, 5));
// NEED TO ADD AN IMAGE TO THIS PANEL
panel1.setLayout(cardlayout);
frame.getContentPane().add(panel1);
frame.setLocationByPlatform(true);
frame.setVisible(true);
I need to add an image to the panel and how can i do it ?
UPDATE 1
panel1 = new JPanel()
{
private static final long serialVersionUID = 1L;
#Override
public void paintComponent(Graphics g)
{
g.drawImage(Toolkit.getDefaultToolkit().createImage("1.jpg"), 0, 0, null);
}
};
You need to override the method paintComponent(Graphics g) of JPanel and use drawImage() on the Graphics object g as in this example.
Also, check these two examples by #trashgod:
example.
example.
You have a resource location problem.
Toolkit#createImage may return an empty image if the resource can not be found.
I suggest you use the ImageIO API instead, it supports a wider range of image formats, but will also throw an exception if the image is not found or can not be loaded.
How you load the image will also depend on where the image is.
If the image exists on the file system, you can simply use a File object reference, if the image is an embedded resource (within you application), you will need to use Class#getResource to obtain a URL to it.
public class TestGraphics {
public static void main(String[] args) {
new TestGraphics();
}
public TestGraphics() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new PaintTest());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class PaintTest extends JPanel {
private BufferedImage image;
public PaintTest() {
setLayout(new BorderLayout());
try {
// Use this if the image exists within the file system
image = ImageIO.read(new File("/path/to/image/imageName.png"));
// Use this if the image is an embedded resource
// image = ImageIO.read(getClass().getResource("/path/to/resource/imageName.png"));
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public Dimension getPreferredSize() {
return image == null ? super.getPreferredSize() : new Dimension (image.getWidth(), image.getHeight());
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (image != null) {
int x = (getWidth() - image.getWidth()) / 2;
int y = (getHeight()- image.getHeight()) / 2;
g.drawImage(image, x, y, this);
}
}
}
}

Best manner to place 'markers' on an ImageIcon Java Swing?

I have a Java swing application where I've created an ImageIcon with a picture and displayed it to a screen. I did that by loading a URL as an ImageIcon and placing it in the Java Swing window as a label.
Now I need to place 'markers' on the image with other images.
In context: Place a picture of an eye on someones face over their eye.
I'd appreciate anyone who can point my in the right direction or give me some SSCCE code to work from.
What is the best manner to place 'markers' on an ImageIcon Java Swing?
The basic concept is, you need a temporary image onto which you can paint the master/base image and the marker.
Create a new BufferedImage. This would typically be the same size as the master image, but doesn't have to be.
Paint the master image onto BufferedImage
Paint the marker onto the BufferedImage
Create a new ImageIcon using the BufferedImage
Apply the ImageIcon to the label...
public class PaintIcon {
public static void main(String[] args) {
new PaintIcon();
}
public PaintIcon() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new PaintPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class PaintPane extends JPanel {
private JLabel label;
private int state = 0;
private BufferedImage disk;
private BufferedImage play;
private BufferedImage pause;
private BufferedImage stop;
public PaintPane() {
setLayout(new GridBagLayout());
add((label = new JLabel()));
try {
disk = ImageIO.read(getClass().getResource("/cd.png"));
play = ImageIO.read(getClass().getResource("/media_play.png"));
pause = ImageIO.read(getClass().getResource("/media_pause.png"));
stop = ImageIO.read(getClass().getResource("/media_stop.png"));
} catch (Exception e) {
e.printStackTrace();
}
updateState();
label.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
state++;
if (state > 2) {
state = 0;
}
updateState();
}
});
}
protected void updateState() {
BufferedImage base = new BufferedImage(disk.getWidth(), disk.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = base.createGraphics();
g2d.drawImage(disk, 0, 0, this);
BufferedImage marker = null;
switch (state) {
case 0:
marker = stop;
break;
case 1:
marker = play;
break;
case 2:
marker = pause;
break;
}
int x = disk.getWidth() - marker.getWidth();
int y = disk.getHeight() - marker.getHeight();
g2d.drawImage(marker, x, y, this);
g2d.dispose();
label.setIcon(new ImageIcon(base));
}
}
}

Categories