I would like to repaint my jPanel
I've a App class who handle the screen displaying in this JFrame I add a Board JPanel object who handle all the JPanel.
In the Board class I had
ex = new Explosion(10, 10);
new Thread(ex).start();
And in my Explosion class I have a constructor who crop my sprite file, an overwriting of paint() and :
public void run()
{
while(cursor < (rows*cols))
{
repaint();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(cursor);
cursor++;
}
}
The loop is working fine but I have no repaint in my screen , only the first image is display.
What can I do to refresh ?
Thanks
Edit :
Here is my code :
public class Explosion extends JPanel implements Runnable{
private BufferedImage img;
final int width = 320;
final int height = 320;
final int rows = 5;
final int cols = 5;
private int x,y;
private int cursor;
BufferedImage[] sprites = new BufferedImage[rows * cols];
public Explosion(int x, int y)
{
this.x = x;
this.y = y;
try {
try {
this.img = ImageIO.read(new File((this.getClass().getResource("files/explosion2.png")).toURI()));
} catch (URISyntaxException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
cursor = 0;
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
sprites[(i * cols) + j] = img.getSubimage(
i * (width/rows),
j * (height/cols),
width/rows,
height/cols
);
}
}
}
public void run()
{
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
cursor++;
repaint();
}
};
while(cursor < (rows*cols))
{
new Timer(50, taskPerformer).start();
if (cursor==(rows*cols)-1)
cursor=0;
}
}
public void paintComponent(Graphics g){
System.out.println("paintComponent");
Graphics2D g2d = (Graphics2D)g;
g2d.drawImage(sprites[cursor], x, y, this);
g.dispose();
}
/*public void paint(Graphics g) {
super.paint(g);
System.out.println("paint");
Graphics2D g2d = (Graphics2D)g;
g2d.drawImage(sprites[cursor], x, y, this);
Toolkit.getDefaultToolkit().sync();
g.dispose();
}*/
}
public class Main extends JFrame{
public Main()
{
Board board = new Board();
add(board);
setTitle("Explosion");
setSize(500, 500);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
new Main();
}
}
public class Board extends JPanel{
Explosion ex;
public Board()
{
setDoubleBuffered(true);
ex = new Explosion(10,10);
new Thread(ex).start();
}
public void paint(Graphics g) {
ex.paintComponent(g);
super.paint(g);
Graphics2D g2d = (Graphics2D)g;
Toolkit.getDefaultToolkit().sync();
g.dispose();
}
}
#StanislavL (I can't comment yet): No, you don't have to call repaint() in the EDT:
The following JComponent methods are safe to call from any thread: repaint(), revalidate(), and invalidate(). The repaint() and revalidate() methods queue requests for the event-dispatching thread to call paint() and validate(), respectively. The invalidate() method just marks a component and all of its direct ancestors as requiring validation.
Source: http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html#exceptions
Is cursor declared as volatile? If not, the EDT may not see the changes the thread made to cursor. Therefore, always the first image is painted.
Do not override paint, instead override paintComponent
Do not use Thread.sleep, instead use a utility class, such as javax.swing.Timer to execute a particular action at a specified interval. This will ensure that all changes are done on the EDT and that the waiting occurs in a background thread.
Note that without compilable code, it's hard to tell what the real problem is; this is all guesswork.
Repaint must be called in EDT.
Use SwingUtilities.invokeAndWait() or invokeLater() to call repaint.
Related
My paint method doesnt seem to paint my 20x20 cells. I have a boolean array for the cells to control their state and that if true, call the cells paint method, a cell is painted however I have two problems;
Only one is painted at a time which is odd because i should have a 40x40 array of booleans meaning i have 40x40 cells
They dont actually paint exactly where I click. I do not know how this is the case as when I get the co-ordinates of my click I immediately place those co-ordinates as my x, and y values in my paint method.
Main
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferStrategy;
public class mainApplication extends JFrame implements Runnable, MouseListener {
private static final Dimension windowsize = new Dimension(80, 600);
private BufferStrategy strategy;
private Graphics offscreenGraphics;
private static boolean isGraphicsInitialised = false;
private static int rows = 40;
private static int columns = 40;
private static int height = windowsize.height;
private static int width = windowsize.width;
private static Cells cells = new Cells();
private int xArrayElement,yArrayElement, xPosition, yPosition;
private static boolean gameState[][] = new boolean[rows][columns];
public mainApplication() {
System.out.println(System.getProperty("user.dir"));
setDefaultCloseOperation(EXIT_ON_CLOSE);
Dimension screensize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
int x = screensize.width / 2 - windowsize.width / 2;
int y = screensize.height / 2 - windowsize.height / 2;
setBounds(x, y, screensize.width, screensize.height);
setVisible(true);
createBufferStrategy(2);
strategy = getBufferStrategy();
offscreenGraphics = strategy.getDrawGraphics();
isGraphicsInitialised = true;
// MouseEvent mouseEvent = new MouseEvent();
addMouseListener(this);
// addMouseMotionListener(MouseEvent);
Thread t = new Thread(this);
t.start();
}
public void mousePressed(MouseEvent e) { }
public void mouseReleased(MouseEvent e) { }
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) { }
public void mouseClicked(MouseEvent e) {
if(e.getClickCount() == 1){
xPosition = e.getX();
yPosition = e.getY();
cells.setPosition(xPosition,yPosition);
xArrayElement = (xPosition/20);
yArrayElement = (yPosition/20);
if(gameState[xArrayElement][yArrayElement]){
gameState[xArrayElement][yArrayElement] = false;
}
else if (!gameState[xArrayElement][yArrayElement]) {
gameState[xArrayElement][yArrayElement] = true;
}
else(gameState[xArrayElement][yArrayElement]) = true;
}
}
#Override
public void run() {
while (true) {
try { //threads entry point
Thread.sleep(20); //forces us to catch exception
}
catch (InterruptedException e) {
}
this.repaint();
}
}
public void paint(Graphics g) {
if (isGraphicsInitialised) {
g = strategy.getDrawGraphics();
g.setColor(Color.BLACK);
g.fillRect(0, 0, 800, 800);
if (gameState[xArrayElement][yArrayElement]) {
g.setColor(Color.WHITE);
cells.paint(g);
System.out.println(xPosition);
}
else if (!gameState[xArrayElement][yArrayElement]) {
g.setColor(Color.BLACK);
g.fillRect(xPosition, yPosition, 20, 20);
}
strategy.show();
}
}
public static void main(String[]args){
mainApplication test = new mainApplication();
}
}
Cell Class
import java.awt.*;
public class Cells {
int x;
int y;
public Cells(){
}
public void setPosition(int xi, int xj){
x = xi;
y = xi;
}
public boolean cellState(boolean visible){
return visible;
}
public void paint(Graphics g){
g.drawRect(x, y, 20,20);
}
}
You are doing a number of things wrong. My first suggestion would be to forget about offscreen graphics and ensure you are doing what you want. You can always create an image latter. Here are some basic guidelines:
Don't extend JFrame. Use an instance.
Extend JPanel or create a class that extends JPanel and add to frame instance
Then override paintComponent(g) and use that graphics context to draw.
Here is an earlier answer that may help Can't add Graphics into JPanel in Java
More information may be found in the Java Tutorials on painting.
Updated. It took me a few minutes to find this.
public void setPosition(int xi, int xj){
x = xi;
y = xi; // <--- should be xj
}
Regarding (1) above. You must repaint every cell each time you enter paintComponent. This means you will need to iterate across the list and paint them in the correct spot. Right now you are only painting one upon each entry.
A couple more suggestions. Instead of messing with the thread and calling repaint every 20ms in a loop, why not just invoke repaint in the mouseClicked() method.
If you do eventually need to paint every 20ms. I suggest using a swing Timer as follows: (check JavaDoc to ensure I got the syntax correct!!)
Timer timer = new Timer(0, (ev)-> frame.repaint());
timer.setDelay(20);
timer.start();
And you can create your own mouseListener class and extending MouseAdapter. The purpose of these adapter classes is to keep the clutter down so you don't have to have empty methods to satisfy the interface requirements. Put the class inside your main class so it has access to the appropriate data structures. Then just add an instance of it to the mouse listener of the target Component.
I'm trying to draw a shape multiple times inside a JPanel to mimic an animation (a moving shape across it). The problem is that the shape is being redrawn and thus appearing on the screen multiple times on different places, when all i pretend is that only one shape is visible at a time when it's being redrawn.
The method super.paintComponent() should be responsible for repainting JPanel's background and thus, only one shape should be visible when the redrawing is being performed.
I have the following code (it has been reduced/simplified for the sake of simplicity and better understanding):
public class Animated_Shape_Test extends JFrame
{
public static void main(String args[]) throws IOException
{
new Animated_Shape_Test();
}
public Animated_Shape_Test() throws IOException
{
this.setSize(500, 500);
this.setPreferredSize(new Dimension(500, 500));
this.setLocation(new Point(430, 150));
this.setTitle("Database Launcher v1.0");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.setVisible(true);
DBPanel panel = new DBPanel();
getContentPane().add(panel, BorderLayout.CENTER);
}
}
final class DBPanel extends JPanel implements Runnable
{
int musicShapePosX = 85;
int musicShapePosY = 100;
int SEGMENT_SHAPE_LENGTH = 50;
int SHAPE_HEIGHT = 10;
float SHAPE_SPEED = 7.5f;
CustomShapeButton musicShapeButton = new CustomShapeButton(musicShapePosX, musicShapePosY, SEGMENT_SHAPE_LENGTH, SHAPE_HEIGHT);
private ArrayList<Shape> shapes = null;
protected DBPanel() throws IOException
{
shapes = new ArrayList();
shapes.add(musicShapeButton);
this.setOpaque(true);
this.setFocusable(true);
startThread();
}
public void startThread()
{
Thread t = new Thread(this);
t.start();
}
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(getBackground().darker());
g2.fillRect(0, 0, getWidth(), getHeight());
g2.setColor(Color.BLACK);
g2.draw(musicShapeButton);
}
public void delay(int milliseconds)
{
try
{
Thread.sleep(milliseconds);
}
catch (InterruptedException e)
{
}
}
#Override
public void run()
{
while (true)
{
delay(35);
animateButtonShapeMusic();
repaint();
}
}
public void animateButtonShapeMusic()
{
if (musicShapePosY < 228)
{
musicShapePosY = (int)(musicShapePosY + SHAPE_SPEED);
musicShapeButton.drawShape(musicShapePosX, musicShapePosY, SEGMENT_SHAPE_LENGTH, SHAPE_HEIGHT);
}
}
}
I'm getting several shapes being redrawn across the screen (animation).
I expect a single shape being redrawn across the screen (animation).
Thank you in advance.
I am working on a version of the Squares game. For it I need to detect when my Ellipses are being clicked. But the problem is my method is using one Ellipse object. How can I detect which Ellipse is being clicked? Here is my code.
Main Squares class
public static boolean running = false;
public Squares() {
this.setSize(600, 600);
this.setTitle("Squares");
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setContentPane(new SquarePane());
this.setLocationRelativeTo(null);
this.setVisible(true);
}
public static void main(String[] args) {
try {
new Squares();
} catch (Exception e) {
e.printStackTrace();
System.out.println("Crashed");
System.exit(-1);
}
running = true;
}
}
SquaresPanel Class
public static int x = 100;
public static int y = 100;
public static Color randomColor;
public static float r;
public static float g;
public static float b;
public void paintComponent(Graphics gra) {
Graphics2D g2d = (Graphics2D) gra;
gra.setColor(Color.black);
gra.fillRect(0, 0, 600, 600);
Random rand = new Random();
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
Ellipse2D oval = new Ellipse2D.Double(x, y, 10, 10);
r = rand.nextFloat();
g = rand.nextFloat();
b = rand.nextFloat();
randomColor = new Color(r, g, b);
g2d.setColor(randomColor);
g2d.fill(oval);
x += 50;
}
x = 100;
y += 50;
}
}
Thanks guys!
Will
Without looking too much at your code (as I see it's lacking alot) I will just explain how your requirement can be achieve.
1st : You need a MouseListener and implement the mousePressed. From the MouseEvent object, you can obtain the point clicked. See How to Write MouseListener if you are unsure.
public void mousePressed(MouseEvent e) {
Point p = e.getPoint();
}
2nd: Keep a List of your ellipses
List<Ellipse2D> ellipses;
3rd: Keep a selectedEllipse variable to hold the select one.
Ellipse2D selectedEllipse;
4th: After clicking the point, you loop through the list, checking if each Ellipse2D.contains the point. Then do something with the selected Ellipse
public void mousePressed(MouseEvent e) {
Point p = e.getPoint();
for (Ellipse2D ellipse : ellipses) {
if (ellipse.contains(p) {
selectedEllipse = ellipse;
// do something with selectedEllipse
break;
} else {
selectedEllipse = null;
}
}
}
5th: Loop through your ellipses to paint the in the paintComponent method
protected void paintComponent(Grapchics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
for (Ellipse2D ellipse : ellipses) {
g2.fill(ellipse):
}
}
Side Notes
You must call super.paintComponent in your paintComponent method
protected void paintComponent(Graphics g) {
super.paintComponent(g);
}
UPDATE
After taking a closer look at your code, I see more of what you are trying to achieve. Looks like you want am 8 by 8 grid of your ellipses. Another option is just to create 64 panels. and paint each of them.
First have a panel class where you can set the color
public class EllipsePanel extends JPanel {
private Color color;
public EllipsePanel(Color color) {
this.color = color;
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(color);
g.fillOval(0, 0, getWidth(), getHeight());
}
}
Then you can use a panel to hold all those panel and use a GridLayout, but also keeping a JPanel[][] so you can easily refer to each panel. You can also a add a mouselistener to each panel
JPanel gridPanel = new JPanel(new GridLayout(8, 8));
EllipsePanel[][] panels = new EllipsePanel[8][8];
EllipsePanel selectedPanel = null;
int currentRow;
int currentCol;
...
for (int i = 0; i < 8; i++) {
for (int j = 0; i < 8; j++) {
final EllipPanel panel = new EllipsePanel(getRendomColor);
panel.addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e) {
selectedPanel = panel;
// do something with selected panel;
}
});
gridPanel.add(panel);
}
}
You should implement a mouse listener on your JPannel, and then use the position clicked retrieved from the listener to work out which ellipse was clicked
I'm trying to learn to program my first game and I would like to understand correctly every step I make. I'll face double buffering and other things later.
I'm just trying to load an image in the game loop.
I have two classes. The first it's just a jframe calling the start method.
I wonder if there is some ugly code, in here (I think so).
So, why are my images not showing up?
public class myPanel extends JPanel implements Runnable{
//FIELDS
public static int WIDTH = 1024;
public static int HEIGHT = WIDTH / 16 * 9;
private BufferedImage bg;
private BufferedImage charac;
private boolean running;
private Thread t1;
private int startposX = WIDTH / 2;
private int startposY = HEIGHT / 2;
private int cordX = startposX;
private int cordY = startposY;
int speed = 50;
//METHODS
public synchronized void start (){
running = true;
t1 = new Thread (this);
t1.start();
}
public synchronized void stop (){
running = false;
try {
t1.join();
System.out.println("The game stopped");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//INIT
public myPanel(){
setPreferredSize(new Dimension(WIDTH, HEIGHT));
setFocusable(true);
requestFocus();
addKeyListener(this);
}
//MAIN RUN METHOD
public void run(){
while (running){
load();
System.out.println("The game runs");
repaint();
}
}
//PAINT WITH GRAPHICS METHOD
public void paint (Graphics g){
super.paint(g);
g.drawImage(bg, 0, 0, this);
g.drawImage(charac, 110, 280, this);
}
//LOAD IMAGES IN MEMORY
public void load (){
try {
String path1 = "res/bg.png";
bg = ImageIO.read(new File (path1));
String path2 = "res/charac.png";
charac = ImageIO.read(new File (path2));
} catch (IOException e) {
e.printStackTrace();
}
}
So, I did some testing about paint vs paintcomponent and I just saw that the first draws on top of the jpanel background. Anyway, I can't still see anything changing the lines to
public void run(){
while (running){
load();
System.out.println("The game runs");
}
}
//PAINT WITH GRAPHICS METHOD
public void paintComponent (Graphics g){
super.paint(g);
g.drawImage(bg, 0, 0, null);
g.drawImage(charac, 110, 280, null);
}
//LOAD IMAGES METHOD AS ABOVE
And yes, I've added the panel to the frame, here is the other class
public class Game {
public static void main (String [] args){
JFrame frame = new JFrame();
frame.setIgnoreRepaint(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new myPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
myPanel game = new myPanel();
game.start();
}
I've been trying to get this rectangle to move that I've created using a for loop. All that's happening with this code is that there is an original rectangle and then a new one next to that rectangle. No animation happens, only those two rectangles show on the window. What are some methods to get this rectangle to animate?
import java.awt.*;
import javax.swing.*;
public class Gunman extends JComponent {
/**
*
*/
private static final long serialVersionUID = 1L;
public int x = 10;
public int y = 10;
public int width = 8;
public int height = 10;
public void paint(Graphics g) {
g.setColor(Color.red);
g.drawRect (x, y, width, height);
g.fillRect (x, y, width, height);
for(int i = 0; i<=1024; i++){
g.setColor(Color.red);
g.drawRect(x++, y, width, height);
g.fillRect(x++, y, width, height);
}
}
}
Don't have program logic in a paint or paintComponent method, and by logic, I mean the for loop with "motion" as that just won't work. You want to
Almost never draw in a JComponent's paint method but rather in its paintComponent method.
Don't forget to call the super.paintComponent(g) method too, often as the first method call in the paintComponent(g) override.
Use a Swing Timer to step wise change the x and y values
call repaint() on the JComponent after the changes are made
For example
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Gunman extends JComponent {
private static final long serialVersionUID = 1L;
private static final int PREF_W = 900;
private static final int PREF_H = 700;
private static final int TIMER_DELAY = 30;
public int rectX = 10;
public int rectY = 10;
public int width = 8;
public int height = 10;
public Gunman() {
new Timer(TIMER_DELAY, new ActionListener() {
#Override
public void actionPerformed(ActionEvent actEvt) {
if (rectX < PREF_W && rectY < PREF_H) {
rectX++;
rectY++;
repaint();
} else {
((Timer)actEvt.getSource()).stop();
}
}
}).start();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.red);
g.drawRect(rectX, rectY, width, height);
g.fillRect(rectX, rectY, width, height);
}
public int getRectX() {
return rectX;
}
public void setRectX(int rectX) {
this.rectX = rectX;
}
public int getRectY() {
return rectY;
}
public void setRectY(int rectY) {
this.rectY = rectY;
}
private static void createAndShowGui() {
Gunman mainPanel = new Gunman();
JFrame frame = new JFrame("Gunman");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
There are numerous ways to animate. Here is another example. Notice the location of repaint() inside a background thread. This paints directly on a JFrame. Use paintComponent() when painting on JPanels.
public static void main(String args[]) throws Exception {
new JFrame("Draw a red box") {
Point pointStart = new Point(50,50);
Point pointEnd = new Point(200,200);
public void paint(Graphics g) {
super.paint(g);
if (pointStart != null) {
g.setColor(Color.RED);
g.drawRect(pointStart.x, pointStart.y, pointEnd.x, pointEnd.y);
}}{
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setSize(300, 300);
setLocation(300, 300);
setVisible(true);
Thread t = new Thread(new Runnable() {
public void run() {
while (pointEnd.x > 0 && pointEnd.y > 0) {
pointEnd = new Point(--pointEnd.x, --pointEnd.y);
repaint();
try {
Thread.sleep(22);
} catch (InterruptedException e) {
e.printStackTrace();
}}
pointStart = null;
pointEnd = null;
}});
t.setDaemon(true);
t.start();
}};}
UPDATE: Ok previous answer was not so good from the old memory, here is the quickest, cheapest, most dirty way to get some animation quicksmart, you can copy and compile the code as is:
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class Test extends JFrame {
public Gunman g = new Gunman();
public static void main( String[] args ) {
Test t = new Test();
t.setSize( 800, 600 );
t.setVisible( true );
t.getContentPane().add( t.g );
while ( true ) {
t.g.x = t.g.x + 1;
t.g.y = t.g.y + 1;
t.repaint();
try {
Thread.sleep( 100 );
} catch ( InterruptedException e ) {
}
}
}
public void paintComponent( Graphics g ) {
g.clearRect( 0, 0, 800, 600 );
}
}
class Gunman extends JComponent {
private static final long serialVersionUID = 1L;
public int x = 10;
public int y = 10;
public int width = 8;
public int height = 10;
public void paintComponent( Graphics g ) {
g.setColor( Color.red );
g.fillRect( x, y, width, height );
}
}
There are ALOT of shortcuts in this, as Hovercraft of Eels has said, this is not an 'ideal' way to do it, but it has the basic structure. You have a canvas (I have used the JFrame, again not really recommended), and you add a component to it. You must override paintComponent (if you are using swing, which I do recommend you do), and this will draw your component.
You then need to alter your component's position in some way (recommend a proper method call on the object that does this), and ask the canvas to repaint itself.
I have included the wait so you can see what's happening, but if you are thinking of game programming, you should look into creating a game loop to manage this, I recommend Killer game programming in java, you can get a free ebook version with a quick google search.