load image to JPanel not working - java

For two days I was trying to load an image into JPanel from a file. I couldn't!
I used JLabel and Icon and it's loaded okay, but I need to load the image to a JPanel directly, is that impossible?
Because almost I saw many and many related problems like this and many people recommended the person who asks the question to load the image into a label!
this is the code :
public class ReadingImage extends JPanel {
JPanel panel;
JFrame frame;
JPanel secPanel;
private BufferedImage img;
public ReadingImage(String path){
frame = new JFrame();
frame.setVisible(true);
frame.setLocation(300, 300);
frame.setSize(300, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
secPanel = new JPanel();
secPanel.setVisible(true);
//secPanel.setLayout(new FlowLayout());
secPanel.repaint();
frame.getContentPane().add(secPanel);
try{
FileImageInputStream fi = new FileImageInputStream(new File(path));
//System.out.println(path);
img = ImageIO.read(fi);
this.repaint();
}
catch (IOException io ){ io.printStackTrace();}
}
#Override
protected void paintComponent(Graphics g){
super.paintComponents(g);
if (img!=null){
g.drawImage(img, 0, 0, this);
repaint();
}
}
}
It's not throwing any exception, but it's not displaying the image in the JPanel!
I adjusted the code many and many times..
any help in this :)
thanks,

Classic confusion caused by extending JPanel and using another JPanel. Replace frame.getContentPane().add(secPanel) with frame.add(this , BORDERLAYOUT.CENTER) and everything should work fine.

You are calling super.paintComponents(g); in paintComponent, not the s at the end, this is going to cause a StackOverflowException eventually, but don't actually ever add the ReadingImage JPanel to anything, so it's never actually painted
This means that there doesn't seem to be any point any point to the secPane
You should also avoid creating frames from within other components, especially from within the constructor, it provides a very limit use case for the component
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.imageio.stream.FileImageInputStream;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class ReadingImage extends JPanel {
private BufferedImage img;
public ReadingImage(String path) {
try {
FileImageInputStream fi = new FileImageInputStream(new File(path));
img = ImageIO.read(fi);
this.repaint();
} catch (IOException io) {
io.printStackTrace();
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (img != null) {
g.drawImage(img, 0, 0, this);
repaint();
}
}
public static void main(String[] args) {
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();
frame.add(new ReadingImage("Your image"));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(300, 300);
frame.setSize(300, 500);
frame.setVisible(true);
}
});
}
}
I'm not sure exactly what you are trying to achieve, but I would also encourage you to override the ReadingImage's getPreferredSize method and return the size of the image, this makes it easier to layout

first load the image in Image Icon, lets say the object as 'pic'.
panel1.add(new JLabel(pic));
add and set panel1 to visible.

Related

Layering text over JLabel

This is how I want my app to look like.
Trouble is, if I drag the JLabel with the "Hello, I'm Myra" over another JLabel (whose icon is the speech bubble), rather than superimposing or layering, NetBeans shifts the JLabels to be adjacent.
How do I superimpose ie. place the text JLabel on top of another JLabel?
Do note, I'm using NetBeans. It doesn't allow me to edit much of the JFrame or JLabel code.
Netbeans won't let you add components to a JLabel, it doesn't see them as a valid Container.
This won't be easily achieved using component labels, as the icon placement is outside of your control. A better solution might be to use a custom component, such as a JPanel and manually draw the speech bubble image yourself, then using a combination of Border and LayoutManager it would allow you to add other components to it
This is a very basic example...
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
public class SpeechBubble {
public static void main(String[] args) {
new SpeechBubble();
}
public SpeechBubble() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
SpeechBubblePane bubble = new SpeechBubblePane();
JLabel hello = new JLabel("Hello, I'm Myra");
hello.setFont(hello.getFont().deriveFont(28f));
hello.setForeground(Color.CYAN);
JLabel message = new JLabel("<html>What would you like to know today?</html>");
message.setFont(message.getFont().deriveFont(22f));
message.setForeground(Color.WHITE);
bubble.setLayout(new GridLayout(2, 1));
bubble.add(hello);
bubble.add(message);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setBackground(Color.BLACK);
frame.add(bubble);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class SpeechBubblePane extends JPanel {
private BufferedImage background;
public SpeechBubblePane() {
setOpaque(false);
try {
background = ImageIO.read(getClass().getResource("/speechbubble.png"));
} catch (IOException ex) {
ex.printStackTrace();
}
setBorder(new EmptyBorder(19, 19, 66, 19));
}
#Override
public Dimension getPreferredSize() {
Dimension size = new Dimension(200, 200);
if (background != null) {
size = new Dimension(background.getWidth(), background.getHeight());
}
return size;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (background != null) {
Graphics2D g2d = (Graphics2D) g.create();
int x = (getWidth() - background.getWidth()) / 2;
int y = (getHeight()- background.getHeight()) / 2;
g2d.drawImage(background, x, y, this);
g2d.dispose();
}
}
}
}
If I was doing this, I would consider developing up a "9-path" which would allow you to break the image down into 9 parts and scale the outer sections based on what the content requires, for example...
It sounds like you just want to add a z-order. If so, you need a LayeredPane:
http://docs.oracle.com/javase/7/docs/api/index.html
http://docs.oracle.com/javase/7/docs/api/javax/swing/JLayeredPane.html

ImageIcon click and drag around the window

I'm trying to make it so I can click and drag an ImageIcon (in this case a card image but I'd like to learn how to do it generally) around the window but I don't really know how. I would like to be able to click and hold the mouse botton, drag the ImageIcon, and have stay where it is whn I release the mouse botton.
This is the code I have so far:
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class MyFirstClass
{
public static void main(String[] args)
{
//load the card image from the gif file.
final ImageIcon cardIcon = new ImageIcon("cardImages/tenClubs.gif");
JLabel lbl = new JLabel(cardIcon);
//create a panel displaying the card image
JPanel panel = new JPanel()
{
//paintComponent is called automatically by the JRE whenever
//the panel needs to be drawn or redrawn
public void paintComponent(Graphics g) {
super.paintComponent(g);
cardIcon.paintIcon(this, g, 20, 20);
}
};
lbl.setTransferHandler(null);
MouseListener listener = new MouseAdapter() {
public void mousePressed(MouseEvent me) {
JComponent comp = (JComponent) me.getSource();
TransferHandler handler = comp.getTransferHandler();
handler.exportAsDrag(comp, me, TransferHandler.COPY);
}
};
lbl.addMouseListener(listener);
//create & make visible a JFrame to contain the panel
JFrame window = new JFrame("Cards");
window.add(panel);
window.setPreferredSize(new Dimension(200,200));
window.pack();
window.setVisible(true);
}
}
Thank you.
The problem is you're mixing paradigms...not to mention you never seem to add lbl to anything, so it could never possible receive events and the fact that the panel is under the control of a layout manager, making moving a component very difficult...
In Swing there are at least three different ways to drag something, which you use comes down to what it is you want to achieve.
You can...
Use MouseListener and MouseMotitionListener to perform the actions manually. This is useful if you want to physical place an object somewhere within the container, like you are trying to do, for example...
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
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 DragMe {
public static void main(String[] args) {
new DragMe();
}
public DragMe() {
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 img;
private Point imgPoint = new Point(0, 0);
public TestPane() {
try {
img = ImageIO.read(new File("Computer.png"));
} catch (IOException ex) {
ex.printStackTrace();
}
MouseAdapter ma = new MouseAdapter() {
private Point offset;
#Override
public void mousePressed(MouseEvent e) {
Rectangle bounds = getImageBounds();
Point mp = e.getPoint();
if (bounds.contains(mp)) {
offset = new Point();
offset.x = mp.x - bounds.x;
offset.y = mp.y - bounds.y;
}
}
#Override
public void mouseReleased(MouseEvent e) {
offset = null;
}
#Override
public void mouseDragged(MouseEvent e) {
if (offset != null) {
Point mp = e.getPoint();
imgPoint.x = mp.x - offset.x;
imgPoint.y = mp.y - offset.y;
repaint();
}
}
};
addMouseListener(ma);
addMouseMotionListener(ma);
}
protected Rectangle getImageBounds() {
Rectangle bounds = new Rectangle(0, 0, 0, 0);
if (img != null) {
bounds.setLocation(imgPoint);
bounds.setSize(img.getWidth(), img.getHeight());
}
return bounds;
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (img != null) {
Graphics2D g2d = (Graphics2D) g.create();
g2d.drawImage(img, imgPoint.x, imgPoint.y, this);
g2d.dispose();
}
}
}
}
You can...
Use the core Drag-n-Drop APIs. This very low level and provides you are wide variety of flexibility. You can drag components, data or sorts of stuff based on your needs...
For example:
java drag and drop
How to drag and drop JPanel with its components
move component after drag and drop
And if you're really adventurous, you can take a look at these...
My Drag Image is Better than Yours
Drop Target Navigation, or You Drag Your Bags, Let the Doorman Get the Door
Smooth JList Drop Target Animation
You can..
Make use of the new transfer API. The intention of this API is to make it easier to transfer data around the application. While, technically, it would be possible to move a component this way, this is not it's intention.
Take a look at...
Drag and Drop and Data Transfer
Introduction to the DnD API
How to drag and drop with Java 2, Part 1
For more details...

I'm trying to draw a filled rectangle over an imageIcon using the coordinates of the image and the rectangle appears off

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();
}
}
}

Undecorated JFrame shadow

How do you add a shadow to a undecorated jframe?
From what I found online, you might be able to add the jframe to another black translucent window to give a shadow effect.
Or somehow apply something like this to a JFrame:
Border loweredBorder = new EtchedBorder(EtchedBorder.LOWERED);
setBorder(loweredBorder);
Either way I just want to know the best method or maybe a completely different way of getting the same effect like extending from another class and not jframe.
I'm new to Java so I might be going down the wrong direction so any advice is appreciated.
Basically, you need to make a series of layers.
JFrame
ShadowPanel
and content...
import java.awt.AlphaComposite;
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.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
public class ShadowWindow {
public static void main(String[] args) {
new ShadowWindow();
}
public ShadowWindow() {
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.setUndecorated(true);
frame.setBackground(new Color(0, 0, 0, 0));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new ShadowPane());
JPanel panel = new JPanel(new GridBagLayout());
panel.add(new JLabel("Look ma, no hands"));
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class ShadowPane extends JPanel {
public ShadowPane() {
setLayout(new BorderLayout());
setOpaque(false);
setBackground(Color.BLACK);
setBorder(new EmptyBorder(0, 0, 10, 10));
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setComposite(AlphaComposite.SrcOver.derive(0.5f));
g2d.fillRect(10, 10, getWidth(), getHeight());
g2d.dispose();
}
}
}
MadProgammer,
frame.setBackground(new Color(0, 0, 0, 0));
is useless if you don't use also:
frame.setOpacity(1.0f);
Setting the default close operation to EXIT_ON_CLSE is bad, the app should close naturely with the end of both processes, so DISPOSE_ON_CLOSE is the right way, reserving the other one to "fix" bugs.
frame.setContentPane(new ShadowPanel());
is useless if you use also (and after):
frame.add(panel);
ShadowPanel's constructor should start with:
super(new GridBagLayout());
instead of:
setLayout(new GridBagLayout());
Additionnally, using a GridBagLayout to only add a single component is a bit disproportionned, isn't it ? What about a GridLayout(1, 1) or even a lazy BorderLayout ?
Return a new Dimension on each call on the preferred size (many of them are done by the machine, during a lot of operation, like repainting, etc) is very expensive. You should return a variable defined in the constructor or the class.
Why override getPreferredSize(), but not getBackground(), nor isOpaque() ?
GraphicsD should be placed inside a try block to dispose of it inside a finally block.

JAVA Showing Image -GUI

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);
}

Categories

Resources