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

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();
}
}

Related

Can't pass method print in java

So, I have a class with the following main method:
public class Game {
public static void main(String[] args) {
JFrame frame = new JFrame("Ball Game");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 550);
frame.setLayout(null);
frame.setVisible(true);
}
}
and a class with the method print:
public class Ball {
public void print(Graphics g) {
g.fillOval(20, 20, 30, 30);
}
}
How can I pass the print method at the main class Game?
Sorry for my english, it isn't my first language.
If your class Ball is in another file you will have to import the class.
In your main, you need to instantiate the class Ball as follow:
Ball b = new Ball();
Which will call the default constructor of the class Ball or a constructor you defined.
Then you can call your function print by doing:
b.print(g);
Assuming that g is an instance of Graphics class.
You can make the print method static.
like this
public static void print(Graphics g){...}
Then call it like this Ball.print(g) (assuming that g is instance of Graphics)

paintComponents method not being called in Java

I watched a tutorial and tried to do same thing, I wrote the codes exactly the same but it shows nothing. I think it is because paintComponent method is not being called, I also tried to print something to console by paintComponent.
Here is my code:
public class Line extends JPanel{
#Override
public void paintComponents(Graphics g){
super.paintComponent(g);
g.setColor(Color.red);
g.drawLine(100, 10, 30, 40);
}
public static void main(String[] args) {
Line l =new Line();
JFrame myFrame = new JFrame("Line");
myFrame.setSize(600, 400);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.add(l);
myFrame.setVisible(true);
}
}
Thank you!
What you want to override is paintComponent, not paintComponents with a s .
paintComponents paints the child components of the current component (well it sort of tells the child components to paint themselves on the Graphics object).
paintComponent paints the component itself, this is the method you want to override to do custom painting for your component.

How to draw a roundedRectangle with text inside a class extending JPanel

I'm new with Java and I'm trying to a class that extends JPanel. I have a updateView() method that is suppose to draw rounded rectangles with text in the middle inside the JPanel. Also, I would need to stock the textfield and the rounded rectangle in a LinkedHashMap. I already got a var for this, I just don't know witch type of var I need to use.
I'have been searching the solution for a while, and all the answers I found are either to complicated for me to understand or just doesn't apply to my case.
I know that it's almost nothing, but here is what I got so far...
package game;
import javax.swing.JPanel;
public class GameNumView extends JPanel
{
private Map<Integer,Integer> backgroundText = new LinkedHashMap<"My rounded rectangle","My textfield">();
public GameNumView()
{
}
public void UpdateView(String[] pNumbers)
{
//Create the background
//Create the text
}
}
I'll give you the right path. It's up to you to adapt it to your existing code.
The idea is to use the Graphics object with the paintComponent method of an extended class of JPanel.
Here is the code, it is clear enough I think but if you have any question, do not hesitate.
The MyFrame class :
public class MyFrame extends JFrame {
public MyFrame(){
this.setTitle("Hello");
this.setSize(200, 200);
this.setLocationRelativeTo(null);
MyPanel pan = new MyPanel();
pan.setBackground(Color.ORANGE);
this.setContentPane(pan);
this.setVisible(true);
}
public static void main(String[] args) {
MyFrame f = new MyFrame();
}
}
And here is the MyPanel class :
public class MyPanel extends JPanel{
#Override
public void paintComponent(Graphics g) {
g.setColor(Color.black);
g.drawRoundRect(10, 10, this.getWidth()-20, this.getHeight()-20, 15, 15);
g.setColor(Color.black);
g.drawString("Hello", 75, 75);
}
}
And here is a picture of what you should have :

JPanel won't repaint when assigned a new subclass

I ran into a problem where no matter what I do my JPanel won't repaint. I was using the following method to create a connect four game board and dynamically change the color of the circles as the play progresses, but I've simplified it into a test class which has the same issue.
I decided to use a state pattern design for each of the circles. The following is the code for the classes so it knows which color to print which are JPanel children classes.
public class GridCircle extends JPanel
{
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.BLUE);
g.fillRect(0, 0, 100, 100);
}
}
public class WhiteGridCircle extends GridCircle
{
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.WHITE);
g.fillOval(5, 5, 80, 80);
}
}
public class RedGridCircle extends GridCircle
{
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.RED);
g.fillOval(5, 5, 80, 80);
}
}
The following is a test class where I attempt to change the class of a JPanel in the main method to see if it would change the color that is painted (which fails).
public class test extends JFrame
{
static JPanel testPanel = new WhiteGridCircle();
public static void main(String[] args)
{
new test();
testPanel = new RedGridCircle();
testPanel.revalidate();
testPanel.repaint();
}
test()
{
this.add(testPanel);
this.setSize(150,150);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
}
}
I can't figure out why the panel wouldn't repaint no matter what I've tried. From what I understand repaint() has no guarantee to call a the paint method but I see no reason it shouldn't when theres nothing else going on.
Because instance you created and added this.add(testPanel); is still new WhiteGridCircle().
You changed instance but the original one added to JFrame remains in the frame.
To change call this.getContentPane().add(testPanel); after instantiating RedGridCircle and before revalidate() call.

Why won't this render?

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

Categories