I've been trying tp paint an image of a cheetah just to mess around with the paint method and such, but it doesn't seem to be working, any idea why?
I've tried a ton of stuff i found on here but nothing seems toi work at all, all i get is my button, i know its the actual paint method not working because it doesn't even pain the Hello string.
Here's the main class:
package dev.main;
import javax.swing.JFrame;
import javax.swing.JPanel;
import dev.angora.gui.GameGUI;
#SuppressWarnings("serial")
public class Main extends JFrame {
public static JFrame p = new JFrame("Angora Realms");
public static void main (String[] args) {
new Main();
}
public Main() {
p.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
p.pack();
p.setSize(640, 800);
p.setVisible(true);
p.setLayout(null);
GameGUI g = new GameGUI();
g.createGui(p);
}
}
And here is the class I try to paint in:
package dev.gui;
import java.awt.Button;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class GameGUI extends JFrame implements ActionListener {
public Button drawCard = new Button("Draw Card");
public Image cheetah = null;
public void createGui(JFrame p) {
drawCard.addActionListener(this);
drawCard.setBounds(20,30,80,30);
p.add(drawCard);
}
#Override
public void actionPerformed(ActionEvent event) {
Object cause = event.getSource();
if (cause == drawCard) {
System.out.println("Ay");
}
}
public void paintComponent(Graphics g) {
super.paint(g);
g.drawString("Hello", 200, 50);
if (cheetah == null) {
cheetah = getImage("plains/Cheetah.png");
Graphics2D g2 = (Graphics2D)g;
g2.drawImage(cheetah, 100, 100, 100, 300, this);
}
}
public Image getImage(String path) {
Image tempImage = null;
try {
URL imageURL = GameGUI.class.getResource(path);
tempImage = Toolkit.getDefaultToolkit().getImage(imageURL);
}
catch (Exception e) {
System.out.println("An error occured -" + e.getMessage());
}
return tempImage;
}
} '
You're creating something like three JFrames, so it's kind of hard to track where things are actually going. There is no need to use extends JFrame for either of the two classes you presented, in fact, this will highlight the cause of your error...
JFrame does not have a paintComponent method, so it will never be called, instead, change GameGUI to extend from JPanel and add #Override to the start of the paintComponent method declaration (before it), then change super.paint(g); to super.paintComponent(g);
For example...
public class GameGUI extends JPanel implements ActionListener {
public Button drawCard = new Button("Draw Card");
public Image cheetah = null;
public void createGui(JFrame p) {
drawCard.addActionListener(this);
drawCard.setBounds(20,30,80,30);
p.add(drawCard);
}
#Override
public void actionPerformed(ActionEvent event) {
Object cause = event.getSource();
if (cause == drawCard) {
System.out.println("Ay");
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
No offense, but I'm not a fan of passing a reference of the "container" to the child component so it can add itself in this way. Better to create an instance of GameGUI and add it to what ever container you want. The GameGUI doesn't need to know or care...IMHO
Runnable Example
Don't use pack and setSize, they are competing with each other. The content of the frame should dictate the size of the frame. This is done through the use of appropriate layout managers and overriding getPreferredSize of custom components.
Don't call setVisible until AFTER you've established the base UI
Make sure you are adding your components to a displayable surface if you expect them to be painted
Also, you're mixing heavy weight (java.awt.Button) and light weight (Swing/javax.swing.JFrame) components together...my recommendation is, don't, this will cause a bunch of other issues you really don't need to deal with.
import java.awt.Button;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main extends JFrame {
public static void main(String[] args) {
new Main();
}
public Main() {
JFrame p = new JFrame("Angora Realms");
p.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GameGUI g = new GameGUI();
p.add(g);
p.setSize(640, 800);
p.setVisible(true);
}
public class GameGUI extends JPanel implements ActionListener {
public Button drawCard = new Button("Draw Card");
public Image cheetah = null;
public GameGUI() {
drawCard.addActionListener(this);
add(drawCard);
}
#Override
public void actionPerformed(ActionEvent event) {
Object cause = event.getSource();
if (cause == drawCard) {
System.out.println("Ay");
}
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString("Hello", 200, 50);
if (cheetah == null) {
cheetah = getImage("plains/Cheetah.png");
Graphics2D g2 = (Graphics2D) g;
g2.drawImage(cheetah, 100, 100, 100, 300, this);
}
}
public Image getImage(String path) {
Image tempImage = null;
try {
URL imageURL = GameGUI.class.getResource(path);
tempImage = Toolkit.getDefaultToolkit().getImage(imageURL);
} catch (Exception e) {
System.out.println("An error occured -" + e.getMessage());
}
return tempImage;
}
}
}
Related
I am currently trying to render an Image to a JPanel. Here is my Code:
import java.awt.Graphics;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class ScreenSaver extends JPanel {
private static final long serialVersionUID = 001;
public static void main(String[] args) {
new ScreenSaver();
}
public ScreenSaver() {
new Window(1600, 900, "ScreenSaver", this);
}
public Image ball;
public void initCode() {
try {
File pathToBall = new File("ball.png");
ball = ImageIO.read(pathToBall);
} catch (IOException ex) {
ex.printStackTrace();
}
renderImage()
}
public void renderImage(Graphics g) {
g.drawImage(ball, 0, 0, 100, 100, null);
}
}
The "initCode()" method gets called after the JFrame has loaded. My problem now is that I want to call the "renderImage()" method. In the parameters I have to put "Graphics g" to use the "g.drawImage" function. Sadly I now dont know what to put in the brackets when I want to call "renderImage()". Can someone help?
The painting of pictures and graphic elements works a little differently than in your question.
Here is a working example:
import java.awt.*;
import java.io.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import javax.swing.*;
public class PaintExample extends JFrame{
private BufferedImage ball;
public static void main(String[] args) {
new PaintExample();
}
public PaintExample(){
initCode();
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setPreferredSize(new Dimension(1600, 900));
setMinimumSize(new Dimension(800, 600));
add(new JPanel(){
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(ball, 0, 0, 100, 100, this);
}
});
pack();
setLocationRelativeTo(null);
setTitle("Paint Example");
setVisible(true);
}
public void initCode() {
try {
File pathToBall = new File("ball.png");
ball = ImageIO.read(pathToBall);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
I hope this solves your problem.
Swing is event driven, this means that you never directly call painting methods.
Basics for a custom painting component:
extends JComponent
override paintComponent(Graphics g), this is the point where you can put your rendering code
override getPreferredSize(), so that the layout managers can do their duty, a suitable value is your image size
In addition I don't understand this line:
new Window(1600, 900, "ScreenSaver", this);
I am trying to create a graphics drawing program that allows the user to draw red pixels on the screen by dragging their mouse over it. So in a way, you can think of this program as Microsoft's Paint program but with only the pencil drawing tool and color red.
Unfortunately the mouseDragged() function in my program is not working properly. It will skip some of the pixels on the screen if I move my mouse too fast, like this:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FrameView extends JFrame {
JPanel panel;
Graphics2D drawingContext;
public static void main(String[] args) {
new FrameView();
}
public FrameView() {
panel = new JPanel();
panel.addMouseMotionListener(new MouseControls());
panel.setBackground(Color.WHITE);
this.add(panel);
this.setSize(new Dimension(500, 500));
this.setTitle("Drawing Program");
this.setVisible(true);
drawingContext = (Graphics2D)panel.getGraphics();
}
private class MouseControls extends MouseAdapter {
#Override
public void mouseDragged(MouseEvent e) {
int x = e.getX();
int y = e.getY();
final int WIDTH = 1;
final int HEIGHT = 1;
Shape pixel = new Rectangle(x, y, WIDTH, HEIGHT);
drawingContext.setColor(Color.RED);
drawingContext.draw(pixel);
}
}
}
getGraphics is NOT how painting works in Swing, instead, you should be overriding the paintComponent method of the component and performing your custom painting there.
Painting is destructive, it is expected that when ever paintComponent is called, you will completely repaint the current state of the component.
Have a look at Painting in AWT and Swing and Performing Custom Painting for more details
As to you "mouse" problem, this is actually how it works, you won't be notified of EVERY pixel position the mouse has to pass through, your mouse would lag horribly across the screen if it did. Instead, the OS moves the mouse in ever increasing steps based on the speed of the movement of the user input.
Instead of drawing just the points, draw lines between them, for example
nb: I've deliberately painted the points larger so you can see where they are been reported, you will see that all the dots (for a single drag) are connected
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.util.ArrayList;
import java.util.List;
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 {
private List<List<Point>> points = new ArrayList<>(25);
private List<Point> activeList;
public TestPane() {
MouseAdapter ma = new MouseAdapter() {
#Override
public void mouseDragged(MouseEvent e) {
if (activeList != null) {
activeList.add(e.getPoint());
repaint();
}
}
#Override
public void mousePressed(MouseEvent e) {
activeList = new ArrayList<>(25);
points.add(activeList);
}
#Override
public void mouseReleased(MouseEvent e) {
if (activeList != null && activeList.isEmpty()) {
points.remove(activeList);
}
activeList = null;
}
};
addMouseMotionListener(ma);
addMouseListener(ma);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(Color.RED);
for (List<Point> group : points) {
Point previous = null;
for (Point p : group) {
// You can get rid of this, it's simply to show
// where the points would actually be rendered
g2d.fill(new Ellipse2D.Float(p.x - 2, p.y - 2, 4, 4));
if (previous != null) {
g2d.draw(new Line2D.Float(previous, p));
}
previous = p;
}
}
g2d.dispose();
}
}
}
In an attempt to make a very simple bullet-hell game to learn about java, I ran into a roadblock: repaint() wasn't calling paintComponent().
Here is the entire program, which for now simply draws an image I created 50 times per second onto a JPanel, which rests on a JFrame.
/*
* Bullet hell, by Nematodes
*/
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class bulletHell extends JFrame
{
private static final long serialVersionUID = 0L;
JPanel gamePanel = new JPanel();
int gameTimerDelay = 20;
int x, y = 0;
BufferedImage lightOrb;
javax.swing.Timer gameTimer;
public static void main(String[] args)
{
bulletHell createFrame = new bulletHell();
createFrame.frameConstructor();
}
public void frameConstructor()
{
// Construct frame and frame components
setTitle("Bullet hell");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
getContentPane().setLayout(new GridBagLayout());
setVisible(true);
GridBagConstraints gridConstraints;
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 0;
gridConstraints.gridy = 0;
gamePanel.setBackground(Color.BLACK);
gamePanel.setPreferredSize(new Dimension(700, 700));
getContentPane().add(gamePanel, gridConstraints);
pack();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setBounds((int) (0.5 * (screenSize.width - getWidth())),
(int) (0.5 * (screenSize.height - getHeight())), getWidth(), getHeight());
try
{
lightOrb = ImageIO.read(new File("C:/Users/Owner/Downloads/orb.bmp"));
}
catch(IOException e)
{
System.out.println("An issue occurred while trying to read orb.bmp");
}
// Start timer that draws game objects 50 times per second (50 FPS)
gameTimer = new javax.swing.Timer(gameTimerDelay, gameTimerAction);
gameTimer.setInitialDelay(0);
gameTimer.start();
}
ActionListener gameTimerAction = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
repaint();
}
};
class GraphicsPanel extends JPanel
{
public GraphicsPanel()
{
}
// Draw all of the components
#Override
public void paintComponent(Graphics g)
{
Graphics2D g2D = (Graphics2D) g;
super.paintComponent(g2D);
g2D.drawImage(lightOrb, x, y, this);
g2D.dispose();
}
}
}
After some debugging with breakpoints and println methods, I can confirm that the correct image is being read, the timer in gameTimerAction is being called 50 times per second, and repaint() is not invoking paintComponent() at all.
I am somewhat new to Java programming, and might just be missing something simple.
Edit: Problem has been solved by changing gamePanel to a GraphicsPanel object. Unfortunately, this also means that my much larger pong project (which this project's flawed drawing logic was essentially copied from) only worked by a miracle, and might be unstable with certain code additions.
I can immediately see several problems:
Most Important: You never instantiate a GraphicsPanel object, nor do you add it to anything. The paintComponent(...) method will never be called on a JPanel that is neither rendered nor created. Why not make your gamePanel variable a GraphicsPanel object and not a JPanel object?
You never change x and y in your Timer, and so without change, no animation will occur.
Also you're calling dispose on a Graphics object given to you by the JVM, something you should never do. This breaks the Swing painting chain making the graphics of your GUI unstable.
So keep at it, you'll get there.
For example:
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
public class BulletExample extends JPanel {
public static final String IMG_PATH = "http://www.i2clipart.com/cliparts/f/0/5/8/clipart-blue-circle-f058.png";
private static final int PREF_W = 700;
private static final int PREF_H = PREF_W;
private static final int TIMER_DELAY = 20;
private BufferedImage bullet;
private int bulletX;
private int bulletY;
public BulletExample() throws IOException {
URL imgUrl = new URL(IMG_PATH);
bullet = ImageIO.read(imgUrl);
new Timer(TIMER_DELAY, new BulletListener()).start();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (bullet != null) {
g.drawImage(bullet, bulletX, bulletY, this);
}
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private class BulletListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
bulletX++;
bulletY++;
repaint();
}
}
private static void createAndShowGui() throws IOException {
// create the drawing JPanel
BulletExample mainPanel = new BulletExample();
JFrame frame = new JFrame("BulletExample");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// add it to the JFrame
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
createAndShowGui();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
Eventually after I work out this small detail it will receive a building and room number to outline said building and room number so it is easy to locate but I can't get the rectangle to draw even close to acurately over a single room.
package programSTLApp;
/*
Program to request the classroom no. in STLCC and Display the location of
that classroom.
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class STLApp extends JFrame
{
private JLabel imageLabel;
private JButton button;
private JPanel imagePanel;
private JPanel buttonPanel;
public STLApp()
{
super("My STLCC Class Locator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
buildImagePanel();
buildButtonPanel();
add(imagePanel, BorderLayout.CENTER);
add(buttonPanel,BorderLayout.SOUTH);
pack();
setVisible(true);
}
private void buildImagePanel()
{
imagePanel = new JPanel();
imageLabel = new JLabel("Click the button to see the drawing indicating "
+ "the location of your class");
imagePanel.add(imageLabel);
}
private void buildButtonPanel()
{
buttonPanel = new JPanel();
button = new JButton("Get Image");
button.addActionListener(new ButtonListener());
buttonPanel.add(button);
}
private class ButtonListener implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
ImageIcon SiteLayoutFV = new ImageIcon("D:\\B120.jpg");
imageLabel.setIcon(SiteLayoutFV);
imageLabel.setText(null);
pack();
}
}
public void paint(Graphics g)
{
super.paint(g);
g.setColor(Color.RED);
g.fillRect(55,740,164,815);
}
public static void main(String[] args)
{
new STLApp();
}
}
As has already being pointed out, top level containers ain't a studiable class for performing custom painting, there is just to much going with these containers to make it easy to paint to.
Instead, create yourself a custom component, extending from something like JPanel, and override it's paintComponent method.
Once you have the floor pane rendered, you can render you custom elements over the top of it.
How you store this information is up to you, but basically, you need some kind of mapping that would allow you to take the floor/room and get the Shape that should be rendered.
Because the floor map might float (it may not always be rendered at 0x0 for example), you need to be able to translate the coordinates so that the Shape will always match.
Take a look at...
Performing Custom Painting
2D Graphics
For more details
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class FloorPlan {
public static void main(String[] args) {
new FloorPlan();
}
public FloorPlan() {
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.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private BufferedImage floorPlan;
private Rectangle myOffice = new Rectangle(150, 50, 32, 27);
public TestPane() {
try {
floorPlan = ImageIO.read(new File("floorPlan.png"));
} catch (IOException ex) {
ex.printStackTrace();
}
}
#Override
public Dimension getPreferredSize() {
return floorPlan == null ? new Dimension(200, 200) : new Dimension(floorPlan.getWidth(), floorPlan.getHeight());
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
if (floorPlan != null) {
int x = (getWidth() - floorPlan.getWidth()) / 2;
int y = (getHeight() - floorPlan.getHeight()) / 2;
g2d.drawImage(floorPlan, x, y, this);
g2d.setColor(Color.RED);
g2d.translate(x, y);
g2d.draw(myOffice);
}
g2d.dispose();
}
}
}
I'm trying to make a simple GUI using JAVA
no image is shown
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.swing.*;
import javax.imageio.*;
public class EmiloLadderSnack {
public JFrame frame=new JFrame("EmiloLadderSnack");
public Image img;
public Graphics g;
public EmiloLadderSnack()
{
frame.setBounds(0, 0, Toolkit.getDefaultToolkit().getScreenSize().width, Toolkit.getDefaultToolkit().getScreenSize().height);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
try
{
img= ImageIO.read(new File("/media/01CCE00FA6888D80/Achieve/Eclipse/EmiloLadderSnack/src/photo.jpg"));
g.drawImage(img, 50, 50, null);
}
catch(Exception e)
{
System.out.println(e.toString());
}
}
public static void main(String args[])
{
new EmiloLadderSnack();
}
}
please help me to show an image in my simple GUI using JAVA
I'm using Eclipse
Hovercraft Full Of Eels is right, as he/she usually is. It really did not look like you tried.
Look at the tutorials, but I do believe when Hovercraft Full Of Eels says the correct way, hover means as follows.
Let me explain what I did below. First I created a new class that extended the JFrame. The JFrame is what is suppose to hold all of the components in a window. Then draw on the JPanel so that all of your drawings are contained in a lightweight container. I set the layout with a new layout I just discovered due to StackOverflow which I am very thankful for. The layout is called the MigLayout and it is a third party resource. You have to download it and import it. Please note that you do not have to have the MigLayout, but it is preferable to use due to its ease of use. After I set the Layout Constraint to fill and docked the JPanel in the center I created a new class which extended the JPanel so that I could change the paint method. The #Override lets you, in a way, re create the method for that extended class. As you can see once draw to that one graphics class then you are all set. There is a lot more you should read up on. Read the comments below your post, they suggest fairly good material.
Anything I get wrong Hovercraft will say below in the comments. So look for that as well.
Hovers corrections:
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class GraphicExample extends JPanel {
private static final String IMG_FILE_PATH = "/media/01CCE00FA6888D80/" +
"Achieve/Eclipse/EmiloLadderSnack/src/photo.jpg";
private BufferedImage img;
public GraphicExample(BufferedImage img) {
this.img = img;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (img != null) {
g.drawImage(img, 0, 0, this);
}
}
#Override
public Dimension getPreferredSize() {
if (img != null) {
return new Dimension(img.getWidth(), img.getHeight());
}
return super.getPreferredSize();
}
private static void createAndShowGui() {
try {
BufferedImage img = ImageIO.read(new File(IMG_FILE_PATH));
JFrame frame = new JFrame("GraphicExample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new GraphicExample(img));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
// the easy way to display an image -- in a JLabel:
ImageIcon icon = new ImageIcon(img);
JLabel label = new JLabel(icon);
JOptionPane.showMessageDialog(frame, label);
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
My initial recommendations:
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
import net.miginfocom.swing.MigLayout;
public class DrawCircle extends JFrame {
JPanel panel;
public DrawCircle(String title, int width, int height) {
this.setTitle(title);
this.setSize(width, height);
this.setLocationRelativeTo(null); // Center JFrame
this.setLayout(new MigLayout("fill")); // Download external jar
this.panel = new DrawOval();
this.add(panel, "dock center"); // Link: http://www.miglayout.com/
this.setVisible(true);
}
public class DrawOval extends JPanel {
Color color = new Color(1, 1, 1);
public DrawOval() {
}
#Override
public void paint(Graphics g) {
g.setColor(color.RED);
g.fillOval(0, 0, this.getWidth(), this.getHeight());
}
}
}
I can't imagine that this is compiling. There must be a NullPointerException.
When you want to draw something you usually subclass JPanel and do the drawing in the paintComponent() method, like this:
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(img, 50, 50, null);
}