Graphics application just shows blank screen - java

I try to write a code to draw a Oval run from the top left down to the bottom right. But when I run to program, it show the blank screen on app.
Why is this happening?
Here is my code:
import javax.swing.*;
import java.awt.*;
public class SimpleAnimation {
int x = 70;
int y = 70;
public static void main(String[] arg){
SimpleAnimation gui = new SimpleAnimation();
gui.go();
}
public void go(){
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MyDrawPanel drawPanel = new MyDrawPanel();
frame.getContentPane().add(drawPanel);
frame.setSize(300, 300);
frame.setVisible(true);
for (int i = 0; i < 130; i++){
x++;
y++;
drawPanel.repaint();
try{
Thread.sleep(50);
} catch(Exception ex){}
}
} // close go() method
class MyDrawPanel extends JPanel{
#Override
public void paintComponents(Graphics g) {
g.setColor(Color.green);
g.fillOval(x, y, 40, 40);
}
} // close inner class
} // close outer class

You should Override paintComponent() instead of paintComponents().
So change the public void paintComponents() {...} to public void paintComponent() {...}
But just for the hint:
Try to use Timers instead of Threads. Always try not to mess with the swing thread. In your case you can use javax.swing.Timer to call the repaint in 50 ms intervals:
counter = 0;
t = new Timer(50, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(counter>=130)
t.stop();
counter++;
x++;
y++;
drawPanel.repaint();
}
});
t.start();
javax.swing.Timer t and int counter are member variables for your class.
Good Luck.

You are not calling super.paintComponent(g); and also you need to call paintComponents rather than repaint method. Please try it with below code. I hope it helps :)
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class SimpleAnimation {
int x = 70;
int y = 70;
public static void main(String[] arg) {
SimpleAnimation gui = new SimpleAnimation();
gui.go();
}
public void go() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MyDrawPanel drawPanel = new MyDrawPanel();
frame.getContentPane().add(drawPanel);
frame.setSize(300, 300);
frame.setVisible(true);
for (int i = 0; i < 130; i++) {
x++;
y++;
drawPanel.paintComponents(drawPanel.getGraphics());
try {
Thread.sleep(50);
} catch (Exception ex) {
}
}
} // close go() method
class MyDrawPanel extends JPanel {
#Override
public void paintComponents(Graphics g) {
// TODO Auto-generated method stub
super.paintComponent(g);
g.drawOval(50, 50, 50, 50);
g.setColor(Color.green);
g.fillOval(x, y, 40, 40);
}
} // close inner class
} // close outer class

Related

java Graphics window only updates when resized

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.*;
//import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
class Rectangle extends JPanel {
private static int rect_x = 40;
private static int rect_y = 40;
private static final int rect_width = 100;
private static final int rect_height = rect_width;
KeyListener listener;
public Rectangle() {
this.listener = new KeyListener() {
#Override
public void keyTyped(KeyEvent e)
{
}
#Override
public void keyPressed(KeyEvent e)
{
//System.out.println(e.getKeyCode());
// w
if(e.getKeyCode() == 87)
{
rect_y -= 10;
//revalidate();
repaint();
}
// s
else if (e.getKeyCode() == 83)
{
rect_y += 10;
repaint();
}
// a
else if (e.getKeyCode() == 65)
{
rect_x -= 10;
repaint();
}
// d
else if (e.getKeyCode() == 68)
{
rect_x += 10;
repaint();
}
}
#Override
public void keyReleased(KeyEvent e)
{
}
}; }
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawRect(rect_x, rect_y, rect_width, rect_height);
g.fillRect(rect_x, rect_y, rect_width, rect_height);
g.setColor(Color.BLACK);
}
#Override
public Dimension getPreferredSize() {
// so that our GUI is big enough
return new Dimension(rect_width + 2 * rect_x, rect_height + 2 * rect_y);
}
// create the GUI explicitly on the Swing event thread
private void createAndShowGui() {
Rectangle mainPanel = new Rectangle();
JFrame frame = new JFrame("DrawRect");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
frame.addKeyListener(listener);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
Rectangle Rct = new Rectangle();
Rct.createAndShowGui();
}
});
}
}
this code is meant to move a rectangle across the screen.
For some reason it does not update unless the window is minimised or resized.
I realise this has been asked many times before, but the answers I have found were very case specific or above my understanding.
I am new to java so sorry if I seem like a blockhead.
You're creating an Extra Rectangle object, and calling repaint() on it, and this is not the displayed object, and so your listener does not repaint the displayed JPanel. Don't do this. Only create one Rectangle object, so your repaints go to the correct reference.
e.g., change this:
Rectangle mainPanel = new Rectangle(); // ***** no!!! ****
JFrame frame = new JFrame("DrawRect");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel); // **** no ****
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
frame.addKeyListener(listener);
to this:
// Rectangle mainPanel = new Rectangle();
JFrame frame = new JFrame("DrawRect");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(this); // ****** note change
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
frame.addKeyListener(listener);
Other side issues:
Prefer Key Bindings to a KeyListener
Avoid magic numbers such as your key code numbers, which make debugging difficult. Instead use the KeyEvent.VK_? constants.
Follow Java naming conventions: constants should be all upper-case.
Your rect_x and y fields should not be static.

java simple bouncing ball flickers

This is just a simple red ball going up and down and i see it flickering. I already saw few subjects about that but did not find any answer that helped me.
Thank you :)
The Window class with the go method that makes the ball goes up and down.
The panel that also contains the ball positions and that just repaints.
Window.java
import java.awt.Dimension;
import javax.swing.JFrame;
public class Window extends JFrame
{
public static void main(String[] args)
{
new Window();
}
public Panel pan = new Panel();
public Window()
{
this.setSize(600, 600);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.setContentPane(pan);
this.setVisible(true);
go();
}
private void go()
{
int vecY = 1;
while (true)
{
if (pan.y <= 100)
{
vecY = 1;
}
else if (pan.y >= 400)
{
vecY = -1;
}
pan.y += vecY;
pan.repaint();
try
{
Thread.sleep(10);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
Panel.java
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
public class Panel extends JPanel
{
public int x = 300;
public int y = 300;
public void paintComponent(Graphics g)
{
g.setColor(Color.white);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
g.setColor(Color.red);
g.fillOval(x, y, 50, 50);
}
}
There are a number of possible issues. The primary issue is likely to be a thread race condition between your while-loop and the paintComponent method.
Your while-loop is capable of change the state of the y position before the paintComponent has a chance to paint it's state. Painting is done at the leisure of the paint sub system, so calling repaint simply makes a request to the RepaintManager which decides what and when an actual paint cycle might take place, this means that you could be dropping frames.
For most animations in Swing, a Swing Timer is more the capable. It's safe to update the UI from within, as the ActionListener is called within the context of the EDT but won't block the EDT
For example:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class Window extends JFrame {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Window();
}
});
}
public Panel pan = new Panel();
public Window() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setContentPane(pan);
pack();
this.setLocationRelativeTo(null);
this.setVisible(true);
go();
}
private void go() {
Timer timer = new Timer(10, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
pan.updateAnmationState();
}
});
timer.start();
}
public class Panel extends JPanel {
private int x = 300;
private int y = 300;
private int vecY = 1;
public void updateAnmationState() {
if (y <= 100) {
vecY = 1;
} else if (y >= 400) {
vecY = -1;
}
y += vecY;
repaint();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.white);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
g.setColor(Color.red);
g.fillOval(x, y, 50, 50);
}
}
}
This example worked fine for me on MiniMac

i can't see circle moving

While using Swing in java, I am trying to move a circle slowly from a starting position to an end position when clicking a button. However, I can't see the circle moving. It just moves from start to end in an instant.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MyApp {
private int x = 10;
private int y = 10;
private JFrame f;
private MyDraw m;
private JButton b;
public void go() {
f = new JFrame("Moving circle");
b = new JButton("click me to move circle");
m = new MyDraw();
f.add(BorderLayout.SOUTH, b);
f.add(BorderLayout.CENTER, m);
f.setSize(500, 500);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
b.addActionListener(new Bute());
}
public static void main(String[] args) {
MyApp m = new MyApp();
m.go();
}
private class Bute implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < 150; i++) {
++x;
++y;
m.repaint();
Thread.sleep(50);
}
}
}
private class MyDraw extends JPanel {
#Override
public void paintComponent(Graphics g) {
g.setColor(Color.white);
g.fillRect(0, 0, 500, 500);
g.setColor(Color.red);
g.fillOval(x, y, 40, 40);
}
}
}
I think the problem is with the action listener because when I'm doing it without using button it is working. Any suggestions?
As Andrew Thompson said, calling Thread.sleep() without defining a second thread freezes everything, so the solution is to define and run another thread like so:
class Bute implements ActionListener, Runnable {
//let class implement Runnable interface
Thread t; // define 2nd thread
public void actionPerformed(ActionEvent e) {
t = new Thread(this); //start a new thread
t.start();
}
#Override //override our thread's run() method to do what we want
public void run() { //this is after some java-internal init stuff called by start()
//b.setEnabled(false);
for (int i = 0; i < 150; i++) {
x++;
y++;
m.repaint();
try {
Thread.sleep(50); //let the 2nd thread sleep
} catch (InterruptedException iEx) {
iEx.printStackTrace();
}
}
//b.setEnabled(true);
}
}
The only problem with this solution is that pressing the button multiple times will speed up the circle, but this can be fixed by making the button unclickable during the animation via b.setEnabled(true/false). Not the best solution but it works.
As said in the comments and another answer, don't block the EDT. Thead.sleep(...) will block it, so you have two options:
Create and manage your own (new) thread.
Use a Swing Timer
In this answer I'll be using a Swing Timer, since it's easier to use. I also changed the paintComponent method to use the Shape API and change the button text to start and stop accordingly as well as reusing the same ActionListener for the button and the timer:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class MovingCircle {
private JFrame frame;
private CustomCircle circle;
private Timer timer;
private JButton button;
public static void main(String[] args) {
SwingUtilities.invokeLater(new MovingCircle()::createAndShowGui);
}
private void createAndShowGui() {
frame = new JFrame(this.getClass().getSimpleName());
circle = new CustomCircle(Color.RED);
timer = new Timer(100, listener);
button = new JButton("Start");
button.addActionListener(listener);
circle.setBackground(Color.WHITE);
frame.add(circle);
frame.add(button, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private ActionListener listener = (e -> {
if (!timer.isRunning()) {
timer.start();
button.setText("Stop");
} else {
if (e.getSource().equals(button)) {
timer.stop();
button.setText("Start");
}
}
circle.move(1, 1);
});
#SuppressWarnings("serial")
class CustomCircle extends JPanel {
private Color color;
private int circleX;
private int circleY;
public CustomCircle(Color color) {
this.color = color;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(color);
g2d.fill(new Ellipse2D.Double(circleX, circleY, 50, 50));
}
#Override
public Dimension preferredSize() {
return new Dimension(100, 100);
}
public void move(int xGap, int yGap) {
circleX += xGap;
circleY += yGap;
revalidate();
repaint();
}
public int getCircleX() {
return circleX;
}
public void setCircleX(int circleX) {
this.circleX = circleX;
}
public int getCircleY() {
return circleY;
}
public void setCircleY(int circleY) {
this.circleY = circleY;
}
}
}
I'm sorry, I can't post a GIF as I wanted but this example runs as expected.

Why the repaint() method not working here?

public class Ova extends JPanel implements ActionListener{
int x=0;
Timer timer=new Timer(100,this);
int y=0,x1=5,y1=5;
public static void main(String[] ds)
{
Ova ss=new Ova();
ss.nn();
}
private void nn() {
JFrame frame=new JFrame("fram");
frame.setSize(1000,600);
JPanel as=new JPanel();
frame.add(as);
frame.add(new Ova());
frame.setVisible(true);
timer.start();
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawOval(x, y, 50, 50);
}
public void actionPerformed(ActionEvent e) {
if (x<0 || x>950){
x1=-x1;
}
if (y<0 || y>530)
{
y1=-y1;
}
x=x+x1;
y=y+y1;
repaint();
}
}
Whenever I put timer.start() inside paintComponent() the repaint() method works but if I start the timer outside the paint component method the repaint method does not work.Please explain the reasons. Thank you.
Problem
You have mis-matched reference issue
Start with this snippet...
public class Ova extends JPanel implements ActionListener {
int x = 0;
Timer timer = new Timer(100, this);
int y = 0, x1 = 5, y1 = 5;
public static void main(String[] ds) {
Ova ss = new Ova();
ss.nn();
}
private void nn() {
JFrame frame = new JFrame("fram");
frame.setSize(1000, 600);
JPanel as = new JPanel();
frame.add(as);
frame.add(new Ova());
frame.setVisible(true);
timer.start();
}
First, main creates an instance of Ova, then the method nn creates a new instance of Ova and then you start the timer...
Now the question you need to ask is, which Ovas timer did you start...the one on the screen or the one main created...
I can tell, it was the one that main created, which is not visible on the screen
(A possible) Solution
Start by never creating a JFrame inside a JPanel (or other component). The only time I would do something like that is via a static support method...
Remove the nn method and replace it with a begin (or something like that) method that starts the timer.
In the main method, create an instance of Ova, add it to an instance of JFrame and call Ova's begin method...
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Ova extends JPanel implements ActionListener {
int x = 0;
Timer timer = new Timer(100, this);
int y = 0, x1 = 5, y1 = 5;
public static void main(String[] ds) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
Ova ova = new Ova();
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(ova);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
ova.begin();
}
});
}
#Override
public Dimension getPreferredSize() {
return new Dimension(600, 600);
}
private void begin() {
timer.start();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawOval(x, y, 50, 50);
}
#Override
public void actionPerformed(ActionEvent e) {
if (x < 0 || x > 950) {
x1 = -x1;
}
if (y < 0 || y > 530) {
y1 = -y1;
}
x = x + x1;
y = y + y1;
repaint();
}
}
Avoid calling setSize on anything, instead, override the getPreferredSize method of the component and return a preferred size and then use pack on the JFrame to wrap the frame around this. You will get far better and reliable results.

I need a little help implementing player movement on java grid

I need a little help with java, I am new to the language hence I have no idea on how to implement such.
I have already made a basic 15;40 grid JLabel Image, thanks to this site as well, what I need help with is about how to make a player(Supposed to be an Image, also shown on the grid) move around using either WASD(I don't know if Ascii-approach works on java) or Arrow Keys.
Here's my code for the Grid
public class GUI {
static Scanner cns = new Scanner(System.in);
JFrame frame = new JFrame();
ImageIcon ImageIcon = new ImageIcon("Grass.png");
JLabel[][] grid;
public GUI(int width, int length) {
Container pane = frame.getContentPane();
frame.setLayout(new GridLayout(width,length));
grid = new JLabel[width][length];
for(int y = 0; y < length; y++) {
for(int x = 0; x < width; x++) {
grid[x][y] = new JLabel();
grid[x][y].setBorder(BorderFactory.createLineBorder(Color.black));
grid[x][y].setBorder(BorderFactory.createEmptyBorder());
}
}
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
for(int y = 0; y < length; y++) {
for(int x = 0; x < width; x++) {
pane.add(grid[x][y]= new JLabel(new ImageIcon("Grass.png")));
grid[x][y].setBorder(BorderFactory.createLineBorder(Color.black));
grid[x][y].setBorder(BorderFactory.createEmptyBorder());
frame.add(grid[x][y]);
}
}
}
public static void main(String[] args) {
new GUI(15, 40);
}
}
Couple of suggestions here:
1 - Make GUI extend JFrame and implement KeyListener.
You have to override KeyListener methods (keyPressed, keyReleased, and keyTyped) and you should override repaint() from JFrame.
The repaint method should call super.repaint() at the end to update frames.
2 - Have the fields of GUI store data about the things that need to be drawn.
You probably should store the grid, or what's in the grid as fields.
3 - The constructor should initialize, not render.
Rendering should be done in repaint(). The constructor should do something like this:
super();
JPanel frame = new JPanel();
add(frame);
pack();
addKeyListener(this);
repaint();
This answer is kinda unfinished but I'll look more into it and update this. Particularly, the JPanel is an element in the JFrame.
UPDATE: Here is a small working example. Use WASD to move the rectangle around the screen.
This is the JFrame.
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
public class MyJFrame extends JFrame implements KeyListener {
private MyJPanel frame;
public MyJFrame() {
super();
frame = new MyJPanel();
add(frame);
pack();
addKeyListener(this);
repaint();
}
public static void main(String[] args) {
MyJFrame window = new MyJFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
window.setTitle("Test");
}
#Override
public void repaint() {
super.repaint();
}
#Override
public void keyPressed(KeyEvent e) {
frame.keyPressed(e);
repaint();
}
#Override
public void keyTyped(KeyEvent e) { }
#Override
public void keyReleased(KeyEvent e) { }
}
This is the JPanel.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import javax.swing.JPanel;
public class MyJPanel extends JPanel {
private int x = 0;
private int y = 0;
public MyJPanel() {
setPreferredSize(new Dimension(200,200));
}
#Override
public void update(Graphics g) {
paint(g);
}
#Override
public void paint(Graphics g) {
g.setColor(Color.red);
g.drawRect(x,y,20,20);
}
public void keyPressed(KeyEvent e) {
int k = e.getKeyCode();
switch (k) {
case KeyEvent.VK_D:
x++;
break;
case KeyEvent.VK_A:
x--;
break;
case KeyEvent.VK_W:
y--;
break;
case KeyEvent.VK_S:
y++;
break;
}
}
}
Good luck!

Categories