Drawing with AWT and components in Java - java

I'm currently making a game in Java with AWT. The main class extends Frame, and I've been using it to draw the graphics using .getGraphics() and .drawRect(). This has been working fine, except that when I add components like labels to the frame it stops rendering the graphics and only displays the components.

Don't
Use getGraphics() to paint. That is not the proper way.
Try and paint on top-level containers like JFrame
Instead
Paint on a JPanel or JComponent (I prefer the former)
Override the paintComponent(Graphics g) method of the JPanel. Do all your painting in this method, use the implicitly passed Graphics context. You never have to actually call paintComponent as it will be implicitly called for you.
See
Performing Custom Painting for more details on painting in Swing
Edit
Just noticed you are using AWT. You really should consider upgrading to Swing. Otherwise, instead of paintComponent, you're going to want to override paint, as AWT components don't have a paintComponent method. But I strongly urge you to use Swing
Example (Using Swing)
public class SimplePaint {
public SimplePaint() {
JFrame frame = new JFrame();
frame.add(new DrawPanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
class DrawPanel extends JPanel {
#Override
public Dimension getPreferredSize() {
return new Dimension(300, 300);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.fillRect(50, 50, 150, 150);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new SimplePaint();
}
});
}
}

Related

Repaint never reaches paintComponent();

I'm back with a problem about java-graphics by swing... I want to paint some stuff at a jframe, here is the code:
PaintUtil-class:
public class PaintUtil extends JPanel{
public PaintUtil(){
this.setFocusable(true);
this.requestFocus();
}
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
System.out.println("Repainted");
g.drawstuff...
}
}
Main-class:
public static PaintUtil util = new PaintUtil();
JFrame frame = new JFrame();
frame.setSize(500,600);
frame.setRezisable(false);
frame.add(util);
frame.setDefaultCloseOperation( 3 );
frame.getContentPane().setColor(Color.BLACK);
setup(); //This add some buttons
frame.setVisible(true);
util.repaint(); //not working
util.paintComponent(frame.getGraphics()); //works
Can you guys help me?
There is no error, no message in the console, just nothing
frame.setLayout(null);
Don't use a null layout. Swing was designed to be used with layout managers. Get rid of that statement.
By default the size of your panel is (0, 0) so there is nothing to paint.
You will need to override the getPreferredSize() method of your panel so the layout manager can do its job.
Read the section from the Swing tutorial on Custom Painting for more information and working examples.

Painting on a JPanel inside a JScrollPane doesn't paint in the right location

So I have a JPanel that's inside a JScrollPane.
Now I am trying to paint something on the panel, but it's always in same spot.
I can scroll in all directions but it's not moving. Whatever I paint on the panel does not get scrolled.
I already tried:
A custom JViewPort
switching between Opaque = true and Opaque = false
Also I considered overriding the paintComponent method of the panel but that would be really hard to implement in my code.
public class ScrollPanePaint{
public ScrollPanePaint() {
JFrame frame = new JFrame();
final JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(1000, 1000));
//I tried both true and false
panel.setOpaque(false);
JScrollPane scrollPane = new JScrollPane(panel);
frame.add(scrollPane);
frame.setSize(200, 200);
frame.setVisible(true);
//To redraw the drawing constantly because that wat is happening in my code aswell because
//I am creating an animation by constantly move an image by a little
new Thread(new Runnable(){
public void run(){
Graphics g = panel.getGraphics();
g.setColor(Color.blue);
while(true){
g.fillRect(64, 64, 3 * 64, 3 * 64);
panel.repaint();
}
}
}).start();
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new ScrollPanePaint();
}
});
}
}
The mistake I make is probably very easy to fix, but I just can't figure out how.
How to implement the paintComponent() on JPanel?
Override getPreferredSize() method instead of using setPreferredSize()
final JPanel panel = new JPanel(){
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
// your custom painting code here
}
#Override
public Dimension getPreferredSize() {
return new Dimension(40, 40);
}
};
Some points:
Override JComponent#getPreferredSize() instead of using setPreferredSize()
Read more Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?
Use Swing Timer instead of Java Timer that is more suitable for Swing application.
Read more How to Use Swing Timers
Set default look and feel using UIManager.setLookAndFeel()
Read more How to Set the Look and Feel
How to fix animation lags in Java?

Can't print any string using drawString() in JFrame

I'm trying to find what is wrong with this short code. I can't print the String TEXT in my JFrame using drawString() method. Please Help . Only a plain white screen will appear if you run the program .
Code:
import javax.swing.*;
import java.awt.*;
public class sample extends JFrame
{
private JPanel panel;
public sample()
{
setSize(500,500);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
panel =new JPanel();
Container mainP= getContentPane();
mainP.add(panel);
panel.setBounds(0,0,500,500);
panel.setBackground(Color.WHITE);
}
public void paintComponent(Graphics g)
{
Graphics2D eg = (Graphics2D)g;
eg.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
eg.setColor(Color.BLACK);
eg.drawString("TEXT", 40, 120);
}
public static void main(String args[])
{
new sample();
}
}
JFrame has no paintComponent method. So you aren't override anything, and not painting will be done.
On that note JPanel does have a paintComponent method, and you should be painting on a JComponent or JPanel, which do have the method. You don't want to paint on top-level containers like JFrame. (if you really need to know though, the correct method to override is paint for JFrame).
That being said, you should also call super.paintComponent inside the paintComponent method so you don't break the paint chain and leave paint artifacts.
Side Notes
As good practice, make use of the #Override annotation, so you know you are correctly overriding a method. You would've seen that paintComponent doesn't override one of JFrames methods.
setVisible(true) after add your components.
panel.setBounds(0,0,500,500); will do absolutely nothing, since the JFrame has a default BorderLayout
Follow Java naming convention and use capital letters for class names.
Run Swing apps from the Event Dispatch Thread. See more at Initial Threads
FINAL
import javax.swing.*;
import java.awt.*;
public class Sample extends JFrame {
private JPanel panel;
public Sample() {
setSize(500, 500);
setDefaultCloseOperation(EXIT_ON_CLOSE);
panel = new JPanel() {
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D eg = (Graphics2D) g;
eg.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
eg.setColor(Color.BLACK);
eg.drawString("TEXT", 40, 120);
}
};
Container mainP = getContentPane();
mainP.add(panel);
panel.setBackground(Color.WHITE);
setVisible(true);
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new Sample();
}
});
}
}

Java - GUI (swing) - Null Pointer Exception

I got 2 classes:
- 1st. makes a frame (JFrame) and adds a panel (JPanel) on it
- second one makes the panel and draws a rectangle on it (at least i thought it would)
this is the first class
class Frame {
JFrame frame;
Panel panel;
void draw() {
frame = new JFrame ("qwertz");
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.setSize(300,200);
panel = new Panel();
panel.setLayout(null);
panel.paint();
frame.add(panel);
}}
and the second
class Panel extends JPanel {
void paint() {
Graphics g = getGraphics();
g.drawRect(50,50,90,70);
}}
when i call the draw() method from the first class it throws this exception at me:
java.lang.NullPointerException
at Panel.paint(Panel.java:8) (( g.drawRect(50,50,90,70); ))
at Frame.draw(Frame.java:15) (( panel.paint(); ))
That's not how you're supposed to paint. To paint a component, override the paintComponent(Graphics g) method of the JPanel then call repaint();
class MyPanel extends JPanel {
#Override // <-- this makes a compiler error if you typod the method name
public void paintComponent(Graphics g) {
g.drawRect(50,50,90,70);
}
}
and
panel = new MyPanel();
panel.setLayout(null);
panel.repaint(); // <<---- Look here! It says repaint() not paint()
frame.add(panel);
Also, if all you have to do is paint on this panel, I'd consider using a plain-old Component, and overriding paint(Graphics g) instead of paintComponent(Graphics g). paintComponent(Graphics g) is exclusively for swing components.
instead of implementing the paint method, you should implement the paintComponent(Graphics g) method. This way, the graphics object you have is valid.
http://docs.oracle.com/javase/6/docs/api/javax/swing/JComponent.html#paintComponent(java.awt.Graphics)
You are trying to draw the panel before it is added to the Frame. Try to move frame.paint(); below frame.add(panel);. Additionally if you are using Swing you should use JPanel instead of Panel.

Graphics dont appear

Whatever I do, I can not display rectangle/line/oval on the screen. I checked other sources where they paint graphics, but when I even execute those codes, I don't get any graphics displayed on the windows. Below is the example from the text book.
import java.awt.*;
import javax.swing.*;
class PlotGraph
{
public static void main (String [] args) {
JFrame win;
Container contentPane;
Graphics g;
win = new JFrame("testing");
win.setSize(300,200);
win.setLocation(100,100);
win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
win.setVisible(true);
contentPane = win.getContentPane();
g = contentPane.getGraphics();
g.drawRect(10, 30, 50, 50);
}
}
Ouch. You should change your text book then. First of all, all the accesses to Swing components must be done in the event dispatch thread.
Second, you should not get the graphics of a component and paint on it. Instead, you should extend a JComponent or JPanel, override its paintComponent(Graphics) method, and paint using the Graphics object passed as argument (and which is in fact a Graphics2D instance).
That's not how graphics work in Swing.
You need to add a component to your frame, not just draw on it. You never want to draw directly on the frame. The reason why it's not doing anything is because your drawing code is being overridden.
If you want your component to have custom drawing code, make a subclass of JComponent and override the paintComponent(Graphics) method. An example of how you should do this is as follows:
import java.awt.*;
import javax.swing.*;
class PlotGraph {
public static void main(String[] args) {
JFrame win;
win = new JFrame("testing");
win.setSize(300, 200);
win.setLocation(100, 100);
win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
win.setVisible(true);
win.setContentPane(new MyComponent());
}
}
class MyComponent extends JComponent {
#Override
public void paintComponent(Graphics g) {
g.drawRect(10, 30, 50, 50);
}
}
I would highly encourage you to check out the Java GUI tutorial online.

Categories

Resources