(I've seen the other 2 questions that are similar to mine in title, but they are different and do not provide a solution to my problem.)
Hi,
I have the below code of simple display of lines. I'm declaring a JFrame in the main, then calling on a new instance of the DrawGraph1 class, passing the JFrame as argument.
In the constructor, I'm invoking a thread (EventQueue.invokeLater). The constructor use the JFrame and use it to create some lines and string and whatever)
(Sorry about improper indentation, it has been tweaked a lot)
package test;
import java.awt.*;
import java.awt.geom.*;
import java.text.DateFormatSymbols;
import javax.swing.*;
public class test {
public static void main(String[] args){
final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 700);
frame.setVisible(true);
DrawGraph1 obj = new DrawGraph1(frame);
}
}
class DrawGraph1{
DrawGraph1(final JFrame frame){
EventQueue.invokeLater(new Runnable(){
#Override
public void run(){
frame.setTitle("LineDrawing");
frame.add(new JComponent()
{
#Override
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
Line2D line = new Line2D.Double();
int decrement = 0, label = 0;
g2.setColor(Color.red);
g.drawString("Red Line ->> High temperatures", 330, 110);
g2.setColor(Color.green);
g.drawString("Green Line ->> Low temperatures", 330, 130);
} });}});}}
So According to my testing, the program reaches the constructor, passes the frame, and starts the thread, but apparently it stops at the line
frame.add(new JComponent()
With the NetBeans debugger underlining (or something) the add method. I also tried in which I invoke the thread at the main, pass the JFrame to the constructor, jump to it and it also stops at the same statement.
The display is simply the Frame itself with whatever settings prior to the add statement (i.e. in the main settings such as size).
I'm pretty sure it is very silly problem since it worked yesterday, not sure what I changed, but I just gave up.
I just changed the order of these two lines.
frame.setVisible(true);
DrawGraph1 obj = new DrawGraph1(frame);
to
DrawGraph1 obj = new DrawGraph1(frame);
frame.setVisible(true);
and the output:
Primarily, you passed the JFrame to the JPanel. You should create the JPanel, and pass it to the JFrame.
Here are the major changes I made.
All of the Swing GUI creation has to be on the Event Dispatch Thread. This includes the JFrame and the JPanel. I added a Runnable to the main method, and called the EventQueue invokeLater method to start the Swing GUI on the Event Dispatch Thread.
I moved all the JFrame code in the main method, and all of the JPanel drawing code in the DrawGraph1 class paintComponent method. The paintComponent method is for painting only. Do your other processing in other classes and / or other methods.
The JFrame methods have to be called in a specific order. Call the JFrame methods in the same order that I called them in your code.
I added a call to super.paintComponent to your paintComponent method. This maintains the Swing paint chain and clears the drawing panel.
I moved the sizing of the GUI from the JFrame to the JPanel. You're concerned with the size of the drawing panel, not the entire GUI.
Here's the revised code. I renamed the class so that it wouldn't conflict with other code in my testing package. You should change it back.
package com.ggl.testing;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Line2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class SimpleJPanelTest {
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
final JFrame frame = new JFrame("Line Drawing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new DrawGraph1());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
};
EventQueue.invokeLater(runnable);
}
}
class DrawGraph1 extends JPanel {
private static final long serialVersionUID = 6733473371292195071L;
public DrawGraph1() {
setPreferredSize(new Dimension(800, 700));
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
Line2D line = new Line2D.Double();
int decrement = 0, label = 0;
g2.setColor(Color.red);
g.drawString("Red Line ->> High temperatures", 330, 110);
g2.setColor(Color.green);
g.drawString("Green Line ->> Low temperatures", 330, 130);
}
}
Related
I have issue with drawing shapes inside of JPanel that I already added using Netbeans GUI. Now, I have no idea where to add code for drawing a circle inside of that JPanel and how to insert and call it in the JPanel that is sitting empty now, waiting for this shape to be drawn. I already set up destination JPanel to be Flow layout.
Netbeans Designer created a big class in which I have entire frame with this JPanel, and I want to keep it inside of it as I can't really add it any other way because Designer doesn't let me change main initComponents method in which all components are sitting now. I have been reading tutorials and previous posts but noone really encountered this using Netbeans Designer.
SO can someone just help me with adding proper method in this frame class and how to call it from JPanel I want to draw in. JPanel is 50x50 pixels.
So as per #Abra, I changed some code:
so I made a new Circle Class, adjusted it a bit as I don't want to create a new frame but put this in JPanel.
public class Circle extends JPanel {
Color color;
public void circle(Color color) {
this.color = color;
setPreferredSize(new Dimension (30,30));
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawOval(0, 0, r, r);
g.setColor(color);
}
private void showGUI() {
JPanel panel = new JPanel();
panel.add(this, FlowLayout.CENTER);
panel.setVisible(true);
}
}
Then I opened JPanel in Designer, and added code to run it, in initComponents method like this:
circlePanel.setPreferredSize(new java.awt.Dimension(40, 40));
new Circle().showGUI();
PanelDS.add(circlePanel);
circlePanel is destination for this drawing and is inside PanelDS itself. It doesn't work this way tho, but Netbeans shows no errors in code. Additionally, how can I forward color to circle class.
In order to draw on a JPanel you need to override the paintComponent() method of JPanel. In order to override the method, you need to create a class that extends JPanel. I don't think that there exists a GUI designer that can generate the required code for you. So you have to write the code of the class that extends JPanel.
Here is a minimal example. It displays a blue circle.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
public class Drawing2 extends JPanel {
private JFrame frame;
public Drawing2() {
setPreferredSize(new Dimension(100, 100));
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLUE);
g.fillOval(25, 25, 50, 50);
}
private void showGui() {
frame = new JFrame("Drawing");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(this, BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
new Drawing2().showGui();
}
}
Here's what you should see when you run the above code.
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
class game extends JFrame {
public game(){ //this is constructor
JFrame frame = new JFrame();
frame.setVisible(true);
frame.setSize(500,500);
frame.setTitle("Hello world");
}
public void paint(Graphics g){
Graphics2D g2 = (Graphics2D) g;
Line2D line = new Line2D.Double(60,90,150,100);
g2.draw(line);
}
public static void main(String args[]) {
game l = new game();
}
}
The above code is compiling in java but on running the code it only displays the frame and its title, but does not include any of the lines being drawn using the Graphics2D and Line2D, what is the mistake that is being made??? The frame being displayed does not show any content, why is that???
First, you are creating and displaying a JFrame which is not an instance of game, so there is no chance that it paints what you have in the paint method of game .
You usually don't want to create a subclass of JFrame for custom painting anyway, just create a subclass of JPanel, and set it as the content pane of the frame.
Also don't override paint, but paintComponent, which is the method responsible for painting the current component.
You should also call the parent method of paintComponent, to make sure that all the usual cleaning takes place correctly.
Also by convention, class names should start with an upper case letter.
One last thing, make the frame visible only once you have added all your components, or you may encounter visual glitches some day.
Putting it all together :
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Line2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
class Game extends JPanel {
#Override
public void paintComponent(final Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.BLACK);
Line2D line = new Line2D.Double(60, 90, 150, 100);
g2.draw(line);
}
public static void main(final String args[]) {
Game l = new Game();
JFrame frame = new JFrame();
frame.setSize(500, 500);
frame.setTitle("Hello world");
frame.setContentPane(l);
frame.setVisible(true);
}
}
In your constructor call method of JFrame class using this keyword because you extends JFrame class in your class.
public game(){ //this is constructor
/*JFrame frame = new JFrame();
frame.setVisible(true);
frame.setSize(500,500);
frame.setTitle("Hello world");*/
this.setVisible(true);
this.setSize(500,500);
this.setTitle("Hello world");
}
This solve your problem.
you dont need to create instance of JFrame class ,
modified you constructor as shown below
public game(){ //this is constructor
setVisible(true);
setSize(500,500);
setTitle("Hello world");
}
I've tried to research how Java's 2D rendering works, but I could never understand it. Here is the code in my main class:
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main{
public static void main(String args[]) {
JFrame frame = new JFrame();
frame.setSize(new Dimension(500,500));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("JFrame testing");
frame.setVisible(true);
Frame panel = new Frame();
frame.add(panel);
}
}
And then here is for the JPanel class:
import java.awt.Graphics;
import javax.swing.JPanel;
public class Frame extends JPanel{
private static final long serialVersionUID = 1L;
public Frame() {
Graphics g = this.getGraphics();
g.drawRect(0, 0, 100, 100);
this.paintComponent(g);
}
}
I am also getting this exception, but I'm not sure what it means:
Exception in thread "main" java.lang.NullPointerException
at Frame.<init>(Frame.java:10)
at Main.main(Main.java:18)
I'm basically just trying to draw a rectangle onto a panel to be shown on the frame I've created. I've heard about the paintComponent method, but I also don't fully understand that.
You should Never use getGraphics() of a Component.
Try below code
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawRect(0, 0, 100, 100);
//this.paintComponent(g);
}
Edit
"why is super.paintComponent(g); called again inside the method?"
The documentation of paintComponent says it pretty well:
if you do not invoker super's implementation you must honor the opaque
property, that is if this component is opaque, you must completely
fill in the background in a non-opaque color. If you do not honor the
opaque property you will likely see visual artifacts.
Why doesn't JPanel (panel) get drawn on the green background (the jpanel)? I want to be able to do this without extending j panel to...
Furthermore, for java games should i use keybindings or keylistener in java.
import javax.swing.*;
import java.awt.event.*;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
public class Game {
JFrame window;
JPanel panel;
int charPosX = 0;
int charPosY = 0;
public Boolean createGui() {
window = new JFrame("Game");
window.setSize(1000,500);
window.setResizable(false);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
panel = new JPanel();
panel.setVisible(true);
panel.setLayout(null);;
panel.setBackground(new Color(65,130,92));
window.add(panel);
return true; //returns true if ran and will be ran by check status in Main.
}
public void paintComponent(Graphics g) {
panel.paintComponents(g);
g.setColor(Color.RED);
g.drawRect(100,10,30,40);
g.fillRect(10, 10, 20, 10);
}
}
Let's take your code for a second and add #Override to your paintComponent method...
public class Game {
//...
#Override
public void paintComponent(Graphics g) {
panel.paintComponents(g);
g.setColor(Color.RED);
g.drawRect(100, 10, 30, 40);
g.fillRect(10, 10, 20, 10);
}
}
And now we have a compiler error! This is because Game extends Object and does not have a paintComponent method. This means that there is no way that the method could be called by any part of the existing painting system, so, it never gets called.
Components make poor "game" entities, they have a lot of "plumbing" which doesn't make them very efficient for this kind of work, you're generally better off heading down a complete custom painting route
import javax.swing.*;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
public class Game {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Game().createGui();
}
});
}
JFrame window;
GamePanel panel;
int charPosX = 0;
int charPosY = 0;
public Boolean createGui() {
window = new JFrame("Game");
window.setSize(1000, 500);
window.setResizable(false);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new GamePanel();
panel.setBackground(new Color(65, 130, 92));
window.add(panel);
window.setVisible(true);
return true; //returns true if ran and will be ran by check status in Main.
}
public class GamePanel extends JPanel {
private Rectangle entity = new Rectangle(100, 10, 30, 40);
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(Color.RED);
g2d.draw(entity);
g2d.setColor(Color.BLUE);
g2d.fill(entity);
g2d.dispose();
}
}
}
Also note, I called window.setVisible(true); only after I had added the panel to the window, this is because Swing is lazy when it comes to adding/removing components. If you want to add/remove components after the UI has been realized on the screen, you'll need to call revalidate and repaint on the container to trigger a layout and paint pass
Also, beware, there is a difference between paintComponent and paintComponents ;)
I would highly recommend having a look at Painting in AWT Swing and Performing Custom Painting to gain a better understanding of how painting works in Swing and how you can take advantage of it
So if I use this code, I get a screen with nothing. I should display a green rectangle. Had this problem previously but couldn't solve it.
package _47b3n.squaregen;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import javax.swing.JFrame;
public class Main extends Component {
private static final long serialVersionUID = 5547487570978675247L;
public static void main(String [] args) {
new Main();
}
public Main() {
JFrame frame = new JFrame();
frame.setSize(200, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setVisible(true);
repaint();
}
public void render(Graphics g) {
g.setColor(Color.GREEN);
g.drawRect(10,10,10,10);
}
}
Custom painting is done by overriding the paintComponent() method of a JPanel and then you add the panel to the frame.
Read the section from the Swing tutorial on Custom Painting for more information and working examples.