Leaving a trace while painting on a transparent JPanel - java

I am relatively new graphics programmer in Java and here is a simple program I was trying. Here is the full code: broken into 3 classes.
Class 1:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MyPanelB extends JPanel
{
int x=0;
int y=0;
public void paintComponent(Graphics g)
{
x=x+1;
y=y+1;
setOpaque(false);
//setBackground(Color.cyan);
g.setColor(Color.red);
g.fillRect(x,y,x+1,y+1);
}
}
Class 2:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MyFrameB implements ActionListener
{
MyPanelB p1;
public void go()
{
JFrame f1= new JFrame();
f1.setLocation(150,50);
f1.setSize(800,700);
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel p0= new JPanel();
p0.setBackground(Color.yellow);
p0.setLayout(new BorderLayout());
f1.add(p0);
p1= new MyPanelB();
p0.add(p1);
f1.setVisible(true);
Timer t = new Timer(200,this);
t.start();
}
public void actionPerformed(ActionEvent ev)
{
p1.repaint();
}
}
Class 3(Main Class):
public class MyBMain
{
public static void main(String[] args)
{
MyFrameB m1= new MyFrameB();
m1.go();
}
}
If I comment out the staement
setOpaque(false);
in class 1, I get a trace(of red expanding rectangles) but not a yellow background.
Otherwise I do not get a trace, but I do get a yellow background.
I want both the yellow background and the trace.
Please feel free to modify my code so that I get both a trace and a yellow background.
I provided the full code so one can easily check out the output.

Basically you need to repaint the entire component every time the paintComponent() method is called. This means you need to start from 0 and iterate up to the current value of x.
So your paintComponent() method should look something like:
public void paintComponent(Graphics g)
{
super.paintComponent(g);
x=x+1;
y=y+1;
for (int i = 0; i < x; i++)
{
g.setColor(getForeground());
//g.fillRect(x,y,x+1,y+1);
g.fillRect(i,i,i+1,i+1);
}
}
This means you don't need your panel0. I also change the code for creating panel1:
p1= new MyPanelB();
p1.setForeground(Color.RED);
p1.setBackground(Color.YELLOW);
f1.add(p1);
Even this code I posted for you is not correct. The x/y values should NOT be updated in the paintComponent() method. Try resizing the frame while your code is executing to see why?
Your ActionListener should invoke a method in your panel1 class to update property of the class to tell the paintComponent() how many times to iterate and paint the square when it is invoked. The the paintComponent() method should reference this property in the loop that I created.

Related

PaintComponent don't seem to get call or to show

My problem is really simple : I have this little program, and it just don't show the red box I'm trying to make :
Main
public class Main {
public static void main(String[] args) {
Affichage a = new Affichage();
a.setVisible(true);
}
}
Affichage :
import java.awt.*;
import javax.swing.*;
public class Affichage extends Frame{
public Affichage(){
setTitle("Exo 1 : Galerie");
setSize(1120,560);
Graphique graph = new Graphique();
this.add(graph);
}
}
Graphique :
import javax.swing.*;
import java.awt.*;
public class Graphique extends JComponent {
#Override
public void paintComponents(Graphics g) {
super.paintComponents(g);
Graphics pinceau = g.create();
pinceau.setColor(Color.RED);
pinceau.fillRect(100, 100, 200, 200);
System.out.println("test");
}
}
I bet it's ridicule but I can't find what it is, help me.
PS : yes the test don't get print too
Actually, don't extend JFrame as it is bad practice. Just make an instance of it. To paint, extend JPanel and override paintComponent.
JFrame f = new JFrame();
f.add(new MyPanel());
class MyPanel extends JPanel {
// other stuff
public void paintComponent(Graphics g) {
super.paintComponent(g);
// painting stuff.
}
}
And remember not to mix Swing and AWT components.
You are adding a Swing component (javax.swing.JComponent) to an AWT frame (java.awt.Frame). Noone will call the paintComponents() method, that's why you don't get any output or result. Extend from javax.swing.JFrame instead, so you have a Swing frame with a Swing component.

Java AWT How to draw objects with delay

I would like to draw a new random shape every 2 seconds.
I already have a window, that shows immediately some shapes. I tried to mess around with Timer to make new things appear in the window after a few seconds, but it didn't work, or the whole program freezes. Is it a good idea to use Timer? How should I implement it, to make it work?
import javax.swing.*;
import java.awt.*;
import java.util.Random;
class Window extends JFrame {
Random rand = new Random();
int x = rand.nextInt(1024);
int y = rand.nextInt(768);
int shape = rand.nextInt(2);
Window(){
setSize(1024,768);
setVisible(true);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public void paint(Graphics g) {
super.paint(g);
g.setColor(new Color(0, 52, 255));
switch(shape) {
case 0:
g.fillOval(x, y, 50, 50);
break;
case 1:
g.fillRect(x,y,100,100);
break;
}
repaint();
}
}
public class Main {
public static void main(String[] args) {
Window window = new Window();
}
}
I would also like to draw some random shapes. Is it ok, to use switch in paint method for this purpose? I would make a random variable, if it's 1 it would paint rectangle, if it's 2 it would paint oval etc.
First of all, do not change the way JFrame gets painted (with other words, do not override paintComponent() of a JFrame). Create an extending class of JPanel and paint the JPanel instead. Secondly, do not override paint() method. Override paintComponent(). Thirdly, always run Swing applications with SwingUtilities.invokeLater() since they should run in their own thread named EDT (Event dispatch thread). Finally, javax.swing.Timer is what you are looking for.
Take a look at this example. It paints an oval shape in random X,Y every 1500ms.
Preview:
Source code:
import java.awt.BorderLayout;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class DrawShapes extends JFrame {
private ShapePanel shape;
public DrawShapes() {
super("Random shapes");
getContentPane().setLayout(new BorderLayout());
getContentPane().add(shape = new ShapePanel(), BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500, 500);
setLocationRelativeTo(null);
initTimer();
}
private void initTimer() {
Timer t = new Timer(1500, e -> {
shape.randomizeXY();
shape.repaint();
});
t.start();
}
public static class ShapePanel extends JPanel {
private int x, y;
public ShapePanel() {
randomizeXY();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.fillOval(x, y, 10, 10);
}
public void randomizeXY() {
x = (int) (Math.random() * 500);
y = (int) (Math.random() * 500);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new DrawShapes().setVisible(true));
}
}
First, don't subclass JFrame; subclass JPanel instead, and place that panel in a JFrame.
Second, don't override paint() - override paintComponent() instead.
Third, create a Swing Timer, and in its actionPerformed() method make the changes you want and then call yourPanel.repaint()

How to call java paintComponent using repaint

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.

Java: Minimizing a Jframe Window without causing the program to run again

My program uses a Jframe, whenever I minimize the window and bring it back up, the program runs itself again. How can I cause it to not do this when minimized?
Code:
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;
import java.util.Random;
public class AB extends Component {
public void paint(Graphics g) {
Random r = new Random();
g.setColor(Color.black);
g.fillRect(r.nextInt(100), r.nextInt(100), 100, 100);
}
public static void main(String[] args) {
JFrame f = new JFrame("Load Image Sample");
f.getContentPane().setBackground(Color.white);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
f.setSize(dim.width, dim.height);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
f.add(new AB());
f.setVisible(true);
}
}
My guess: you have program logic present in your paint(...) or paintComponent(...) method override. If so, get the logic out of these methods, because as you're finding out, you do not have full control over when or even if they are called. The logic belongs elsewhere, perhaps in a Swing Timer, hard to say without code or a more detailed question.
If this doesn't help, then you'll need to show us the bugs in your code by creating and posting a minimal, runnable, example program as well as tell us more of the details of your program and its misbehavior.
After looking at your code, I see that my assumption/guess was correct: you are selecting your random numbers inside of the paint method, and so they will change with each repaint. You will want to
Create a class that extends JPanel.
Create your random numbers in this class's constructor, and use the random numbers to set class instance fields.
Override this class's paintComponent method
Don't forget to call the super's paintComponent method inside this method.
Use the numbers generated in the constructor in the paintComponent method override to draw your rectangle.
Place your JPanel into a JFrame.
e.g.,
import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.*;
#SuppressWarnings("serial")
public class RandomRect extends JPanel {
private static final int MAX_INT = 100;
private static final Color RECT_COLOR = Color.black;
private Random random = new Random();
private int randomX;
private int randomY;
public RandomRect() {
randomX = random.nextInt(MAX_INT);
randomY = random.nextInt(MAX_INT);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(RECT_COLOR);
g.fillRect(randomX, randomY, MAX_INT, MAX_INT);
}
private static void createAndShowGui() {
JFrame frame = new JFrame("RandomRect");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new RandomRect());
//frame.pack();
// frame.setLocationRelativeTo(null);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

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