Cannot get image to display in Swing on OSX - java

I think I'm being a bit of an idiot, given that I haven't done Swing programming in a while, but I'm trying to draw a simple image to screen, and I'm not getting what I expected
public class ImageApp {
public static void main(String[] args) throws MalformedURLException, IOException {
final Image image = ImageIO.read(new File("/Library/WebServer/Documents/image.gif"));
final JPanel component = new JPanel(){
public void paint(final Graphics g) {
System.out.println("Drawing image "+image.getWidth(null)+" "+image.getHeight(null));
g.drawString("hello", 0,0);
g.drawImage(image,this.getWidth()/2,this.getHeight()/2, 100, 100, Color.blue,this);
super.paint(g);
}
};
final JFrame frame = new JFrame();
frame.add(component);
frame.setSize(100, 100);
frame.pack();
frame.setVisible(true);
}
}
This renders a blank window which doesn't seem to be sized to 100,100. Is there some other step I need to perform to get the graphics to appear on screen, or the size to be respected?
I'm using JDK6 on OSX 10.6

In Swing, you should override paintComponent(), not paint().
Addendum: e.g., see below. In a comment, #eugener raises an excellent point about using a JLabel as an alternative image container.
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ImageApp {
public static void main(String[] args) throws IOException {
final Image image = ImageIO.read(new File("image.jpg"));
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
final JPanel component = new JPanel() {
#Override
public void paintComponent(final Graphics g) {
g.drawImage(image, 0, 0, null);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(
image.getWidth(this), image.getHeight(this));
}
};
final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(component);
frame.pack();
frame.setVisible(true);
}
});
}
}

Try this:
public class ImageApp {
public static void main(String[] args) throws MalformedURLException, IOException {
final Image image = ImageIO.read(new File("/Library/WebServer/Documents/image.gif"));
final JPanel component = new JPanel() {
#Override
public void paintComponent(final Graphics g) {
super.paintComponent(g);
System.out.println("Drawing image " + image.getWidth(null) + " " + image.getHeight(null));
g.drawString("hello", 0,10);
g.drawImage(image, this.getWidth() / 2, this.getHeight() / 2, 100, 100, Color.blue, this);
}
};
final JFrame frame = new JFrame();
frame.add(component);
frame.setSize(100, 100);
frame.setVisible(true);
}
}

Related

Java - BufferedImage Not Appearing on JFrame

I'm having trouble getting an image to show on a JFrame.
The frame is completely black upon running. Here's my code:
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
public class JFrameTesting extends JFrame {
BufferedImage test = null;
public static void main(String[] args) throws URISyntaxException {
new JFrameTesting();
}
public JFrameTesting() throws URISyntaxException {
JFrame frame = new JFrame("My first JFrame!");
frame.setSize(400, 400);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
try {
test = ImageIO.read(new File(getClass().getResource("test.png").toURI()));
} catch (IOException ex) {
Logger.getLogger(JFrameTesting.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void paint(Graphics g) {
super.paint(g);
g.drawImage(test, 200, 200, null);
}
}
I'm not sure if I'm nessecarily doing anything wrong. I have no errors at all when running.
Thanks in advance!
you can try, with this code.
you need to load a JLabel on Jframe when you add a image.
BufferedImage test = null;
public static void main(String[] args) throws URISyntaxException {
new JFrameTesting();
}
public JFrameTesting() throws URISyntaxException {
JFrame frame = new JFrame("My first JFrame!");
JLabel label = new JLabel();
frame.setSize(800, 800);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
try {
test = ImageIO.read(new File(getClass().getResource("test.png").toURI()));
frame.add( new JLabel(new ImageIcon(test)),BorderLayout.CENTER);
frame.setIconImage(test);
frame.setVisible(true);
label.setVisible(true);
} catch (IOException ex) {
Logger.getLogger(JFrameTesting.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void paint(Graphics g) {
super.paint(g);
g.drawImage(test, 200, 200, null);
}
}
You haven't actually added your image to the JFrame yet. To have the image appear you need to add the BufferedImage onto a component then draw that. You can do that using a JLabel and an ImageIcon.
public class JFrameTesting extends JFrame {
BufferedImage test = null;
ImageIcon image = new ImageIcon();
public static void main(String[] args) throws URISyntaxException {
new JFrameTesting();
}
public JFrameTesting() throws URISyntaxException {
JFrame frame = new JFrame("My first JFrame!");
try {
test = ImageIO.read(new File(getClass().getResource("test.png").toURI()));
image.setImage(test);
} catch (IOException ex) {
Logger.getLogger(JFrameTesting.class.getName()).log(Level.SEVERE, null, ex);
}
JLabel label = new JLabel();
label.setIcon(image);
frame.add(label);
frame.setSize(400, 400);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Alternatively you can skip the Label and draw onto a component if you want. In which case you you'll have to override the draw method of a JPanel.
JPanel pane = new JPanel() {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 200, 200, null);
}
};
frame.add(pane);
Another note is that you're extending JFrame but also making a new JFrame inside of the class. You can remove the extra JFrame and all the "frame." The class itself is a JFrame so you don't need an extra one.
//set the title using the setTitle method
setTitle("My first JFrame!");
add(label);
setSize(400, 400);
setVisible(true);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
Also, I believe the ImageIO.read(...) method can take a URI as a parameter so you shouldn't have to create a File from it.
My code draws image, but need repaint. For this you need for example to change size of frame using you mouse.
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
public class JFrameTesting extends JFrame {
BufferedImage test = null;
public static void main(String[] args) throws URISyntaxException {
new JFrameTesting();
}
public JFrameTesting() throws URISyntaxException {
JFrame frame = new JFrame("My first JFrame!");
frame.setSize(400, 400);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
try {
System.out.println("init");
test = ImageIO.read(new File(getClass().getResource("test.png").toURI()));
System.out.println(test);
} catch (IOException ex) {
Logger.getLogger(JFrameTesting.class.getName()).log(Level.SEVERE, null, ex);
}
final JPanel pane = new JPanel() {
#Override
protected void paintComponent(Graphics g) {
System.out.println("paint");
super.paintComponent(g);
g.drawImage(test, 0, 0, null);
}
};
frame.add(pane);
frame.repaint();
}
#Override
public void paint(Graphics g) {
super.paint(g);
System.out.println("paint");
g.drawImage(test, 200, 200, null);
}
}

How do I set the size of a JPanel? [duplicate]

I have a JPanel in my java code and I want to set its size, I have used JPanel.setSize(500,500); and JPanel.setSize(new Dimension(500,500)); but both are not working. Please tell how I can set the size of JPanel?
Most Swing layout managers respect a component's preferredSize and not its size. You could call setPreferredSize(new Dimension(500, 500)), but this can be overridden later in your code, and can lead to an inflexible GUI. Better to override the JPanel's getPreferredSize() method and return a calculated Dimension that works best in all situations.
For example:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.*;
public class PrefSizePanel extends JPanel {
private static final int PREF_W = 500;
private static final int PREF_H = PREF_W;
public Dimension getPreferredSize() {
// update as per Marco:
if (super.isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
// just for fun
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setPaint(new GradientPaint(0, 0, Color.red, 20, 20, Color.blue, true));
g2.fillOval(0, 0, 2 * getWidth(), 2 * getHeight());
}
private static void createAndShowGUI() {
PrefSizePanel paintEg = new PrefSizePanel();
JFrame frame = new JFrame("PrefSizePanel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(paintEg);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Which displays as

Why is rectangle not rendering to screen

public class Rec extends JFrame {
public Rec (){
JFrame jframe = new JFrame();
jframe.setSize(500, 500);
jframe.setVisible(true);
}
public void render (Graphics g){
g.setColor(Color.red);
g.fillRect(0,0,50,50);
}
public static void main(String[] args) {
Rec frame = new Rec();
frame.render(g);
}
}
Why does this not work? I am aware I may need a paintComponent, if so how would I go about doing this? Any help would be great, Thank You!
The thing is that painting in a JFrame is not what you should be doing. It is better (in this instance) to set the contentpane as a JPanel, and paint inside the JPanel.
Take this short snippet as an example:
import java.awt.*;
import javax.swing.*;
public class Rec {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame rec = new JFrame();
rec.setSize(50, 150);
rec.setContentPane(new JPanel() {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.red);
g.fillRect(0, 0, 50, 50);
}
});
rec.setVisible(true);
}
});
}
}
Result:
//May be this is what you are looking for.
public void paintComponent(Graphics g) {
// Create a copy of the passed in Graphics object
Graphics gCopy = g.create();
// Change the properties of gCopy and use it for drawing here
// Dispose the copy of the Graphics object
gCopy.dispose();
}
//or might be this
import javax.swing.JPanel;
import java.awt.Graphics;
import java.awt.Dimension;
import javax.swing.JFrame;
public class DrawingCanvas extends JPanel {
public DrawingCanvas() {
this.setPreferredSize(new Dimension(600, 75));
}
#Override
public void paintComponent(Graphics g) {
// Draw a rectangle
g.fillRect(100, 100, 100, 100);
}
public static void main(String[] args) {
JFrame frame =new JFrame("Drawing");
frame.getContentPane().add(new DrawingCanvas());
frame.pack();
frame.setVisible(true);
}
}

how to set the size of JPanel in java

I have a JPanel in my java code and I want to set its size, I have used JPanel.setSize(500,500); and JPanel.setSize(new Dimension(500,500)); but both are not working. Please tell how I can set the size of JPanel?
Most Swing layout managers respect a component's preferredSize and not its size. You could call setPreferredSize(new Dimension(500, 500)), but this can be overridden later in your code, and can lead to an inflexible GUI. Better to override the JPanel's getPreferredSize() method and return a calculated Dimension that works best in all situations.
For example:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.*;
public class PrefSizePanel extends JPanel {
private static final int PREF_W = 500;
private static final int PREF_H = PREF_W;
public Dimension getPreferredSize() {
// update as per Marco:
if (super.isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
// just for fun
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setPaint(new GradientPaint(0, 0, Color.red, 20, 20, Color.blue, true));
g2.fillOval(0, 0, 2 * getWidth(), 2 * getHeight());
}
private static void createAndShowGUI() {
PrefSizePanel paintEg = new PrefSizePanel();
JFrame frame = new JFrame("PrefSizePanel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(paintEg);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Which displays as

Why is this graphics component not working?

I am trying to draw a rectangle in the class "Graphics", but for some reason the rectangle does not appear, but the program returns no errors. I have never experience issues such as this before so I am rather confused.
Main()
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Main
{
public Main()
{
JFrame window = new JFrame();
Sound soundCall = new Sound();
Graphics graphicsCall = new Graphics();
final JPanel container = new JPanel();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.getContentPane().add(container);
window.setSize(600, 400);
window.setLocationRelativeTo(null);
window.setVisible(true);
window.setResizable(false);
}
public static void main(String args[])
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
new Main();
}
});
}
Graphics()
import java.awt.Color;
import java.awt.Graphics2D;
import javax.swing.JPanel;
public class Graphics extends JPanel
{
public void paintComponent(java.awt.Graphics g)
{
super.paintComponent(g);
g.setColor(Color.GRAY);
g.drawRect(500, 500, 500, 500);
}
}
EDIT FOR HOVERCRAFT
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Main
{
public Main()
{
JFrame window = new JFrame();
Sound soundCall = new Sound();
Draw drawCall = new Draw();
final JPanel container = new JPanel();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.getContentPane().add(drawCall);
window.setSize(600, 400);
window.setLocationRelativeTo(null);
window.setVisible(true);
window.setResizable(false);
}
public static void main(String args[])
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
new Main();
}
});
}
}
Through adding this window.getContentPane().add(drawCall); asks me to change drawCall to a Component
EDIT 2:
public class Draw
{
public class Graphics extends JPanel
{
public void paintComponent(java.awt.Graphics g)
{
super.paintComponent(g);
g.setColor(Color.GRAY);
g.drawRect(0, 0, 500, 500);
}
}
}
ERROR
The method add(Component) in the type Container is not applicable for the arguments (Draw)
You add your graphicsCall variable to nothing, and so it will not be displayed. Solution: add it to a container such as that JPanel that you just created, or perhaps directly to the JFrame's contentPane.
i.e., change this:
JFrame window = new JFrame();
Sound soundCall = new Sound();
Graphics graphicsCall = new Graphics();
final JPanel container = new JPanel();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.getContentPane().add(container);
to this:
JFrame window = new JFrame();
Sound soundCall = new Sound();
Graphics graphicsCall = new Graphics();
// final JPanel container = new JPanel();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.getContentPane().add(soundCall);
As an aside, you will want to re-name that class from Graphics to something else, or else you risk confusing yourself or your compiler since there already exists a critical Java class with that name.
Also, avoid using setSize(...). Better to have your drawing JPanel override getPreferredSize() and to call pack() on your JFrame.
Edit
As per MadProgrammer's astute observation, you're drawing outside of the bounds of your component.
Edit 2
Regarding your latest code, this:
public class Draw
{
public class Graphics extends JPanel
{
public void paintComponent(java.awt.Graphics g)
{
super.paintComponent(g);
g.setColor(Color.GRAY);
g.drawRect(0, 0, 500, 500);
}
}
}
is useless dreck. Why are you needlessly wrapping a class inside of a class? Instead why not simply:
public class Draw extends JPanel {
public void paintComponent(java.awt.Graphics g)
{
super.paintComponent(g);
g.setColor(Color.GRAY);
g.drawRect(0, 0, 500, 500);
}
#Override
public Dimension getPreferredSize() {
// return an appropriate Dimension here
}
}

Categories

Resources