My Superclass is failing to use the method I created in my subclass. I get an error because I'm using the Graphics argument. What am I missing here?
I've tried the suggestions given by eclipse, however they result in more errors.
Here's my super class
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
public class GameScreen extends Canvas{
public GameScreen() {
}
public static void main(String[] args) {
// TODO Auto-generated method stub
//Sets Screen
JFrame jframe = new JFrame("Game Screen");
Canvas canvas = new GameScreen();
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
canvas.setBackground(Color.cyan);
canvas.setSize(1000,800);
jframe.add(canvas);
jframe.pack();
jframe.setVisible(true);
Paddle1.paint(Graphics g);
}
}
And here's my subclass
import java.awt.Color;
import java.awt.Graphics;
public class Paddle1 extends GameScreen {
public void paint(Graphics g) {
g.setColor(Color.white);
g.fillRect(50, 50, 40, 130);
}
}
The subclass creates a rectangle that is supposed to appear on top of the canvas
If you would like to trigger method "paint" of Paddle1, you have to modify your code as below:
JFrame jframe = new JFrame("Game Screen");
Canvas canvas = new Paddle1();
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
canvas.setBackground(Color.cyan);
canvas.setSize(1000,800);
jframe.add(canvas);
jframe.pack();
jframe.setVisible(true);
canvas.paint(g);
Related
I'm new in java swing programming. What i'm trying to do is paint a string to a specific location in a JPanel. The JPanel is very large and so i add it to a JScrollpane, but when i draw the string it is printed not just in the specified location but also in others.
The first image represents the bottom of the panel where i decided to draw the string and this is correct. But if you observe whole the panel you can find the string too in others locations (see second image).
Can someone tell me why this happen? How can i prevent it?
import java.util.*;
import java.io.*;
import javax.swing.*;
import java.awt.*;
class Example extends JFrame
{
private MyPanel gg=new MyPanel();
Example(){
add(new JScrollPane(gg));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setExtendedState(MAXIMIZED_BOTH);
}
public static void main(String argv[]){
EventQueue.invokeLater(new Runnable() {
public void run() {
Example test=new Example();
test.setVisible(true);
}
});
return;
}
}
class MyPanel extends JPanel
{
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2d=(Graphics2D)g;
g2d.drawString("HI I LOVE ELON MUSK", 90, 300035);
return;
}
public Dimension getPreferredSize() {
return new Dimension(500, 300060);
}
}
Your code ran fine on my Windows 10 system. I have a Java 13 JDK that I compile at Java 8.
I made a few changes to your main class. Maybe these changes stabilized the display. Run my code on your system and see.
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class LongJPanelExample {
public LongJPanelExample() {
JFrame frame = new JFrame("Long JPanel Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MyPanel gg = new MyPanel();
frame.add(new JScrollPane(gg));
frame.pack();
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setVisible(true);
}
public static void main(String argv[]) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new LongJPanelExample();
}
});
}
}
class MyPanel extends JPanel {
private static final long serialVersionUID = 1L;
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.drawString("HI I LOVE ELON MUSK", 90, 300035);
return;
}
public Dimension getPreferredSize() {
return new Dimension(500, 300060);
}
}
I have just started with Graphics in java, and I'm already stuck. I have tried to set the color of the JPanel to red but nothing seems to work! Any help is highly appreciated.
JFrame class:
import javax.swing.JPanel;
import javax.swing.JFrame;
import java.awt.Color;
public class redBoxFrame{
public static void main(String[]args){
JFrame f = new JFrame();
f.setSize(400, 200);
f.setTitle("A red box");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel p = new redBoxPanel();
p.setBackground(Color.RED);
f.add(p);
f.setVisible(true);
}
}
JPanel class:
import java.awt.Graphics;
import javax.swing.JPanel;
import java.awt.Color;
public class redBoxPanel extends JPanel {
public void paintComponent(Graphics g){
g.fillRect(0, 0, 100, 100);
g.setColor(Color.RED);
}
}
As you can see I have both tried to declare the color in the JFrame class and in the JPanel class but none of them seem to work.
Thank you!
Everyone here seems to miss the fact that the colour should be set before drawing.
I'll set the main background to BLUE for demo purposes.
public static void main(String[] args) {
//...
JPanel p = new redBoxPanel();
// BLUE bg. This covers the whole panel.
p.setBackground(Color.BLUE);
//...
}
And now for the red box!
public static class redBoxPanel extends JPanel {
#Override public void paintComponent(Graphics g) {
// You need to call the superclass' paintComponent() so that the
// setBackground() you called in main() is painted.
super.paintComponent(g);
// You need to set the colour BEFORE drawing your rect
g.setColor(Color.RED);
// Now that we have a colour, perform the drawing
g.fillRect(0, 0, 100, 100);
// More, for fun
g.setColor(Color.GREEN);
g.drawLine(0, 0, 100, 100);
}
}
I think you you are missing super.paintComponent(g); in your painComponent method.
I Believe that the solution is working however you are, like you said in your question, setting the background in the JFrame class and the JPanel class.
if you remove the setBackground from the JFrame class you should see only the rectangle that you are drawing. Please try the below solution and let us know if it works.
JFrame class:
import javax.swing.JPanel;
import javax.swing.JFrame;
import java.awt.Color;
public class redBoxFrame{
public static void main(String[]args){
JFrame f = new JFrame();
f.setSize(400, 200);
f.setTitle("A red box");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel p = new redBoxPanel();
f.add(p);
f.setVisible(true);
}
}
JPanel class:
import java.awt.Graphics;
import javax.swing.JPanel;
import java.awt.Color;
public class redBoxPanel extends JPanel {
public void paintComponent(Graphics g){
super.paintComponent(g);
g.fillRect(0, 0, 100, 100);
g.setColor(Color.RED);
}
}
Hi I'm new to java GUI Programming. I created Jframe(MainFrame) and add JPanel(OutPanel) Which has another Jpanel(InnerPanel). I try to achieve drawing Image in InnerPanel, not drawing OutPanel. I want OutPanel used to be just Container. So as you see TestA. I get Graphics from InnerPanel in OutPanel's paintComponent() which is overided method.
So finally I can draw using InnerPanel's Graphics in OutPanel's paintComponent() method. but It couldn't work well. It couldn't draw Image one time when program starts. when I hided window and shown again, the program shows image. Even though that is part of Image, not all Image.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TestA{
private static Image image = GUI.loadImage("PlayerBoard.jpg");
public static void main(String[] args) {
TestA testA = new TestA();
}
public TestA() {
JFrame mainFrame = new JFrame("Main Frame");
mainFrame.setLayout(null);
mainFrame.setSize(500, 500);
mainFrame.setVisible(true);
mainFrame.setBackground(Color.black);
mainFrame.setLocation(800, 400);
OutPanel outPanel = new OutPanel();
mainFrame.getContentPane().add(outPanel);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
outPanel.repaint();
}
private class OutPanel extends JPanel {
JPanel innerPanel;
public OutPanel() {
this.setLayout(null);
this.setLocation(0, 0);
this.setSize(500, 50);
this.setBackground(Color.red);
innerPanel = new JPanel();
this.innerPanel.setSize(400, 50);
this.innerPanel.setVisible(true);
this.add(innerPanel);
}
#Override
protected void paintComponent(Graphics g) {
// TODO Auto-generated method stub
super.paintComponent(g);
int width = 500;
int height = 50;
BufferedImage resized = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB_PRE);
Graphics gBuffer = resized.createGraphics();
gBuffer.drawImage(TestA.image, 0, 0, width, height, this);
Graphics gPanel = innerPanel.getGraphics();
gPanel.drawImage(resized, 0, 0, width, height, this);
}
}
}
So I try diffrerent way(TestB). Only different thing is I just moved drawImage() method and getGraphics() thing to InnerPanel's paintComponent() from OutPanel's paintComponent(). Here's another Code TestB. and It works well.
Why this happens. Is it relates to context?. What is Context. and could I draw InnerPanel's Image in OutPanel?
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TestB {
private static Image image = GUI.loadImage("PlayerBoard.jpg");
public static void main(String[] args) {
TestB testB = new TestB();
}
public TestB() {
JFrame mainFrame = new JFrame("Main Frame");
mainFrame.setLayout(null);
mainFrame.setSize(500, 500);
mainFrame.setVisible(true);
mainFrame.setBackground(Color.black);
mainFrame.setLocation(800, 400);
OutPanel outPanel = new OutPanel();
mainFrame.add(outPanel);
outPanel.repaint();
}
private class OutPanel extends JPanel {
JPanel innerPanel;
public OutPanel() {
this.setLayout(null);
this.setLocation(0, 0);
this.setSize(500, 50);
this.setBackground(Color.red);
innerPanel = new InnerPanel(this);
this.innerPanel.setSize(500, 50);
this.innerPanel.setVisible(true);
this.add(innerPanel);
this.repaint();
}
}
private class InnerPanel extends JPanel {
OutPanel outPanel;
public InnerPanel(OutPanel outPanel) {
this.outPanel = outPanel;
}
#Override
protected void paintComponent(Graphics g) {
// TODO Auto-generated method stub
super.paintComponent(g);
int width = 500;
int height = 50;
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.drawImage(TestB.image, 0, 0, width, height, this);
}
}
}
The paintComponent() method of a component is responsible for painting itself only. It should never know or care about any other component.
I want OutPanel used to be just Container.
Then do just that. Create the panel and set the layout manager for the outer panel and then add the outer panel to the JFrame.
Then create your inner panel and add it to the outer panel. Make sure you override the getPreferredSize() method of the inner panel so the layout manager of the outer panel can do its job.
Read the section from the Swing tutorial on Custom Painting for more information and working examples to start with.
I just started learning Java and am now recently learning new things outside of the console. I copied a code from The Professor's board but i can't seem to get it to work. It is suppose to draw circles and rectangles for now but i just get a blank window when i try to paint. I think i may have missed a line of code or something. I am using Eclipse on Mac.
I understand there may be many ways to do this but i want to kind of keep the code exactly how he has it for now in addition with whatever fixes you think will make it work. Thanks alot.
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
public class Bunny {
public static void main(String [] args)
{
MyFrame f = new MyFrame();
f.setSize(500,400);
f.setVisible(true);
f.setLocation(50,100);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
public class MyFrame extends JFrame
{
public MyFrame()
{
}
}
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
public class MyPanel extends JPanel
{
public void paintComponent(Graphics g)
{Graphics2D g2 = (Graphics2D) g;
Ellipse2D.Double Circle = new Ellipse2D.Double(100,50,75,75);
g2.setColor(Color.RED);
g2.fill(Circle);
Rectangle box = new Rectangle(200,100,150,150);
g2.setColor(Color.RED);
g2.fill(box);
Color myColor = new Color(255,0,0);
}
}
I'd like to, very much, tell your professor that they need to go back to school and learn how to use Swing properly
You should start by taking a look at Painting in AWT and Swing and Performing Custom Painting for more details about how painting works in Swing
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.geom.Ellipse2D;
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 {
public TestPane() {
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g.create();
Ellipse2D.Double Circle = new Ellipse2D.Double(100, 50, 75, 75);
g2.setColor(Color.RED);
g2.fill(Circle);
Rectangle box = new Rectangle(200, 100, 150, 150);
g2.setColor(Color.RED);
g2.fill(box);
g2.dispose();
}
}
}
Code Review...
public class Bunny {
public static void main(String[] args) {
MyFrame f = new MyFrame();
f.setSize(500, 400);
f.setVisible(true);
f.setLocation(50, 100);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Bad: Interacting with UI from outside the context of the Event Dispatching Thread. See Initial Threads for details
public class MyFrame extends JFrame {
public MyFrame() {
}
}
Bad: Extending from a top level container is (like JFrame) is generally discourage, you're not adding any new features to the class and this is one of the areas where most problems occur. You might like to do some research into "composition over inheritance".
You also not actually adding anything to the frame, so it will appear blank.
public class MyPanel extends JPanel {
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
Ellipse2D.Double Circle = new Ellipse2D.Double(100, 50, 75, 75);
g2.setColor(Color.RED);
g2.fill(Circle);
Rectangle box = new Rectangle(200, 100, 150, 150);
g2.setColor(Color.RED);
g2.fill(box);
Color myColor = new Color(255, 0, 0);
}
}
Bad: paintComponent should never be public, there is no reason ever that any other class should be calling this method. Not calling super.paintComponent will cause no end of graphic glitches and issues, you should always call super.paintComponent first. The only times you wouldn't is when you know what you're doing and you have an extremely good reason not to...which is like <1% of the time.
I'm new to Java and I'm trying to display an image on JFrame.
I have the main class:
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class PingPong extends JPanel{
Ball ball = new Ball(this);
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
}
public static void main(String[] args){
/* Creating the frame */
JFrame frame = new JFrame();
frame.setTitle("Ping Pong!");
frame.setSize(600, 600);
frame.setBounds(0, 0, 600, 600);
frame.getContentPane().setBackground(Color.darkGray);
frame.add(new JLabel(new ImageIcon("images/Table.png")));
frame.setVisible(true);
}
}
and Ball class:
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
public class Ball {
int x,y;
ImageIcon ball = new ImageIcon("images/Ball.png");
Image ballImage = ball.getImage();
public Ball(JPanel panel){
this.x = panel.getWidth()/2;
this.y = panel.getHeight()/2;
}
public void repaint(Graphics g){
g.drawImage(ballImage, x, y, null);
}
}
I want to display the Ball image in the main.
How can I do it?
I saw something with repaint() and paintComponent.
I just want to draw the ball image on the frame.
Thanks in advance!
Fist you need to add your custom component PingPong to frame. Then custom paintComponent(Graphics g) will be called.
Secondly add drawing code to paintComponent(Graphics g).
public class PingPong extends JPanel {
private static final long serialVersionUID = 7048642004725023153L;
Ball ball = new Ball();
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
ball.paint(g);
}
public static void main(String[] args) {
/* Creating the frame */
JFrame frame = new JFrame();
frame.setTitle("Ping Pong!");
frame.setSize(600, 600);
frame.setBounds(0, 0, 600, 600);
frame.getContentPane().setBackground(Color.darkGray);
frame.add(new PingPong());
frame.setVisible(true);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
You have to use the ball class in your main method. There isn't an instantiated ball object inside any method, only an instance of the Ball class inside the Pong class.
You also never paint the method in the frame created in the main method.