How to call java paintComponent using repaint - java

In this video drawing() method is called in main class. When we remove drawing() in the main method it still draws the shape. How can we avoid this situation ?
shapes class:
import java.awt.*;
import javax.swing.*;
public class shapes{
public static void main(String[] args){
JFrame frame = new JFrame("Test");
frame.setVisible(true);
frame.setSize(400,200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
draw object = new draw();
frame.add(object);
object.drawing();
}
}
Draw class:
import java.awt.*;
import javax.swing.*;
public class draw extends JPanel{
public void drawing(){
repaint();
}
public void paintComponent(){
super.paintComponent(g);
g.setColor(Color.BLUE);
g.fillRect(10,15,100,100);
}
}

There are some minor issues with the code, but I assume that it's only a small snippet for demonstration purposes. For details, have a look at Performing Custom Painting.
Actually, this tutorial would also answer your question, but to summarize it:
The paintComponent method will be called automatically, "by the operating system", whenever the component has to be repainted. The call to repaint() only tells the operating system to call paintComponent again, as soon as possible. So you can call repaint() to make sure that something that you canged appears on the screen as soon as possible.
If you explicitly want to enable/disable certain painting operations, you can not influence this by preventing paintComponent from being called. It will be called anyhow. Instead, you'll introduce some flag or state indicating whether something should be painted or not.
In your example, this could roughly be done like this:
import java.awt.*;
import javax.swing.*;
public class Draw extends JPanel{
private boolean paintRectangle = false;
void setPaintRectangle(boolean p) {
paintRectangle = p;
repaint();
}
#Override
public void paintComponent(){
super.paintComponent(g);
if (paintRectangle) {
g.setColor(Color.BLUE);
g.fillRect(10,15,100,100);
}
}
}
You can then call the setPaintRectangle method to indicate whether the rectangle should be painted or not.

Related

Java program | What I give instead graphics in constructor?

/*If given constructor values draw moving circle
* But if it does not give him the values ​​draws a line
*/
package samr;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Graphics;
public class AX{
public static class panel extends JPanel{
public int w,c=1;
public panel(int start,int end){
int x=start;
int y=end;
w=x;
paint(?,x,y);
}
public panel(){
paint(?);
}
public void paint(Graphics e){
e.drawLine(0,0,500,500);
}
public void paint(Graphics g,int x,int y){
super.paint(g);
if(w<=y){
w=w+c;
if(w==x||w==y){c=c*-1;}
g.drawOval(w,0,50,50);
this.repaint();
}
}
}
public static void main(String[] arg){
JFrame f=new JFrame("test");
f.setBounds(100,100,500,500);
panel p=new panel(100,300);
f.add(p);
f.setVisible(true);
}
}
What I give instead graphics in constructor?
You don't, that's provided by the system, take a look at Painting in AWT and Swing and Performing Custom Painting for more details about how painting works in Swing.
If you want to update the component, then you should call repaint
Painting in Swing is done via a passive algorithm, to improve performance, you should never modify the state or call any functionality which could modify the state of the UI from within any paint method, so you should remove the repaint call in your paint method.
By convention, we are encouraged to override paintComponent instead of paint, it's safer to do so.
Painting should paint the current state of the component, this means you will need to set some variables to the desired values and call repaint for them to updated.

In my JFrame project, my methods are being completed twice. What is causing this?

First class
package com.mudd.render;
import java.awt.Dimension;
import javax.swing.JFrame;
import com.mudd.game.Game;
public class render {
int width = 500;
int height = 600;
Game g = new Game();
public void show(){
JFrame gameWindow = new JFrame("..");
gameWindow.setPreferredSize(new Dimension(width, height));
//gameWindow.setIconImage(new ImageIcon(imgURL).getImage());
gameWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gameWindow.pack();
gameWindow.add(g);
gameWindow.setVisible(true);
}
public static void main(String[] args) {
render game = new render();
game.show();
}
}
Second class
package com.mudd.game;
import java.awt.Graphics;
import javax.swing.JPanel;
#SuppressWarnings("serial")
public class Game extends JPanel {
public void paint(Graphics g){
g.fillOval(10, 10, 500, 500);
System.out.println("Test");
}
}
What is causing my Test print statement to be printed twice? If I add other priintlns it will also print them both out. I've been learning Java from Head First Java and I've done other small command line projects but nothing like this has ever happened to me.
Swing graphics are passive -- you don't call the painting methods directly yourself, but rather the JVM calls them. They are sometimes possibly called at your suggestion such as when you call repaint() but even this is never a guarantee, and they are sometimes possibly called at the suggestion of the platform, such as when it determines that your application has "dirty" pixels that need cleaning. So you have to plan for this -- the painting method should contain no code that changes the state of the object nor should it contain business logic code. Instead it should have code for painting and nothing more.
For more details on this, please see:
Lesson: Performing Custom Painting: introductory tutorial to Swing graphics
Painting in AWT and Swing: advanced tutorial on Swing graphics
Side recommendations:
Override the JPanel's paintComponent method, not its paint method
Use the #Override annotation for any method override
Don't forget to call the super's method in your override.

JPanel won't display

I got a class that's supposed to launch a game (with main()), and the game's opening screen. The class with main() (named Starter), that extends JFrame, creates a new OpeningScreen class (extending JPanel), and adds it to the JFrame.
For some reason, the OpeningScreen won't be added to the JFrame. Code:
Starter class:
import javax.swing.*;
import java.awt.*;
public class Starter extends JFrame {
public Starter(){
setSize(500,500);
setResizable(false);
setTitle("Ping-Pong Battle");
setDefaultCloseOperation(EXIT_ON_CLOSE);
OpeningScreen openingS = new OpeningScreen();
add(openingS);
setVisible(true);
}
public static void main(String[]args){
Starter starter = new Starter();
}
}
OpeningScreen class:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class OpeningScreen extends JPanel {
public OpeningScreen(){
setBackground(Color.BLACK);
setFocusable(true);
setVisible(true);
}
public void paint(Graphics g){
// Soon code here to be drawn.
}
public void startGame(){
Board board = new Board();
}
}
What's the problem? Thanks
EDIT: The constructor of OpeningScreen does run, but doesn't paint the background black. Also, trying to draw things in paint() doesn't work.
Your problem arises from overriding paint in your OpeningScreen class. The background is not drawn because you never draw it! Call super.paint(g) to fix this.
However, it is generally recommended to use paintComponent() instead of paint(). Just move your code to paintComponent.
This method correctly draws a black background a red square:
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g.fillRect(100, 100, 100, 100);
}
I think because you override paint() the background doesn't get painted, so it appears like the Panel isn't added. Commenting out the paint method results in the Window being black for me.
Also, drawing in the paint method works for me, maybe your color is set to black so it doesn't show on the black background ? Try g.setColor(Color.white) before drawing.

Java : repaint is undefined in class

I am new on java. I want to create an abstract factory in java. I have a class point and I want to extend other classes ( circle, rectangle ) from this.
Here is my code. It says repaint is undefined..
import javax.swing.*;
import java.awt.*;
import java.awt.Component;
import javax.swing.*;
public class Circle extends Point {
public void Draw() {
repaint();
}
public void paint(Graphics g) {
g.drawOval(this.x, this.y, 10, 10);
}...
The class Point simply encapsulates an x and y integer value. It is not derived from java.awt.Component so therefore repaint cannot be invoked.
For custom painting in Swing extend JComponent or JPanel and override paintComponent rather than paint. Remember to invoke super.paintComponent(g).
See: Performing Custom Painting
repaint() method is part of java.awt.Component.Point is not a subclass of java.awt.Component. You can't use it that way.

Buttons all over the window - Java

I am trying to learn java and i am practicing with a simple program with 2 simple buttons. Here is my code :
import javax.swing.*;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("Askhsh 3");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ColorJPanel application = new ColorJPanel();
frame.add(application);
frame.setSize(500,500);
frame.setVisible(true);
}
}
And the class ColorJPanel:
import java.awt.*;
import javax.swing.*;
public class ColorJPanel extends JPanel{
public void paintComponent(Graphics g)
{
super.paintComponent(g);
this.setBackground(Color.WHITE);
JButton arxikopoihsh = new JButton("Αρχικοποίκηση");
JButton klhrwsh = new JButton("Κλήρωση");
add(arxikopoihsh);
add(klhrwsh);
this.revalidate();
this.repaint();
}
}
As you can see the only thing i want to do for now is to place 2 simple buttons that do nothing! Here is my output:
http://imageshack.us/photo/my-images/847/efarmogh.jpg/
When i am running the application i am seeing the buttons filling the window!
Note that if i remove the "this.revalidate();" command i have to resize the window to see the buttons !
Thanks very much for your time :)
Don't add components in paintComponent. This method is for painting only, not for program logic or to build GUI's. Know that this method gets called many times, often by the JVM and most of the time this is out of your control, and also know that when you ask for it to be called via the repaint() method, this is only a suggestion and the paint manager may sometimes choose to ignore your request. The paintComponent method must be lean and fast as anything that slows it down will slow down the perceived responsiveness of your application.
In your current code, I don't even see a need to have a paintComponent method override, so unless you need it (if doing for instance custom painting of the component), I suggest that you get rid of this method (and the calls to repaint and revalidate). Instead, add your components in the class's constructor and make sure to pack your top level container after adding components and before calling setVisible(true). Most important -- read the Swing tutorials as this is all covered there.
e.g.,
Main.java
import javax.swing.*;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("Askhsh 3");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ColorJPanel application = new ColorJPanel();
frame.add(application);
frame.pack();
frame.setVisible(true);
}
}
ColorJPanel.Java
import java.awt.*;
import javax.swing.*;
public class ColorJPanel extends JPanel{
public static final int CJP_WIDTH = 500;
public static final int CJP_HEIGHT = 500;
public ColorJPanel() {
this.setBackground(Color.WHITE);
JButton arxikopoihsh = new JButton("Αρχικοποίκηση");
JButton klhrwsh = new JButton("Κλήρωση");
add(arxikopoihsh);
add(klhrwsh);
}
// let the component size itself
public Dimension getPreferredSize() {
return new Dimension(CJP_WIDTH, CJP_HEIGHT);
}
}

Categories