I have no idea what I'm doing - Paint Methods, etc - java

I have been struggling with Paint methods, and paint components, and extends JFrame, and have been trying all sorts of ways to get a simple rectangle to draw. here is a class called Window:
import javax.swing.*;
import java.awt.Graphics;
public class Window extends JFrame
{
/**
*
*/
private static final long serialVersionUID = 1L;
Window()
{
setSize(300,300);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void paint(Graphics g)
{
g.drawRect(300,300,300,300);
}
}
then class Main
public class Main {
public static void main(String args[])
{
Window mainWindow = new Window();
mainWindow.setBounds(100,100,300,300);
}
}
The sole purpose of this program is just draw a damn rectangle. I have no idea what I could be doing wrong, and I have been trying to drawRect or drawString for several days now, to no avail. I also tried with a panel.

Don't override paint of top level containers like JFrame, this is the quickest way to end up with a world of weird and unexpected results.
Between the frames actual surface and the use, there is a JRootPane, a contentPane and possibly a glassPane...
All of these can interface/erase what you've painted in the paint method.
Instead, start with a JPanel and override it's paintComponent. Create an instance of this and place it on an instance of a JFrame when you want to show it.
Have a look at Painting in AWT and Swing and Performing Custom Painting for more details
Also, beware that when painting, 0x0 is the top/left of your component, so in your example, you start painting at 300x300, but your frame is only 300x300, so you're actually painting of the screen
As an example:
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestPaint {
public static void main(String[] args) {
new TestPaint();
}
public TestPaint() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new PaintPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class PaintPane extends JPanel {
public PaintPane() {
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.drawRect(10, 10, getWidth() - 20, getHeight() - 20);
g2d.dispose();
}
}
}

could you try this code
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main extends JPanel {
public static void main(String[] a) {
JFrame f = new JFrame();
f.setSize(400, 400);
f.add(new Main());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
public void paint(Graphics g) {
g.fillRect (5, 15, 50, 75);
}
}

Related

paintComponent() not being called

Here is a little program that should (in theory) draw an image of a ball on screen.
The problem is that paintComponent seems to not get called. The program consists of two classes.
import java.awt.*;
import java.io.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import javax.swing.*;
public class ScreenSaver extends JPanel {
private static final long serialVersionUID = 001;
public static void main(String[] args) {
new ScreenSaver();
}
public ScreenSaver() {
new Window(1600, 900, "ScreenSaver", this);
}
//----------------------------------------------------------------------------------
private static BufferedImage ball;
public static BufferedImage getBallSprite() {
try {
File pathToBall = new File("ball.png");
ball = ImageIO.read(pathToBall);
} catch (IOException ex) {
ex.printStackTrace();
}
return ball;
}
}
import java.awt.*;
import java.io.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import javax.swing.*;
public class Window extends Canvas {
private static final long serialVersionUID = 002;
public Window(int width, int height, String title, ScreenSaver ScreenSaver) {
JFrame frame = new JFrame(title);
frame.setPreferredSize(new Dimension(width, height));
frame.setMaximumSize(new Dimension(width, height));
frame.setMinimumSize(new Dimension(width, height));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
repaint();
}
public void paintComponent(Graphics g) {
System.out.println("Painting...");
BufferedImage ball = ScreenSaver.getBallSprite();
g.drawImage(ball, 0, 0, 100, 100, this);
}
}
As you can see, I tested if paintComponent was called using a console message. Sadly this was not the case. Can someone explain?
java.awt.Canvas does not inherit from JComponent so paintComponent won't be called automatically. You can create a new custom window instead to create a Swing-centric component
public class MyWindow extends JComponent {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
...
}
It's no wonder that paintComponent is not called, because Canvas has no implementation of paintComponent which you can override. With a canvas you have to overwrite paint for your purposes. In your code you use both a JPanel and a Canvas, which is not necessary at all. Use either of the two.
The following is an example with a Canvas:
import java.awt.*;
import javax.swing.*;
public class ScreenSaver extends Canvas{
public static void main(String[] args) {
JFrame window = new JFrame("Screensaver");
window.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
window.setResizable(false);
ScreenSaver canvas = new ScreenSaver();
canvas.setPreferredSize(new Dimension(1600, 900));
canvas.setBackground(Color.BLACK);
window.add(canvas);
window.pack();
window.setLocationRelativeTo(null);
window.setVisible(true);
}
#Override
public void paint(Graphics g){
g.setColor(Color.GREEN);
g.fillOval(100, 100, 100, 100);
}
}
The annotation Override above the method to be overwritten ensures that the compiler can issue a warning message if the overwritten method does not exist or there is a typo. I hope this helps you further.

Java questions about coordinates with Graphics

If I create a JFrame 800x600 pixels and draw a line from (0,0) to (800,600) it doesn't go from corner to corner, so, where is the (0,0) and where is the (800,600)?
Here is the code
import java.awt.Graphics;
import javax.swing.JFrame;
public class Point0_0test extends JFrame {
public Point0_0test() {
setTitle("Test");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(800, 600);
setLocationRelativeTo(null);
}
#Override
public void paint(Graphics g) {
super.paint(g);
g.drawLine(0, 0, 800, 600);
}
public static void main(String[] args) {
Point0_0test test = new Point0_0test();
test.setVisible(true);
}
}
Here you can see what appears when the program is running
If you want a drawing area that's 800 x 600 pixels, then set a drawing area that's 800 x 600 pixels. Who cares how big the frame is?
Here's a simple drawing GUI that I created. I made it 400 x 300 pixels so it would fit in the answer easier.
Here's the code. It's a minimal, runnable example for setting the size of the drawing area.
import java.awt.BasicStroke;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class SimpleDrawingArea implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new SimpleDrawingArea());
}
#Override
public void run() {
JFrame frame = new JFrame("Simple Drawing Panel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new DrawingPanel());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public class DrawingPanel extends JPanel {
private static final long serialVersionUID = 1L;
public DrawingPanel() {
this.setPreferredSize(new Dimension(400, 300));
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setStroke(new BasicStroke(4f));
g2d.drawLine(0, 0, 400, 300);
}
}
}
The JFrame size and coordinates count the size of the decorations, such as the top part of the window contains the bar with the close button, the rest contain the extra outline that is added on Windows(Ubuntu, at least, doesn't seem to add an extra outline). In order to get a line like you would want to, you should use JFrame.getInsets(), which returns the size of the GUI that decorates the JFrame, like this:
import java.awt.Insets;
#Override
public void paint(Graphics g) {
super.paint(g);
Insets in = getInsets();
g.drawLine(in.left, in.top, 800-in.right, 600-in.bottom);
}
Edit: this means that you don't have an actual 800x600 space. The Insets class seems to be "created" when setVisible(true) is called, as far as I can tell. So this would be how the code for that looks like:
import javax.swing.JFrame;
import java.awt.Insets;
import java.awt.Graphics;
public class InsetsTest extends JFrame {
public InsetsTest() {
super();
setTitle("Test");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(800,600);
setVisible(true);
Insets insets= getInsets();
setSize(800+insets.right+insets.left,600+insets.top+insets.bottom);
setLocationRelativeTo(null);
}
#Override
public void paint(Graphics g) {
super.paint(g);
Insets in = getInsets();
g.drawLine(in.left, in.top, 800+in.left, 600+in.top);
}
public static void main(String[] args) {
InsetsTest test = new InsetsTest();
test.setVisible(true);
}
}```
The window size should be defined without OS specific window decoration.
Try to add
this.setUndecorated(true);
before the
this.setVisible(true);

Why is graphics not showing on my JFrame / JPanel?

When I run this code. The result is a window with the name. Fully blank. I tried editing background color and adding graphics (rectangle) etc but the same result keeps occurring .
Question: This ends up as a white screen on a window. No graphics or background color. Even though I added it to panel and added panel. How do I fix this?
Main.java
package ball.tec.main;
import javax.swing.JFrame;
import ball.tec.frame.Frame;
public class Main {
public static void main(String[] args) {
String Version = "0.1.2";
Frame f = new Frame();
f.setVisible(true);
f.add();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setResizable(false);
f.setSize(1500, 1000);
f.setTitle("RedBall V: " + Version);
}
}
Frame.java
package ball.tec.frame;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Frame extends JFrame{
private static final long serialVersionUID = 1L;
public boolean debug = false;
//Creating panel object
JPanel panel = new JPanel();
//Graphics displayed
public void paintComponent(Graphics g) {
//Firstly Nothing pops up
g.setColor(Color.RED);
g.drawRect(20, 40, 10, 10);
//And this doesn't work.
this.setBackground(Color.RED);
}
//Add everything to 'panel'
public void add() {
add(panel);
//Even if I put it here it doesn't work ;-;
this.setBackground(Color.RED);
this.pack();
}
}
You don't use paintComponent() in a JFrame. What you probably intended to do was create a third class, extending JPanel. Add your paintComponent() there.
public class MyPanel extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.RED);
g.drawRect(20, 40, 10, 10);
this.setBackground(Color.RED);
}
}
f.add(new MyPanel());

Java Swing: Transparent PNG permanently captures original background

I have the following code:
import javax.swing.JWindow;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
public class sutff extends JWindow
{
//Get transparent image that will be use as splash screen image.
Image bi=Toolkit.getDefaultToolkit().getImage("window.png");
ImageIcon ii=new ImageIcon(bi);
public sutff()
{
try
{
setSize(ii.getIconWidth(),ii.getIconHeight());
setLocationRelativeTo(null);
show();
//Thread.sleep(10000);
//dispose();
//JOptionPane.showMessageDialog(null,"This program will exit !!!","<>",JOptionPane.INFORMATION_MESSAGE);
}
catch(Exception exception)
{
exception.printStackTrace();
}
}
//Paint transparent image onto JWindow
public void paint(Graphics g)
{
g.drawImage(bi,0,0,this);
}
public static void main(String[]args)
{
sutff tss=new sutff();
}
}
The purpose is to create a window that is translucent and resembles Windows Aero-style glass. I have the following transparent png that I am using:
http://i.imgur.com/5UNGbsr.png
The problem is that since its transparent, its suppose to show the things behind the window, right? That's what it does when first executed, except whatever window is behind this "transparent window" when it first starts up, the program somehow creates an "image" of that and permanently attaches it with the window. So even if I minimize the windows behind this "transparent window," the image of the first background window remains.
Here is a screenshot:
When I took this screen shot, I had already minimized the command prompt and the IDE which can be seen in the background, yet it still remains in the background of the window.
What am I doing wrong?
Don't override the paint() method of a top level container, especially when you don't invoke super.paint(). This will cause painting problems. If you ever do need to do custom painting then you should override the paintComponent() method of JPanel (or JComponent) and then add the panel to the window/frame. Read the Swing tutorial on Custom Painting. This advice is given daily, I don't know why people still try to override paint()???
However this is only one of your problems. The better solution is to add your image to a JLabel and then add the label to the window. You will also need to make the window background transparent:
import javax.swing.*;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import java.awt.*;
import java.awt.Image;
import java.awt.Toolkit;
public class Stuff extends JWindow
{
//Get transparent image that will be use as splash screen image.
Image bi=Toolkit.getDefaultToolkit().getImage("transparent.png");
ImageIcon ii=new ImageIcon(bi);
public Stuff()
{
try
{
setBackground( new Color(0, 0, 0, 0) );
setSize(ii.getIconWidth(),ii.getIconHeight());
setLocationRelativeTo(null);
JLabel label = new JLabel(ii);
add(label);
show();
//Thread.sleep(10000);
//dispose();
//JOptionPane.showMessageDialog(null,"This program will exit !!!","<>",JOptionPane.INFORMATION_MESSAGE);
}
catch(Exception exception)
{
exception.printStackTrace();
}
}
/*
//Paint transparent image onto JWindow
public void paint(Graphics g)
{
super.paint(g);
g.drawImage(bi,0,0,this);
}
*/
public static void main(String[]args)
{
Stuff tss=new Stuff();
}
}
The problem is, you window is actually transparent. Java still thinks that the Window opaque and therefore won't update the graphics in such away as to show what's actually behind.
Creating a transparent window is relatively simple in Java since Java 1.6.10 (I think)
The following is a very simple example, using a semi transparent paint effect that will allow what ever falls below the window to continue to be painted correctly.
import com.sun.awt.AWTUtilities;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.RoundRectangle2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TransaprentBlur {
public static void main(String[] args) {
new TransaprentBlur();
}
public TransaprentBlur() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setUndecorated(true);
frame.setBackground(new Color(0, 0, 0, 0));
// Java 6...
// AWTUtilities.setWindowOpaque(frame, true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setOpaque(false);
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
System.exit(0);
}
}
});
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Shape shape = new RoundRectangle2D.Float(0, 0, getWidth() - 1, getHeight() - 1, 20, 20);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(new Color(225, 225, 225, 128));
g2d.fill(shape);
g2d.setColor(Color.GRAY);
g2d.draw(shape);
g2d.dispose();
}
}
}
Update with image example
Screen shoots showing windows been moved behind the window...
Basically, all you need to do, is place you image rendering code with in the paintComponent method of TestPane
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TransaprentBlur {
public static void main(String[] args) {
new TransaprentBlur();
}
public TransaprentBlur() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setUndecorated(true);
frame.setBackground(new Color(0, 0, 0, 0));
// Java 6...
// AWTUtilities.setWindowOpaque(frame, true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private BufferedImage image;
public TestPane() {
try {
image = ImageIO.read(getClass().getResource("/5UNGbsr.png"));
} catch (IOException ex) {
}
setOpaque(false);
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
System.exit(0);
}
}
});
}
#Override
public Dimension getPreferredSize() {
return image == null ? super.getPreferredSize() : new Dimension(image.getWidth(), image.getHeight());
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (image != null) {
Graphics2D g2d = (Graphics2D) g.create();
int x = (getWidth() - image.getWidth()) / 2;
int y = (getHeight() - image.getHeight()) / 2;
g2d.drawImage(image, x, y, this);
g2d.dispose();
}
}
}
}

paint method draws outside jFrame if first coord 0,0

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 :)

Categories