I know this is probably simple, but it is causing me trouble. When I use paint(), it shows nothing, and if I use paintComponent(), it shows an error (cannot find symbol). What am I doing wrong?
This is an example of using paint():
import javax.swing.*;
import java.awt.Graphics;
import java.awt.*;
public class Test extends JFrame {
public Test() {
this.setPreferredSize(new Dimension(400, 400));
this.pack();
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
#Override
public void paint(Graphics g) {
super.paint(g);
// define the position
int locX = 200;
int locY = 200;
// draw a line (there is now drawPoint..)
g.drawLine(locX, locY, locX, locY);
}
public static void main(String[] args) {
Test test = new Test();
}
}
Comments say this is a nice and simple code but I can't see anything because it shows nothing.
[SOLVED]
To all who answered, thanks. LOL at me bros, I really didn't notice that there was a tiny dot. Awesome dude, thanks.
You code is not the recommended way of doing things, but that aside, it works.
You do not set a color to paint with, and you draw a single dot. You probably just didnt see it (I had to look twice). It draw a single black pixel at 200, 200.
I would bet the problem is that you're only drawing a single point, so it's hard to see. Your code works fine for me.
However, you should be extending JPanel, not JFrame. Recommended reading: http://docs.oracle.com/javase/tutorial/uiswing/painting/
Related
Background:
I'm tearing my hair here because I've used awt and Swing a couple of times, and I always run into a roadblock during my initial graphics setup and I never seem to have an "Of course, this thing again! I just have to something something"-moment. This time I can't seem to get even basic drawing to work!
Problem description:
I wish to draw a number of simple boxes in a JFrame (via a JPanel, if necessary). To this end I have a Sprite extends JComponent class which currently only draws simple geometric shapes but will eventually do things with BufferedImageor somesuch.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import javax.swing.JComponent;
#SuppressWarnings("serial")
public class Sprite extends JComponent {
private Rectangle rctBounds;
private Color clrFill;
public Sprite(int x, int y, Color color) {
this.rctBounds = new Rectangle(x, y, 100, 100);
this.clrFill = color;
}// Sprite(int,int,Color)
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(clrFill);
g.fillRect(rctBounds.x, rctBounds.y, rctBounds.width, rctBounds.height);
}// paintComponent(Graphics)
}// Sprite.class
The window for these to go in is obtained by a simple Win extends JFrame class รก:
import javax.swing.JFrame;
public class Win extends JFrame{
public Win(){
setSize(800,600);
setLocation(100,100);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
Finally, components are initialized and connected in the main method, in the class run, using JComponent's (I believe) add() method, called on an instance of Win:
import java.awt.Color;
public class run {
public static void main(String[] args) {
Win w = new Win();
Sprite s1 = new Sprite(10,100, Color.BLUE);
Sprite s2 = new Sprite(200,200, Color.RED);
Sprite s3 = new Sprite(300,200, Color.CYAN);
w.add(s1);
w.add(s2);
w.add(s3);
}//main()
}//run.class
Expectations vs. Reality:
Now, I expect a window with three colored boxes, as in this image (all boxes visible). Instead, only the final JComponent to be added shows up, as seen here (only cyan box painted). What's even more infuriating is that attempting to edit the JFrame's layout or adding a JPanel as an intermediary container for the Sprites results in a blank window.
Exasperated Plea:
I'm at a complete loss! Everything I find on here talks about improper use of paintComponent(Graphics) (using paint() instead, forgetting to #Override, not propagating the graphical context properly, etc) or to use a JPanel as an intermediary container. The most infuriating part of all this is that I've built two functioning programs using Swing before (school assignments) and, looking at that code, I cannot for the life of me figure out what I'm doing wrong here! Please help!
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.
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.
I am complete Java noob and this question will be very easy. I did try to find answer across whole internet but, nothing was particularly what I need (if you know any tutorial pages for this subject please post link I would be very grateful.)
Basically I am trying to draw string in my DrawPanel. I know I need to call method somewhere in order to do so but I have no idea where. My draw panel has method:
public void drawGuessWord(Graphics g){
WordsList guessWord = new WordsList();
String word = guessWord.pickWord();
g.drawString(word, 20, 20);
}
And I want to call that method so it would draw string inside DrawPanel.
Just in case this is my whole DrawPanel:
import java.awt.*;
import javax.swing.*;
import javax.swing.border.Border;
public class DrawPanel extends JPanel {
DrawPanel(){
Border raisedbevel = BorderFactory.createRaisedBevelBorder();
Border loweredbevel = BorderFactory.createLoweredBevelBorder();
this.setBackground(Color.WHITE);
this.setBorder(BorderFactory.createLoweredBevelBorder());
this.setPreferredSize(new Dimension(200,200));
}
public void drawGuessWord(Graphics g){
WordsList guessWord = new WordsList();
String word = guessWord.pickWord();
g.drawString(word, 20, 20);
}
}
public void paint(Graphics g)
{
g.drawString(word, 20, 20);
}
In addition to MimiEAM's solution, you might like to take a read of
Performing Custom Painting
2D Graphics
i have a problem with the repaint function
when i compile, the error is
pc3#pc3-desktop:~/Desktop$ javac LoadImageApp.java
LoadImageApp.java:17: cannot find symbol
symbol : method repaint(int,int,int,int,int)
location: class java.awt.Graphics
g.repaint(1000,0,0,1440,900)
^
1 error
and this is my code -->
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;
public class LoadImageApp extends Component {
BufferedImage img;
public void paint(Graphics g) {
g.drawImage(img, 0, 0, null);
super.update(g);
g.repaint(1000,0,0,1440,900);
}
public LoadImageApp() {
try{
img = ImageIO.read(new File("screenshot.jpg"));
}catch(IOException e){}
}
public Dimension getPreferredSize() {
if (img == null) {
return new Dimension(100,100);
} else {
return new Dimension(img.getWidth(null), img.getHeight(null));
}
}
public static void main(String[] args) {
JFrame f = new JFrame("Load Image ");
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
f.add(new LoadImageApp());
f.pack();
f.setVisible(true);
}
}
can anyone tell me what is the problem ? i intend to do a program that is display the image and keep refreshing every 0.1 seconds . the image will be receive from other machine and every 0.1 seconds and the image will be keep override the old image ..
thanks in advance for those who reply .. THANK YOU !!!!!!
I would highly recommend reading the Swing tutorials and understand the methods defined in the Graphics class as well as the Component class. More specifically, what do you expect the statement:
g.repaint(1000, 0, 1440, 900)
to do? If it's repaint one of your components based on some interval, you can do this using a TimerTask. Also from reading the tutorials you'll see why you have a compilation error. The repaint method is not defined on Graphics.
As a side note, don't name your method paint - it's confusing since there is a paint method already defined in Component
I don't actually know where you found that repaint method signature for Graphics since it does not exist.
You should instead call repaint on the component which is the owner of that specified Graphics, which is the LoadImageApp itself.
But first of all you absolutely need to study a little bit better how drawing works with AWT and Swing, take a look here.
In Addition you should use something that schedules your update phase, otherwise your code, as it is, doesn't make any sense. There is nothing that is periodically loading the imagine neither anything that is repainting the frame. I'd suggest a TimerTask like Amir told you.