Java: paintComponent() Oval is not appearing in Netbeans - java

I'm trying to learn how to draw an oval in java but the paintComponent I made is not being called by anything, and attempting to call it only causes more issues.
The program runs successfully but the image I want displayed isn't showing up.
import java.awt.*;
import javax.swing.*;
public class TEST2{
public void paintComponent(Graphics g){
g.drawOval(70, 70, 100, 100);
}
public static void main(String[] args) {
TEST2 gui = new TEST2();
gui.setUpFrame();
}
public void setUpFrame(){
JFrame frame = new JFrame();
frame.setTitle("Images should be in this program");
frame.setSize(600,300);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

Start by taking a look at Painting in AWT and Swing and Performing Custom Painting
In order to be able to perform custom painting in Swing, you must...
Inherit from a swing based component (like JComponent or JPanel)
You must then override it's paintComponent method and perform you custom painting within this method.
Add this component to something that is displayable (like a JFrame)
You should make sure to call super.paintComponent before doing any custom painting
To ensure that you're not making any (common) mistakes, you should use the #Override annotation
As an example...
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test2 extends JPanel {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawOval(70, 70, 100, 100);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
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.setTitle("Images should be in this program");
frame.add(new Test2());
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
});
}
}

The paintComponent() method is a method that you override and it should be accessed inside a class that extends JPanel. You can create a new class that extends JPanel and override the paintComponent() method to draw your oval. You will also have to add the new JPanel to your JFrame for it to display. I modified your code below it should display the oval now. As Madprogrammer noted you should probably construct your GUI within the context of the edt to avoid concurrency issues but I will omit that for simplicity.
import java.awt.*;
import javax.swing.*;
public class Test {
public static void main(String[] args) {
Test gui = new Test();
gui.setUpFrame();
}
public void setUpFrame() {
JFrame frame = new JFrame();
frame.setTitle("Images should be in this program");
frame.setSize(600, 300);
JPanel oval = new oval();
frame.setContentPane(oval);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public class oval extends JPanel{
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawOval(70, 70, 100, 100);
}
}
}

Related

Adding JPanel to JLayeredPane causes paint() method to not get called

To provide some background info that might help, I am creating the game pong and I decided to add an escape/pause menu (when you press escape on the keyboard a menu pops up with some settings), I looked around and found that the best way to do this is to use JLayeredPane and add another JPanel on top. However, when I added my 'painter' class to the JLayeredPane, the paint(Graphics g) method stopped getting called (it worked fine when I just added it to the JFrame).
import javax.swing.*;
public class Game extends JFrame {
public static Painter painter;
public Game() {
setSize(500, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLayeredPane lp = getLayeredPane();
painter = new Painter();
add(lp);
}
public static void main(String[] args) {
Game frame = new Game();
frame.setVisible(true);
painter.repaint();
}
}
And here is my Painter class
import java.awt.*;
import javax.swing.*;
public class Painter extends JPanel {
public void paint(Graphics g) {
System.out.println("Working");
super.paint(g);
}
}
Instead of add(lp);, I originally tried lp.add(painter); in which case the paint method never got called. By doing add(lp) I get an IllegalArgumentException for adding container's parent to itself.
Here is mcve of using LayeredPane :
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
public class Game extends JFrame {
public Game() {
setSize(250, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLayeredPane lp = getLayeredPane();
//assign layout manager. otherwise you need to set content
//bounds (not recommended)
lp.setLayout(new BorderLayout());
Painter painter = new Painter();
lp.add(painter,1);
}
public static void main(String[] args) {
Game frame = new Game();
frame.setVisible(true);;
}
}
class Painter extends JPanel {
#Override
protected void paintComponent(Graphics g) { //do not override paint
super.paintComponent(g);
g.drawString("Working",50,50);
}
}

paintComponent is not working at all

I'm using paintComponent to make a GUI for a class assignment and it's just not affecting the appearance of the GUI at all. To start, I'm just setting the background to white. The following code works:
import javax.swing.*;
import java.awt.*;
public class PA05a extends JPanel {
public static void main(String[] args) {
JFrame window = new JFrame("MouseDrawDemo");
JPanel content = new JPanel();
content.setBackground(Color.WHITE);
window.setContentPane(content);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setLocation(120,70);
window.setSize(400,300);
window.setVisible(true);
}
}
but this does not:
import javax.swing.*;
import java.awt.*;
public class PA05a extends JPanel {
public static void main(String[] args) {
JFrame window = new JFrame("MouseDrawDemo");
JPanel content = new JPanel();
window.setContentPane(content);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setLocation(120,70);
window.setSize(400,300);
window.setVisible(true);
}
#Override
public void paintComponent(Graphics g) {
//add backdrop
super.paintComponent(g);
g.setColor(Color.WHITE);
g.fillRect(0,0,getWidth(),getHeight());
}
}
I can't just not use paintComponent because I'll later be adding things that will change from frame to frame. Can someone pinpoint where I'm missing something?
JPanel content = new PA05a();
You did not create an object of PA05a. ;)
You just forgot to create your object. Change your code to:
import javax.swing.*;
import java.awt.*;
public class PA05a extends JPanel {
public static void main(String[] args) {
JFrame window = new JFrame("MouseDrawDemo");
JPanel content = new PA05a();
window.setContentPane(content);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setLocation(120,70);
window.setSize(400,300);
window.setVisible(true);
}
#Override
public void paintComponent(Graphics g) {
//add backdrop
super.paintComponent(g);
g.setColor(Color.WHITE);
g.fillRect(0,0,getWidth(),getHeight());
}
}

JPanel drawing - why do I have to override paintComponent method?

I am learning Java and I have started to play with drawing possibilities.
Basically I have 2 questions:
Why do I have to override paintCompoment method in order to paint something on JPanel?
Taking into account the first example when I call f.add(new MyPanel()); it creates a new MyPanel object and draw the text. How come the text is drawn? Method paintComponent(g) is not called.
To me it looks like I have two options:
First one (from http://docs.oracle.com/javase/tutorial/uiswing/painting/step2.html):
package painting;
import javax.swing.SwingUtilities;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.BorderFactory;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
public class SwingPaintDemo2 {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI() {
System.out.println("Created GUI on EDT? "+
SwingUtilities.isEventDispatchThread());
JFrame f = new JFrame("Swing Paint Demo");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new MyPanel());
f.pack();
f.setVisible(true);
}
}
class MyPanel extends JPanel {
public MyPanel() {
setBorder(BorderFactory.createLineBorder(Color.black));
}
public Dimension getPreferredSize() {
return new Dimension(250,200);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
// Draw Text
g.drawString("This is my custom Panel!",10,20);
}
}
Second one: which works as well
Graphics g = panel.getGraphics();
g.setColor(new Color(255, 0, 0));
g.drawString("Hello", 200, 200);
g.draw3DRect(10, 20, 50, 15, true);
panel.paintComponents(g);
You are not supposed to call paintComponent() yourself.
The paintComponent() is called automatically (by the UI thread).
If you leave the paintComponent() method empty, it will be invoked but nothing will be painted because it is empty.

Java graphics - failing to paint properly

Learning to use graphics in java and currently at the moment i'm trying to add some graphics to the screen but failing. I've tried different approaches in a trial and error fashion yet had no luck. The code shown, the structure cannot change in terms of having paint method in a separate class for example. Its a simplified version on a project I’m working on.
Other questions on stackoverflow have helped to an extend and similar with the oracle website but I'm still facing issues hence why I am asking here.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class test
{
public static void main(String Args[])
{
panelme p1 = new panelme();
}
}
class panelme
{
JFrame mainPanel;
panelme ()
{
mainPanel = new JFrame();
mainPanel.setSize(1000,1000);
mainPanel.setDefaultCloseOperation(mainPanel.EXIT_ON_CLOSE);
//paintFrame();
//paintFrame(g);
//paintFrame(null);
mainPanel.setVisible(true);
}
public void paintFrame(Graphics g)
{
g.drawString("This is a string!", 30, 40);
//repaint();
}
}
Start by taking a look at Painting in AWT and Swing and Performing Custom Painting for more details about how painting works in Swing
Next, take a look at 2D Graphics trail
Next, create your self a custom class which extends from JPanel and then override it's paintComponent method and place your custom painting within it...
public class PaintPane extends JPanel {
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString("This is a string!", 30, 40);
}
}
Next, add your custom panel to a window...
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 PaintPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});

Issue with this simple code

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MyDrawPanel extends JPanel{
public void paintComponents(Graphics g){
g.setColor(Color.orange);
g.fillRect(20,50,100,100);
}
public static void main(String[] args){
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.getContentPane().add(paintComponents(g));
frame.setVisible(true);
}
}
I think I should add something arguments in frame.getContentPane().add(paintComponents(g));.
I looked up Graphics class but I'm still struggling with it. What should be the parameter of it?
try this
public class MyDrawPanel extends JPanel{
MyDrawPanel()
{
setOpaque(true);
}
protected void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.orange);
g.fillRect(20,50,100,100);
}
public static void main(String[] args){
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new MyDrawPanel());
frame.setBounds(10,10,500, 500);
frame.setVisible(true);
}
}
I'm no awt expert, but what I think you want to do is add a Canvas object to your content pane from the JFrame, then paint a Graphics object on it.
Okay, this is what I came up with:
public class MyDrawPanel extends JPanel
{
private static void createAndShowGUI()
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
MyDrawPanel panel = new MyDrawPanel();
panel.setOpaque(true);
frame.getContentPane().add(panel);
frame.setVisible(true);
}
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.orange);
g.fillRect(20,50,100,100);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run()
{
createAndShowGUI();
}
});
}
}
Notes:
There are several problems with your line frame.getContentPane().add(paintComponents(g));. What you said is "add to the content pane the result of calling paintComponents on g. Where did g come from? You can not used a variable until declared. The result of calling paintComponents is void which means the result cannot be used as an argument to a method. Presumably you had compiler errors.
I changed paintComponents to paintComponent. The former is used to control painting of subcomponents and in general should not be overridden.
Swing objects should not be created on the main thread. The details are complicated for a beginner (and described here in detail). Mostly you can just memorize the SwingUtilities.invokeLater pattern used above.

Categories

Resources