Display Image JFrame - java

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.

Related

Java swing: i called once drawString and it printed my string multiple times

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

Superclass not using subclass method

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

Can't set color to JPanel in Java

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

Can't load Image one time using getGraphics() method

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.

Attempting to paint window black using JFrame and JPanel

I've made a JFrame, and added a JPanel to it. I am trying to paint the window completely black, and it isn't working! Thank you in advance.
This is my Main class!
package com.lootdatdungeon.net;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
public class Main {
public static void main(String[] args){
initWindow();
}
public static void initWindow(){
Window window = new Window();
Thread windowThread = new Thread(window);
windowThread.start();
}
}
Okay, and here is my Window class!
package com.lootdatdungeon.net;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Window extends JFrame implements Runnable{
private static final long serialVersionUID = 1L;
private static final int HEIGHT = 240;
private static final int WIDTH = 320;
private static final int SCALE = 2;
private BufferedImage image;
private Graphics2D g;
private boolean running = true;
public Window(){
System.out.println("Window object made");
JFrame frame = new JFrame("Loot dat dungeon");
JPanel panel = new JPanel();
frame.setSize(WIDTH*SCALE,HEIGHT*SCALE);
frame.setVisible(true);
frame.setResizable(false);
frame.add(panel);
image = new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB);
g = (Graphics2D) image.getGraphics();
}
public void Draw(Graphics g){
System.out.println("Draw method ran");
g.setColor(Color.BLACK);
g.drawRect(0, 0, WIDTH, HEIGHT);
}
#Override
public void run() {
while(running){
Draw(g);
}
}
}
Simply do in this way using overriiden paintComponent() method of JPanel
JPanel panel = new JPanel() {
#Override
public void paintComponent(Graphics g) {
// don't forget to call it
super.paintComponent(g);
// set color
g.setColor(Color.BLACK);
// fill a rect that cover whole panel with specified color
g.fillRect(0, 0, getWidth(), getHeight());
}
};
Note: There is no need of Thread and BufferedImage in this case.
You should give this a read http://www.gametutorial.net/article/Java-game-framework
That site has a lot of good info if you want to create games. That's there I started.

Categories

Resources