I don't understand why my code isn't working, trying to print a rectangle in my JFrame, but keep ending up with an error on f.add(p);.
import javax.swing.*;
import java.awt.*;
public class SPEL{
public void paintComponent(Graphics g){
g.drawRect(50,75,100,50);
}
public static void main(String[] args) {
JFrame f = new JFrame();
f.setSize(400, 300);
f.setLocation(100,100);
f.setTitle("SPEL");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
SPEL p = new SPEL();
f.add(p);//error
f.setVisible(true);
}
}
You forgot to extends something, for example:
public class SPEL extends JPanel {
You can add #Override to reduce the chance of this kind of mistake
#Override
public void paintComponent(Graphics g){
try this! :
import javax.swing.*;
import java.awt.*;
#SuppressWarnings("serial")
public class SPEL extends JPanel {
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setPaint(Color.red);
Rectangle b = new Rectangle(50, 75, 100, 50);
g2d.draw(b);
g2d.fill(b);
}
public static void main(String[] args) {
JFrame f = new JFrame();
f.setSize(400, 300);
f.setLocation(100, 100);
f.setTitle("SPEL");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
SPEL p = new SPEL();
f.add(p);
f.setVisible(true);
}
}
extends JPanle
#Override
Using Graphics2D
g2d.fill(Shape s)
Related
so i'm trying to put Rectangle2D.Float in window using JFrame but when i'm compiling code i'm getting just blank window without rectangle. Can you guys take look on it and tell me what i'm doing wrong?
package zestaw8;
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
class Plansza85 extends JPanel
{
Shape figura;
Plansza85(Shape figura)
{
this.figura=figura;
}
}
public class Zestaw8_cw85
{
public static void main(String[] args)
{
Shape obj1;
obj1=new Rectangle2D.Float(100,100,140,140);
zestaw8.Plansza85 p;
p=new zestaw8.Plansza85(obj1);
JFrame jf=new JFrame();
jf.setTitle("Plansza p");
jf.setSize(400,400);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true);
jf.add(p);
}
}
You seem to have a misunderstanding of how painting works in Swing.
Start by looking at Performing Custom Painting, Painting in Swing and 2D Graphics. Rectangle2D is a graphics primitive, which needs to be painted through the normal custom painting process
As per the common recommendations of Performing Custom Painting you should override the paintComponent method of the Plansza85 and paint the Shape through the Graphics2D API, something like...
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.geom.Rectangle2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
Shape obj1;
obj1 = new Rectangle2D.Float(100, 100, 140, 140);
Plansza85 p;
p = new Plansza85(obj1);
JFrame jf = new JFrame();
jf.setTitle("Plansza p");
jf.add(p);
jf.pack();
jf.setLocationRelativeTo(null);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true);
}
});
}
class Plansza85 extends JPanel {
Shape figura;
Plansza85(Shape figura) {
this.figura = figura;
}
#Override
public Dimension getPreferredSize() {
if (figura == null) {
return super.getPreferredSize();
}
Rectangle2D bounds = figura.getBounds2D();
double width = bounds.getMaxX();
double height = bounds.getMaxY();
return new Dimension((int)width + 1, (int)height + 1);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(getForeground());
g2d.draw(figura);
g2d.dispose();
}
}
}
for example.
I've also overridden the getPreferredSize method to generate an appropriate sizing hint for the component based on the size of the shape, I've done this because I dislike guess work and the window also includes variable sized borders and title bars which will change the size the panel if you only rely on setSize
You need to override the paintComponent method of Plansza85
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
class Plansza85 extends JPanel {
private Shape figura;
Plansza85(Shape figura) {
this.figura = figura;
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.draw(figura);
}
}
public class Zestaw8_cw85 {
public static void main(String[] args) {
Shape obj1;
obj1 = new Rectangle2D.Float(100, 100, 140, 140);
Plansza85 p;
p = new Plansza85(obj1);
JFrame jf = new JFrame();
jf.setTitle("Plansza p");
jf.setSize(400, 400);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.add(p);
jf.setVisible(true);
}
}
Hope it helps!
I have the following java programm:
import java.awt.*;
import java.awt.Graphics;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
public class Lapex extends JPanel implements MouseListener{
JPanel p = new JPanel();
Lapex(){
JFrame f = new JFrame();
p.addMouseListener(this);
p.setPreferredSize(new Dimension(600, 600));
f.add(p);
f.pack();
f.show(true);
}
public void paint(Graphics g){
paintComponents(g);
g.setColor(Color.RED);
g.drawLine(10, 10, 100, 100);
}
public void mouseClicked(MouseEvent me){
System.out.println("AAAA");
repaint();
}
}
public static void main(String[] args){
new Lapex();
}
}
Clicking the mouse, at the console is displayied "AAAAA", but draws no line.(I deleted the other mouse event)
How to modify ?
You have to call the super method and use paintComponent.
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.RED);
g.drawLine(10, 10, 100, 100);
}
A few things to note:
Your class extends JPanel, but then you create another JPanel inside the class that you actually add to the frame. Add the instance of your class instead.
Override paintComponent instead of paint.
Use a call to invokeLater to start your program on the EDT. See Event Dispatch Thread for more info.
Override getPreferredSize rather than call setPreferredSize.
Here is a complete example that toggles the line on/off when the mouse button is clicked:
import java.awt.*;
import java.awt.Graphics;
import javax.swing.*;
import java.awt.event.*;
public class Lapex extends JPanel {
boolean drawLine = false;
Lapex(){
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent me){
drawLine = !drawLine;
repaint();
}
});
f.add(this);
f.pack();
f.setVisible(true);
}
#Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
if(drawLine) {
g.setColor(Color.RED);
g.drawLine(10, 10, 100, 100);
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(600, 600);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run()
{
new Lapex();
}});
}
}
No!, don't override paint() leave this up to Swing itself. All you should do is override paintComponent().
My problem is that when i use
public void paint(Graphics g)
{}
Method to draw a String as
g.drawString("hello java",0,0);
My full code is
import javax.swing.*;
import java.awt.*;
class test
extends JFrame
{
public void testing()
{
setSize(500,500);
show();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void paint(Graphics g)
{ super.paint(g);
g.drawString("HELLO JAVA");
}
public static void main(String arg[])
{
test t=new test();
t.testing();
} }
In JFrame i am getting a black screen without hello java being drawn
Please help me
Thanks in advance
To display the inherited frame correctly, the paint method in the inherited class should contain the call of super.paint():
class MyFrame extends JFrame {
public void paint(Graphics g) {
super.paint(g);
g.drawString("hello java", 50, 50);
}
}
EDIT (painting in the panel):
import java.awt.*;
import javax.swing.*;
public class CustomPaint {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame("CustomPaint");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new MyPanel());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
});
}
}
class MyPanel extends JPanel {
public Dimension getPreferredSize() {
return new Dimension(320, 240);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
String msg = "HELLO JAVA";
g2.setPaint(Color.BLUE);
int w = (getWidth() - g.getFontMetrics().stringWidth(msg)) / 2;
g2.drawString(msg, w, getHeight() / 2);
}
}
I tried to implement a simple GUI application,having a class extend JPanel and then adding it to a frame and adding a button,but nothing happens when I click on the button.What is wrong?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class dup extends JPanel {
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.green);
g2d.fillRect(0, 0, this.WIDTH, this.HEIGHT);
System.out.println("inside paint component class");
}
}
public class drawing implements ActionListener {
JFrame frame;
dup d1;
public static void main(String args[]) {
drawing d2 = new drawing();
d2.go();
}
public void go() {
frame = new JFrame();
JButton button = new JButton("click me");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
d1 = new dup();
button.addActionListener(this);
frame.getContentPane().add(BorderLayout.WEST, button);
frame.getContentPane().add(BorderLayout.CENTER, d1);
frame.setSize(300, 300);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
frame.repaint();
}
}
What is wrong with this?
Width and height is wrong. It should be
g2d.fillRect(0, 0, this.getWidth(), this.getHeight());
You were using constants from ImageObserver class instead of width and height properties of the component.
First coord in this case should be 0,0 and not 8,30. What am i doing wrong(i am using NetBeans)
import java.awt.Color;
import java.awt.Graphics;
public class TEST extends javax.swing.JFrame {
#Override
public void paint(Graphics g){
super.paint(g);
g.setColor(Color.blue);
g.drawRect(8, 30, 200, 200);
repaint();
}}
Add a JPanel to the frame and paint in that. The frame's coordinates include the decorations (title bar, borders, etc.). It would look something like this:
public class Test extends JFrame {
public static void main(String[] args) {
new Test();
}
private Test() {
add(new MyPanel());
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(600, 600);
setVisible(true);
}
private class MyPanel extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.blue);
g.drawRect(8, 30, 200, 200);
}
}
}
Also, don't call repaint(); in paint();. That will cause an infinite loop and will freeze the entire program.
The problem is your paint(..) method is not taking into account the JFrame Insets by calling getInsets which as docs state:
If a border has been set on this component, returns the border's
insets.
this code works fine:
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class Test {
public Test() {
createAndShowGui();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Test();
}
});
}
private void createAndShowGui() {
JFrame frame = new JFrame() {
#Override
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.blue);
g.drawRect(0 + getInsets().left, 0 + getInsets().top, 200, 200);
}
};
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
however this is not best practice.
Rather add JPanel to JFrame and override paintComponent(Graphics g) of JPanel dont forget call to super.paintComponent(g) as first call in the overridden method and than draw there (dont forget to override getPreferredSize() and return correct Dimensions so the JPanel will fit its drawing/graphic content) this problem will no longer persist as JPanel is added at correct co-ordinates on contentPane like so:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Test {
public Test() {
createAndShowGui();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Test();
}
});
}
private void createAndShowGui() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel() {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
g2d.setColor(Color.blue);
g2d.drawRect(0, 0, 200, 200);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(300, 300);
}
};
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
}
The above includes Graphics2D and RenderingHints i.e anti-aliasing. Just for some better looking drawings :)