Why won't this render? - java

here is my code:
import java.awt.*;
class g
{
public static void main(String arg[])
{
System.out.println("hello");
Rectangle rec=new Rectangle(4,4);
Graphics2D.draw(rec);
}
}
when i try to compile it i get this:
non-static method draw(java.awt.Shape) cannot be referenced from a static context
this confuses me. Why does this happen? If Graphics2D is an abstract Class how can Graphics2D.draw(shape s) be non-static?

If Graphics2D.draw was static, where would you expect the rectangle to be drawn? The top, left corner of your monitor? The currently active window? Inside a new window?
Graphics2D.draw is not static because there are many graphics contexts in which you could be drawing. Explain to us where you expect the rectangle to be drawn and we can help you obtain the appropriate Graphics2D object to suit your needs.
If you want to learn about graphics, you should be able to do something like this:
public class MyGraphicsFun {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(800, 600);
frame.add(
new JComponent() {
public Dimension getPreferredSize() {
return new Dimension(800, 600);
}
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.RED);
// Any other drawing you want...
}
}
);
frame.setVisible(true);
}
}
Disclaimer: This code was written from memory, so it could have errors

Not in this javadocs:
http://download.oracle.com/javase/6/docs/api/
Which one are you looking at?
Besides, why don't you believe the compiler? What's the point of disagreeing if you'll never get it past the compiler? Just do what it says and get on with it.
You sound like a lost soul. Start with this:
http://download.oracle.com/javase/tutorial/2d/index.html

Related

How to draw a simple class object in Java(JFrame)?

I am quite new to Java application development and I want to draw some simple shapes in the JFrame-canvas without using one main class but rather split it into a main class and a class playerRectangle. In the playerRectangle class I created a method paint:
public void paint(Graphics g) {
setSize(500, 500);
g.drawRect(320, 20, 640, 120);
}
I then created an object in some render funtion in the main class and called the paint function of this object.
playerRectangle p1 = new playerRectangle();
p1.paint(null);
But somehow it threw the java.lang.NullPointerException error and didn't render the rect to the screen. When I don't split this function into two classes it works properly even though it throws this error. So please help me and tell me, what I am missing here.
Any research on Youtube and other stuff only told me that I have to create classes like screen etc. but I am not so sure that is helping me.
Thanks for helping
Simple example how to draw Rectangle using standard libraries :
public class SomeClass extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.GREEN);
g.fillRect(0,0,320,220);
}
SomeClass() {
JFrame frame = new JFrame();
frame.serContentPane(this);
frame.setBounds(0,0,320,220);
frame.setVisible(true);
}
}
Class with main method:
public class Main {
public static void main(String[] args) {
new SomeClass();
}
}

Java 2D Graphics BufferedImage FillRect issue

I am still getting used to painting graphics on java and am trying to write a simple graphics program that paints a background using a buffered image. However, strangely enough, even though my jpanel size is set to 1200x400 and so are the buffered image and fillrect method, there is a small "gap" as you can see in the picture I have attached so the panel is clearly larger than 1200x400 but I don't understand why? What does the setPreferredSize method actually do? Also when I change my fillrect method and bufferedimage to 1300x500 there is no longer a gap so this is clearly the issue. If anyone has any advice as to where I am going wrong I would greatly appreciate it, thanks
Here is my code:
public class Q2 extends JPanel {
private BufferedImage image;
public static void main(String[] args) {
Q2 test = new Q2();
}
public Q2() {
this.init();
}
private void init() {
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setContentPane(this);
this.setPreferredSize(new Dimension(1200,400));
refreshCanvas();
window.pack();
window.setVisible(true);
window.setResizable(false);
}
public void paintComponent(Graphics g) {
Graphics2D twoD = (Graphics2D) g;
twoD.drawImage(image,0,0,null);
}
private void refreshCanvas() {
image = new BufferedImage(1200,400,BufferedImage.TYPE_INT_ARGB);
Graphics2D twoD = image.createGraphics();
twoD.setColor(Color.BLACK);
twoD.fillRect(0, 0, 1200,400);
repaint();
}
}
Have a look at this answer here.
You have to put window.setResizeable(false); before window.pack();. This should fix it.

I'm trying to move an object but i want it to leave a trail

So basically it won't leave a trail. I tried to remove super.paint and i've tried to make multiple but it either creates an error or it doesn't. I've gone throught it atleast 10 times which is why i went here. Thanks in advance!
import javax.swing.*;
import java.awt.*;
public class Grafik extends JPanel {
private int x = 0;
private void moveBall()
{
x += 1;
}
public void paint(Graphics g)
{
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.fillRect(x, 50, 20, 80);
}
public static void main(String[] args)
{
JFrame frame = new JFrame();
Grafik grafik = new Grafik();
frame.setSize(700, 800);
frame.setLocation(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(grafik);
frame.setTitle("Mitt spel");
frame.setResizable(false);
frame.setVisible(true);
while(true)
{
grafik.repaint();
grafik.moveBall();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Problems/Solutions:
Swing painting is done in the paintComponent method override, not the paint method.
Be sure to call the `super's paintComponent method first thing in your own override method, so the JPanel can do house-keeping painting
Your animation loop should be a Swing Timer, not a while (true) loop as the latter risks running afoul of Swing threading rules
If you want to create an animation but leave persisting images within the drawing then
Either create an ArrayList of objects, perhaps Points, that represent the trail, and in your paintComponent method draw the trail using a for loop that iterates through the ArrayList, or
use a BufferedImage as a background image, one that is drawn within the paintComponent method immediately after calling super.paintComponent(g) but before drawing the moving sprint. Draw your trail into this BufferedImage by getting a Graphics object out of it, by calling getGraphics() on the BufferedImage.

Background image not displaying in java project

The variable was made, the image is loaded into the variable and the paintComponent is asked to display the image in my JPanel. I can't see my mistake.
public class Main extends JFrame {
public static void main(String[] args) {
JFrame frame = new Main();
frame.setSize(1524, 715);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Animatieproject Stijn Mannaerts: Free Kick");
frame.setContentPane(new Voetbalveld());
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
}
class Voetbalveld extends JPanel {
private ImageIcon afbIntro;
public Voetbalveld() {
afbIntro = new ImageIcon("scr/afbeeldingen/Intro.jpg");
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
afbIntro.paintIcon(null, g, 0, 0);
}
}
That isn't how painting is done. Why not use Graphics.drawImage() instead? Check out this tutorial: http://docs.oracle.com/javase/tutorial/uiswing/painting/
Your code seems right to me. Make sure you don't want src instead of scr. Next, if your image folder is inside source folder of your project then you might want to try this:
afbIntro = new ImageIcon(Voetbalveld.class.getResourceAsStream("scr/afbeeldingen/Intro.jpg"));
or
afbIntro = new ImageIcon(Voetbalveld.class.getResourceAsStream("afbeeldingen/Intro.jpg"));
depending on your file structure. The path in the second example needs to be relative to the file Main.java.
The frame class
import javax.swing.JFrame;
public class Main
{
public static void main(String[] args)
{
Jframe frame = new JFrame("Animatieproject Stijn Mannaerts: Free Kick");
frame.setSize(1524, 715);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new Voetbalveld());
frame.setVisible(true);
}
}
The panel class
import javax.swing.*;
import java.awt.*;
public class Voetbalveld extends JPanel
{
public void paintComponent(Graphics g)
{
ImageIcon afbIntro = new ImageIcon("scr/afbeeldingen/Intro.jpg");
/*The following are two methods for image sizing,
*Use the one that best fits your code:
*
*g.drawImage(afbIntro.getImage(), x, y, null);
*Fill in the arguments for x and y to locate your upper left corner
*The image will be in it's original size with the designated upper left corner
*
*g.drawImage(afbIntro.getImage(), x, y, w, h, null);
*Fill in the arguments for w and h to set the width and height of your image
*The image will be in it's scaled size (w and h) and starting at the
*designated upper left corner (x and y)
*/
}
}
You spelled src wrong. You have scr.
"scr/afbeeldingen/Intro.jpg"
Fix that

JFrame image display at frame resize

I have this JFrame containing a children of JPanel wherein it displays the image which is declared in this manner.
BufferedImage image = ImageIO.read(filename);
The program displays the image properly. But the only thing is, it requires to resize the frame to display the image.
Is there a possible way to display the image once the frame appears?
You should override paintComponent(Graphics g) and draw the image therein. In this case, you should do this for the JPanel component (I think? If not, do this for the JComponent(s) you're referring to). Also, since Swing is not thread-safe, ensure these modifications are performed in the EDT.
EXAMPLE
public class Demo{
private static BufferedImage bi;
public static void main(String[] args){
try{
loadImage();
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run(){
createAndShowGUI();
}
});
}
catch (IOException e){
// handle exception
}
}
private static void loadImage() throws IOException{
bi = ImageIO.read(new File("src/resource/braveheart.PNG"));
}
private static void createAndShowGUI(){
final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JPanel panel = new JPanel(){
#Override
protected void paintComponent(Graphics g){
Graphics g2 = g.create();
g2.drawImage(bi, 0, 0, getWidth(), getHeight(), null);
g2.dispose();
}
#Override
public Dimension getPreferredSize(){
return new Dimension(bi.getWidth(), bi.getHeight());
}
};
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
OUTPUT
It's important to keep in mind that this example ignores rendering hints, so when you maximize the JFrame, the image quality will be very poor. :)
EDIT
When answering this question, I assumed you had a basic understanding of Swing. I suppose I assumed too much. It is important to mention that all components should be added to the top-level container before it's been realized (i.e. made visible). This will ensure that everything is rendered without having to resize your frame. As others have suggested, you could have simply used a JLabel to render the image, and then added it to your JPanel. Instead, I promoted custom painting, which is perfectly acceptable, and to me, cleaner.
for dispaly Image or ImageIcon is better look for JLabel (basic stuff)

Categories