Java Graphics Update/Repaint Graphic - java

I'm trying to work with the Java paint
utility and it's been a bit of a hassle.
I'm trying to do something which I assume is quite basic.
I'm drawing a square Graphic to a JPanel and then trying
to move it using repaint
import javax.swing.*;
import java.awt.*;
import java.awt.image.*;
public class testGui {
static gui gc_gui;
static int gv_x;
static int gv_y;
public static void main(String[] args) {
gc_gui = new gui();
gv_x = 50;
gv_y = 50;
gc_gui.cv_frame.setVisible(true);
}
public static class gui {
JFrame cv_frame;
content cv_content;
public gui() {
cv_frame = new JFrame();
cv_frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
cv_frame.setTitle("Test GUI");
cv_frame.setSize(600, 400);
cv_frame.setLayout(new FlowLayout());
cv_content = new content();
cv_content.setBackground(Color.Black);
cv_content.setPreferredSize(new Dimension(500, 300));
cv_frame.add(cv_content);
gv_x = 0;
gv_y = 0;
cv_content.update();
}
}
public static class content extends JPanel {
public void paint(Graphics graphic) {
super.paint(graphic);
draw(graphic);
}
public void update() {
super.repaint();
}
public void draw(Graphics graphic) {
Graphics2D graphic2D = (Graphics2D) graphic;
graphic2D.setPaint(Color.Red);
graphic2D.fillRect(gv_x, gv_y, 100, 100);
}
}
}
I don't know why the call to the update function isn't doing
anything though.
It draws the square at 50x and 50y, the sets it to 0x and 0y
immediately and then when I call repaint I expected it to
be moved to it's new coordinates although it's still at
50x and 50y.
Why is this?

Your solution is to use KeyBindings.
https://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html
and also.
You need to create a Swing Timer, Thread, or Loop , that manages the frames to be painted. and such
Here is a link for Swing Timers as they are pretty easy to implement:
https://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html
A lot of programs I see also have this ( AKA. working with threads.):
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});

Related

My game is flickering due to my painting directly in JFrame. How do I use JPanel? [duplicate]

I think I need to put some code where the comment is (or maybe use non static method but I am not sure). The main method creates the window and then starts the graphics method. I would like the blue square to flash.
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class paintTest extends JPanel{
private static JFrame theWindow = new JFrame("Window");
static boolean blueSqr = false;
public void paint(Graphics g) {
g.setColor(Color.RED);
g.fillRect(10, 10, 10, 10);
if(blueSqr){
g.setColor(Color.BLUE);
g.fillRect(10, 10, 10, 10);
}
}
public static void main(String[] args){
createWindow();
theWindow.getContentPane().add(new paintTest());
while(true){
blueSqr = false;
System.out.println("off");
try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}
blueSqr = true;
// Needs something here
System.out.println("on");
try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}
}
}
public static void createWindow(){
theWindow.setSize(500, 500);
theWindow.setLocationRelativeTo(null);
theWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
theWindow.setVisible(true);
}
}
Any help would be really good.
Use a Swing Timer to call repaint(). Also, override paintComponent() in a JPanel, rather than paint().
Something like this:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PaintTest extends JPanel{
boolean blueSqr = false;
PaintTest() {
setPreferredSize(new Dimension(100,25));
ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent ae) {
blueSqr = !blueSqr;
repaint();
}
};
Timer timer = new Timer(1000,al);
timer.start();
}
public void paintComponent(Graphics g) {
Color c = (blueSqr ? Color.BLUE : Color.RED);
g.setColor(c);
g.fillRect(10, 10, 10, 10);
}
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame theWindow = new JFrame("Window");
theWindow.getContentPane().add(new PaintTest());
createWindow(theWindow);
}
});
}
public static void createWindow(JFrame theWindow){
theWindow.pack();
theWindow.setLocationByPlatform(true);
theWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
theWindow.setVisible(true);
}
}
There were other improvements I could not be bothered documenting (code speaks louder than words). If you have any questions (check the docs first, then) ask.
your issues are
1) by calling Thread.sleep(int) in the Swing related code, never do that, for delaying in Swing (there are lots of topics about why not use sleep in programing languages ...) use Swing Timer
2) your JPanel doesn't returns any XxxSize
3) for Swing use paintComponent(), only if you have got really important reasons then use method paint() more about repaint and animating Graphics in the 2D Graphics tutorial
4) Swing GUI should be built in the Event Dispatch Thread

JLabel from a different class not being drawn

I am trying to show a label from another class. However when I add it to the frame it will not show. I have tried drawing it from the counter class itself by passing in the Frame which I would assume is not good practice (ignoring the fact it didn't work). As well as what is in the code below. Can anybody help me and explain why my solution will not show the created label? As you can most likely tell i'm very new to using JPanel.
CookieChaser Class
public class CookieChaser extends JPanel {
public static void main(String[] args) throws InterruptedException {
JFrame frame = new JFrame("Cookie Chaser");
CookieChaser game = new CookieChaser();
frame.add(game);
frame.setSize(1000, 1000);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
counter Score = new counter(frame);
cookie Cookie = new cookie();
JLabel item = counter.getLabel();
frame.add(item);
frame.setVisible(true);
while (true) {
game.repaint();
Thread.sleep(10);
}
}
#Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
}
}
Counter Class
public class counter {
int count;
static JLabel text;
public counter(JFrame frame){
count = 0;
text = new JLabel(String.valueOf(count));
text.setLocation(0,0);
text.setSize(50,50);
}
public static JLabel getLabel(){
return text;
}
I modified your code to create the following Swing GUI.
Whenever I create a Swing game or application, I use the model / view / controller pattern. This means I create a GUI model. The GUI model contains all of the fields that my GUI needs. Next, I create a GUI view which reads the values from the GUI model. Finally, I create one or more GUI controllers, which update the GUI model and refresh / repaint the GUI view.
I made the following changes to your code:
I created a GUI model. I created the Counter class. All the Counter class does is hold a counter value.
I created a GUI view, which uses the GUI model. I created the JFrame, JPanel, and JLabel all in the view class. You may use more than one class to create the view. Since this view was simple, I created everything in one class.
All Swing applications must start with a call to the SwingUtilities invokeLater method. The invokeLater method puts the creation and updating of the Swing components on the Event Dispatch thread. Oracle and I insist that all Swing applications start this way.
I created a separate Animation runnable so that you can see the JLabel updates. I increment the counter once a second.
The repaint method in the Animation class calls the SwingUtilities invokeLater method to ensure that the JLabel update is done on the Event Dispatch thread. The animation loop runs in a separate thread to keep the GUI responsive.
Here's the revised code.
package com.ggl.testing;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class CookieChaser implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new CookieChaser());
}
private JLabel counterLabel;
#Override
public void run() {
Counter counter = new Counter();
JFrame frame = new JFrame("Cookie Chaser");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainPanel = new JPanel();
counterLabel = new JLabel(" ");
mainPanel.add(counterLabel);
frame.add(mainPanel);
frame.setSize(300, 200);
frame.setVisible(true);
new Thread(new Animation(this, counter)).start();
}
public void setCounterLabel(String text) {
counterLabel.setText(text);
}
public class Counter {
private int counter;
public int getCounter() {
return counter;
}
public void setCounter(int counter) {
this.counter = counter;
}
public void incrementCounter() {
this.counter++;
}
}
public class Animation implements Runnable {
private Counter counter;
private CookieChaser cookieChaser;
public Animation(CookieChaser cookieChaser, Counter counter) {
this.cookieChaser = cookieChaser;
this.counter = counter;
}
#Override
public void run() {
while (true) {
counter.incrementCounter();
repaint();
sleep(1000L);
}
}
private void repaint() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
cookieChaser.setCounterLabel(Integer.toString(counter
.getCounter()));
}
});
}
private void sleep(long duration) {
try {
Thread.sleep(duration);
} catch (InterruptedException e) {
}
}
}
}

Grapghic doesn't move

I'm trying to make a code that will move a red ball with JButtons (and later add keybinders). There are no problems when I compile and when I run I see the ball but the JButtons won't affect him. I think the problem might be that the ball is drawed only once and then is called again and again without being drawed in the new position but I don't know how to fix that.
1) does anybody know how I can fix that?
2) is there a way to change the shape of a JPanel to a ball? (that would probably be a simpler way to move him)
package il.co.atlantis;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.*;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class KeyBinders implements ActionListener {
boolean right=true, left=false, up=false, down=false, inGame=true;
JPanel backgroundPanel, bannerPanel, scorePanel, applePanel;
JLabel currentScoreLabel, highestScoreLabel;
JButton upButton, downButton, rightButton, leftButton;
long millis =System.currentTimeMillis(), millisn =System.currentTimeMillis();
public static final int WID = 10, HEI = 10;
public static int x1 = 100, y1 = 100;
public class MyGraphics extends JComponent {
private static final long serialVersionUID = 1L;
MyGraphics() {
setPreferredSize(new Dimension(700, 500));
}
public void moveRight(){
++x1;
}
public void moveLeft(){
--x1;
}
public void moveUp(){
--y1;
}
public void moveDown(){
++y1;
}
public void paintComponent(Graphics g){
super.paintComponents(g);
g.setColor(Color.red);
g.fillOval(x1, y1, WID, HEI);
}
}
public JPanel CreateContentPane (){
JPanel totalGUI = new JPanel();
totalGUI.setLayout(null);
backgroundPanel = new JPanel();
backgroundPanel.setBackground(Color.black);
backgroundPanel.setLocation(100, 10);
backgroundPanel.setSize(700, 500);
totalGUI.add(backgroundPanel);
upButton = new JButton("up");
upButton.setLocation(0,0);
upButton.setSize(50,50);
totalGUI.add(upButton);
downButton = new JButton ("down");
downButton.setLocation(0,50);
downButton.setSize(50,50);
totalGUI.add(downButton);
rightButton = new JButton("right");
rightButton.setLocation(0,100);
rightButton.setSize(50,50);
totalGUI.add(rightButton);
leftButton = new JButton("left");
leftButton.setLocation(0,150);
leftButton.setSize(50,50);
totalGUI.add(leftButton);
MyGraphics tr = new MyGraphics();
tr.setLocation(100, 100);
backgroundPanel.add(tr);
return totalGUI;
}
public void ActionPerformed(ActionEvent h){
if(h.getSource() == upButton) {
--y1;
}
else if(h.getSource() == downButton){
++y1;
}
else if(h.getSource() == leftButton){
--x1;
}
else if(h.getSource() == rightButton){
++x1;
}
}
private static void createAndShowGUI() {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("[=] JButton Scores! [=]");
//Create and set up the content pane.
KeyBinders demo = new KeyBinders();
frame.setContentPane(demo.CreateContentPane());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(280, 190);
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
public KeyBinders() {
// TODO Auto-generated constructor stub
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
When you invoke action event, actionPerformed() function gets called, as you did. You have change the drawing position too. you need to call Component.repaint() which tells Swing t hat the entire component, whichever one you specified to be repainted , must be updated . So add this function calling in your code. For example:
public void ActionPerformed(ActionEvent h){
if(h.getSource() == upButton) {
--y1;
}
else if(h.getSource() == downButton){
++y1;
}
else if(h.getSource() == leftButton){
--x1;
}
else if(h.getSource() == rightButton){
++x1;
}
repaint();
}
Check the tutorial: Performing Custom Painting.
There's a method called repaint() you should familiarize yourself with.
When called on a component (such as a JFrame) it'll repaint all the components within. Naturally you need to call it if you want your changes to become visible on the screen.
As for custom painting, you shouldn't use a Component at all, rather use the Graphics.fillRect/fillOval etc. methods to just draw what you want.
See here for the custom painting tutorial.

how to suspend Applet in browser when tab is unselected

I'm making my first Applet. I have a JPanel which creates a Swing GUI and performs CPU intensive tasks (repainting a Component 60Hz). My Applet displays this JPanel on event dispatching thread. here is an abstraction of the problem. Normally I would launch the applet from an html document instead of having a main method. This program puts about a 40% load on my CPU.
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
import java.awt.event.*;
public class TestApplet extends JApplet {
TestPanel tp;
public void init() {
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
createGUI();
}
});
} catch (Exception e) {
System.err.println("createGUI didn't complete successfully");
}
}
private void createGUI() {
//Create and set up the content pane.
tp = new TestPanel();
tp.setOpaque(true);
setContentPane(tp);
}
public static void main(String[] args) {
JFrame f = new JFrame("Fish Tank");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JApplet ap = new TestApplet();
ap.init();
f.add("Center", ap);
f.pack();
f.setVisible(true);
}
}
class TestPanel extends JPanel{
public TestTank tt = new TestTank();
public TestPanel() {add(tt);}
public void stop() {tt.stop();}
public void start() {tt.start();}
}
class TestTank extends Component implements ActionListener{
private javax.swing.Timer timer;
TestTank(){
timer = new javax.swing.Timer(17, this);
timer.setCoalesce(true);
timer.start();
}
public Dimension getPreferredSize(){
return new Dimension(900, 700);
}
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
Dimension size = getSize();
g2.setPaint(new GradientPaint(0,0,Color.RED,900, 0,Color.WHITE));
g2.fill(new Rectangle2D.Float(0,0,size.width,size.height));
}
public void actionPerformed(ActionEvent e) {
repaint();
}
public void stop(){timer.stop();}
public void start(){timer.start();}
}
My question: How do I suspend and resume execution of the JPanel (FishTankPanel) when the user switches tabs or minimizes the browser? I want the Applet to stop using the CPU when the user can't see what it is doing. I need to capture browser events in order to execute tp.stop() in the applet. I have tried to execute them with window event listeners in the JPanel, and by overriding the start() and stop() methods in the Applet. I have been unsuccessful. Any suggestions or solutions would be appreciated.
I would do as Dave said and use the JApplet override start and stop methods to call your GUI methods. For instance, see changes in code:
public class TestApplet extends JApplet {
TestPanel tp;
public void init() {
// ... no change
}
private void createGUI() {
// ... no change
}
#Override
public void stop() {
if (tp != null) {
tp.stop();
}
}
#Override
public void start() {
if (tp != null) {
tp.start();
}
}
}
class TestTank extends Component implements ActionListener {
private javax.swing.Timer timer;
// ... no change
public void stop() {
timer.stop();
System.out.println("stop");
}
public void start() {
timer.start();
System.out.println("start");
}
}
It seems you might need to leverage some JS for this. E.G. use the JS shown in this answer to explicitly call the applet start() & stop() methods on focus & blur detection respectively.
The solution for my problem was to use javascript to implement the Page Visibility API. I then called the appropriate Java methods from within the javascript script.

Java function that gets called every frame

I was wondering if there was a function like void draw() which Processing programming language uses that gets called every frame. Or even just a function that loops infinitely when it gets called but only runs through it every time there is a new frame. I heard of something called a runnable in java how do i go about using this? also is there a better way then having a runnable with a delay like a function that is hardcoded to run every frame. Oh and also what is the function call that will allow me to see how much time (in milliseconds preferably) since the application has started running that way i can make my runnables / frame calls much more precise so that the game runs about the same speed on every computer regardless of the frame rate.
Perhaps you need something like this
import java.awt.Graphics;
import java.awt.Point;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
public class Repainter extends JPanel {
private Point topLeft;
private int increamentX = 5;
public Repainter() {
topLeft = new Point(100, 100);
}
public void move() {
topLeft.x += increamentX;
if (topLeft.x >= 200 || topLeft.x <= 100) {
increamentX = -increamentX;
}
repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawRect(topLeft.x, topLeft.y, 100, 100);
}
public void startAnimation() {
SwingWorker<Object, Object> sw = new SwingWorker<Object, Object>() {
#Override
protected Object doInBackground() throws Exception {
while (true) {
move();
Thread.sleep(100);
}
}
};
sw.execute();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Repaint Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
Repainter repainter = new Repainter();
frame.add(repainter);
repainter.startAnimation();
frame.setVisible(true);
}
});
}
}

Categories

Resources