I have issue with drawing shapes inside of JPanel that I already added using Netbeans GUI. Now, I have no idea where to add code for drawing a circle inside of that JPanel and how to insert and call it in the JPanel that is sitting empty now, waiting for this shape to be drawn. I already set up destination JPanel to be Flow layout.
Netbeans Designer created a big class in which I have entire frame with this JPanel, and I want to keep it inside of it as I can't really add it any other way because Designer doesn't let me change main initComponents method in which all components are sitting now. I have been reading tutorials and previous posts but noone really encountered this using Netbeans Designer.
SO can someone just help me with adding proper method in this frame class and how to call it from JPanel I want to draw in. JPanel is 50x50 pixels.
So as per #Abra, I changed some code:
so I made a new Circle Class, adjusted it a bit as I don't want to create a new frame but put this in JPanel.
public class Circle extends JPanel {
Color color;
public void circle(Color color) {
this.color = color;
setPreferredSize(new Dimension (30,30));
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawOval(0, 0, r, r);
g.setColor(color);
}
private void showGUI() {
JPanel panel = new JPanel();
panel.add(this, FlowLayout.CENTER);
panel.setVisible(true);
}
}
Then I opened JPanel in Designer, and added code to run it, in initComponents method like this:
circlePanel.setPreferredSize(new java.awt.Dimension(40, 40));
new Circle().showGUI();
PanelDS.add(circlePanel);
circlePanel is destination for this drawing and is inside PanelDS itself. It doesn't work this way tho, but Netbeans shows no errors in code. Additionally, how can I forward color to circle class.
In order to draw on a JPanel you need to override the paintComponent() method of JPanel. In order to override the method, you need to create a class that extends JPanel. I don't think that there exists a GUI designer that can generate the required code for you. So you have to write the code of the class that extends JPanel.
Here is a minimal example. It displays a blue circle.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
public class Drawing2 extends JPanel {
private JFrame frame;
public Drawing2() {
setPreferredSize(new Dimension(100, 100));
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLUE);
g.fillOval(25, 25, 50, 50);
}
private void showGui() {
frame = new JFrame("Drawing");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(this, BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
new Drawing2().showGui();
}
}
Here's what you should see when you run the above code.
Related
This question already has an answer here:
Can't draw to JPanel with getGraphics
(1 answer)
Closed 4 years ago.
I'm having trouble getting the graphics of my JPanel to work. It refuses to draw anything, regardless of anything I've tried and anything I can find on the internet.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.Timer;
import java.util.*;
import java.io.*;
public class Mandelbrot{
public static void main(String[] args){
JFrame win=new JFrame();
JPanel dis=new JPanel();
win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
win.setResizable(false);
win.setVisible(true);
win.add(dis);
dis.setPreferredSize(new Dimension(1000,500));
win.pack();
Graphics g=dis.getGraphics();
g.setColor(Color.red);
g.fillRect(0, 0, 100, 100);
}
}
Posting as an answer because I ran out of comment room:
Note:
If you need to be constantly changing things, then a JPanel is probably not your best option. I recommend you rethink what you are trying to do because you should probably use a Canvas or paint to a bunch of different labels/glass panes and overlay them however you want, this will allow you to have moving components/animations in a foreground item, and make different changes to the background item.
Alternatively, you can make the JPanel draw a buffered image, or you can store a list of items to paint, and you can paint them each time. For the buffered image method you can directly edit and draw to the buffered image every time you need to make a change.
Below is an example of how to use the buffered image method.
First create a custom JPanel in a new class:
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;
public class DrawPanel extends JPanel{
public BufferedImage canvas = new BufferedImage(panelWidth, panelHeight, BufferedImage.TYPE_INT_ARGB);
#Override
public void paintComponent(Graphics g){
//Draw the canvas
g.drawImage(canvas, 0, 0, this);
}
}
Now in your main method you can replace JPanel dis=new JPanel() with this:
DrawPanel dis = new DrawPanel();
Graphics g=dis.canvas.getGraphics();
g.setColor(Color.red);
g.fillRect(0, 0, 100, 100);
Note how I use dis.canvas to get the graphics of the bufferedImage instead of the graphics of the JPanel.
It's as simple as that.
As per Andrews comment. You should consider extending a JLabel instead of a JPanel, it is much more lightweight, and easier to update using label.repaint();.
public static void main(String... args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
JPanel panel = new JPanel() {
#Override
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.red);
g.fillRect(0, 0, 100, 100);
}
};
panel.setPreferredSize(new Dimension(640, 480));
frame.add(panel);
frame.setVisible(true);
frame.pack();
}
Just an example - you should create a new Class subclassing JPanel, see Painting in AWT and Swing.
I've tried to research how Java's 2D rendering works, but I could never understand it. Here is the code in my main class:
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main{
public static void main(String args[]) {
JFrame frame = new JFrame();
frame.setSize(new Dimension(500,500));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("JFrame testing");
frame.setVisible(true);
Frame panel = new Frame();
frame.add(panel);
}
}
And then here is for the JPanel class:
import java.awt.Graphics;
import javax.swing.JPanel;
public class Frame extends JPanel{
private static final long serialVersionUID = 1L;
public Frame() {
Graphics g = this.getGraphics();
g.drawRect(0, 0, 100, 100);
this.paintComponent(g);
}
}
I am also getting this exception, but I'm not sure what it means:
Exception in thread "main" java.lang.NullPointerException
at Frame.<init>(Frame.java:10)
at Main.main(Main.java:18)
I'm basically just trying to draw a rectangle onto a panel to be shown on the frame I've created. I've heard about the paintComponent method, but I also don't fully understand that.
You should Never use getGraphics() of a Component.
Try below code
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawRect(0, 0, 100, 100);
//this.paintComponent(g);
}
Edit
"why is super.paintComponent(g); called again inside the method?"
The documentation of paintComponent says it pretty well:
if you do not invoker super's implementation you must honor the opaque
property, that is if this component is opaque, you must completely
fill in the background in a non-opaque color. If you do not honor the
opaque property you will likely see visual artifacts.
I'm practising to draw a shape on a JPanel by clicking on a Jbutton, but I cannot. It's been five hours that I'm surfing the web, but I cannot find the way to do it.
This is what I want to do: if I click on "Rectangle" button a rectangle appears under the buttons and if I click on "Circle" button a circle appears.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Shape extends JFrame {
JButton rec, circle;
static String botSelected;
Shape (){
frameSet ();
}
void frameSet(){
JFrame frame = new JFrame();
frame.setVisible(true);
frame.setSize(600,300);
rec = new JButton ("Rectangle");
circle = new JButton("Circle");
JPanel panel = new JPanel();
frame.add(panel);
panel.add(rec);
panel.add(circle);
Click clk = new Click();
rec.addActionListener(clk);
circle.addActionListener(clk);
}
public void paint (Graphics g){
super.paint(g);
if (botSelected.equals("Rectangle"))
g.fillRect(50,50,50,50);
else if (botSelected.equals("Circle"))
g.fillOval(50,50,50,50);
}
public static void main (String [] arg){
Shape s = new Shape();
}
}
class Click implements ActionListener{
public void actionPerformed (ActionEvent e){
Shape.botSelected = e.getActionCommand();
}
}
The first thing I would do is have a read through Painting in Swing and Performing custom painting to better understand how the painting process works.
Next you need to understand that JFrame is a bad choice for painting to. Why? Because it's multilayered.
A JFrame contains a JRootPane, which contains a JLayeredPane the contentPane, glassPane and the JMenuBar and in your example, it also contains a JPanel.
With the (default) exception of the glassPane, all these components are opaque.
While it's possible to have something drawn in the paint method show it, if any of the other components paint themselves, it will be wiped clean - this is because Swing components can actually be painted independently of each other, with having to have the parent paint itself first.
A better solution is to start by extending from JPanel and override its paintComponent method.
For simplicity, I'd also encourage you to implement the ActionListener against this class as well, it will allow the actionPerformed method to access the properties of the component and, in your case, call repaint to trigger a paint cycle when you want to update the UI.
Here is a derived example from your code.
As #MadProgrammer said, don't extend JFrame.
In the following example, here are the major changes :
give a non-null value to botSelected, or the first calls to paintComponent will give you a NullPointerException
the class now extends JPanel, and overrides paintComponent for custom painting
the ActionListener is an anonymous class, because you don't need a separate class, and it has direct access to the fields from Shape
botSelected is no longer static (see above point)
.
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
class Shape extends JPanel {
JButton rec, circle;
String botSelected = "";// don't let it be null, it would make paintComponent crash on startup
Shape() {
frameSet();
}
void frameSet() {
JFrame frame = new JFrame();
frame.setVisible(true);
frame.setSize(600, 300);
rec = new JButton("Rectangle");
circle = new JButton("Circle");
frame.add(this);
this.add(rec);
this.add(circle);
// anonymous class, has access to fields from the outer class Shape
ActionListener clk = new ActionListener() {
public void actionPerformed(final ActionEvent e) {
botSelected = e.getActionCommand();
repaint();
}
};
rec.addActionListener(clk);
circle.addActionListener(clk);
}
//custom painting of the JPanel
#Override
public void paintComponent(final Graphics g) {
super.paintComponent(g);
if (botSelected.equals("Rectangle")) {
g.fillRect(50, 50, 50, 50);
} else if (botSelected.equals("Circle")) {
g.fillOval(50, 50, 50, 50);
}
}
public static void main(final String[] arg) {
Shape s = new Shape();
}
}
I am working on an assignment (GASP) and having issues with my image displaying. I am not looking for someone to complete my assignment for me but I desperately need some help figuring out why my code is not working properly. I have reviewed my Java Programming book as well as searched for the answers online to no avail so if someone could lead me in the right direction I would greatly appreciate it!!
Here is my displayImage code:
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class DisplayImage extends JFrame {
public void DislayImage(){
add (new ImagePanel());
}
public static void main(String[] args) {
JFrame frame = new DisplayImage ();
frame.setTitle("Go Bearcats!");
frame.setSize(300, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
Assignment02 a = new Assignment02();
frame.add(a);
}
}
class ImagePanel extends JPanel {
public final static String LOC = "C:\\UCincinnatiLogo.jpg";
private ImageIcon imageIcon = new ImageIcon (LOC);
private Image image = imageIcon.getImage();
#Override /**Draw image on the panel*/
protected void paintComponent(Graphics g){
super.paintComponent(g);
if (image !=null)
g.drawImage(image, 200, 200, getWidth(), getHeight(), this);
}
}
You're adding a component right on top of your image panel. The JFrame uses borderLayout, so anything added to it as you're doing will cover anything added previously.
JFrame frame = new DisplayImage ();
frame.setTitle("Go Bearcats!");
frame.setSize(300, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
Assignment02 a = new Assignment02();
frame.add(a); // here you add something on top of your imagePanel
Instead, make the ImagePanel the JFrame's contentPane via setContentPane(...), and then add things to the JFrame/contentPane, but be sure that they're not opaque.
public class DisplayImage extends JFrame {
public void DislayImage(){
setContentPane(new ImagePanel());
}
and then,
Assignment02 a = new Assignment02();
a.setOpaque(false);
frame.add(a);
Note, as an aside, I rarely create any classes that extend JFrame, and instead create my JFrame when needed. Instead I'd create my ImagePane and then add components directly to it before adding all to a JFrame.
Also you don't show us the Assignment02 class, but it had better have non-opaque JPanels and components.
I got a class that's supposed to launch a game (with main()), and the game's opening screen. The class with main() (named Starter), that extends JFrame, creates a new OpeningScreen class (extending JPanel), and adds it to the JFrame.
For some reason, the OpeningScreen won't be added to the JFrame. Code:
Starter class:
import javax.swing.*;
import java.awt.*;
public class Starter extends JFrame {
public Starter(){
setSize(500,500);
setResizable(false);
setTitle("Ping-Pong Battle");
setDefaultCloseOperation(EXIT_ON_CLOSE);
OpeningScreen openingS = new OpeningScreen();
add(openingS);
setVisible(true);
}
public static void main(String[]args){
Starter starter = new Starter();
}
}
OpeningScreen class:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class OpeningScreen extends JPanel {
public OpeningScreen(){
setBackground(Color.BLACK);
setFocusable(true);
setVisible(true);
}
public void paint(Graphics g){
// Soon code here to be drawn.
}
public void startGame(){
Board board = new Board();
}
}
What's the problem? Thanks
EDIT: The constructor of OpeningScreen does run, but doesn't paint the background black. Also, trying to draw things in paint() doesn't work.
Your problem arises from overriding paint in your OpeningScreen class. The background is not drawn because you never draw it! Call super.paint(g) to fix this.
However, it is generally recommended to use paintComponent() instead of paint(). Just move your code to paintComponent.
This method correctly draws a black background a red square:
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g.fillRect(100, 100, 100, 100);
}
I think because you override paint() the background doesn't get painted, so it appears like the Panel isn't added. Commenting out the paint method results in the Window being black for me.
Also, drawing in the paint method works for me, maybe your color is set to black so it doesn't show on the black background ? Try g.setColor(Color.white) before drawing.