Paint Component Method not working for JFrame - java

I'm trying to paint an image on the screen after trying to use JLabel's and am now trying the paintComponent method. I tried inserting breakpoints after seeing no results and the method doesn't get called, and nothing appears. What should I do? Here is my important code-
`
public void createWindow(){
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setSize(xSize, ySize);
frame.setLocation(0, 0);
frame.addComponentListener(this);
//frame.add(im);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(placeholder, 0, 0, getWidth(), getHeight(), null);
g.drawString("Hello", 100, 100);
}
Also I'm using a JFrame instead of JPanel or component if that makes a difference.

JFrame does not have a paintComponent method. You should avoid painting directly to a frame and instead use a JPanel and override its paintComponent method
You should also make use of the #Override annotation, which will raise a compiler exception if the parent class does not have the method you are trying to override...

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.

Drawing with AWT and components in 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();
}
});
}
}

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.

Scrolls not appears

I want add JScrolpane to JPanel, but that not appears. In JLabel works fine and its very easy. I am using JPanel beacuse I'll add some image proccessing stuff to my program. There is my code:
public void draw(){
panel=new JPanel(){
protected void paintComponent(Graphics g){
Graphics g2 = g.create();
g2.drawImage(image, 0, 0, this);
g2.dispose();
}
};
panel.setBorder(BorderFactory.createEtchedBorder());
panel.setPreferredSize(new Dimension(400, 330));
s=new JScrollPane(panel);
s.setPreferredSize(new Dimension(400,285));
this.getContentPane().add(s,BorderLayout.CENTER);
add(panel);
revalidate();
repaint();
}
s=new JScrollPane(panel);
s.setPreferredSize(new Dimension(400,285));
this.getContentPane().add(s,BorderLayout.CENTER);
add(panel); // ****** ????????????
revalidate();
repaint();
}
You're adding the JPanel to the GUI not the JScrollPane, so you really shouldn't expect to see any scrollpanes if they've not been added anywhere.
Solution: Add your JScrollPane, s, that holds the JPanel to the GUI, not JPanel itself.
You dont honor the paint chain, call super.paintComponent(g) as first call in overridden paintComponent method. i.e
#Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
//draw here
}
or visual artifacts may occur.
Also note the #Override annotation which should be used with overridden methods in order to gain the advantage of compiler checking that we overrode the method correctly.
There is no need for getContentPane().add(..) simply call add on JFrame instance as add(..) along with remove(..) and setLayout(..) have been forward to the JFrames contentPane
Also not a good idea to go extending JFrame for nor reason, simply create an instance and use that i.e:
JFrame frame=new JFrame("Title here");
...
frame.add(..);
...
frame.pack();
frame.visible(true);
Also draw onto the Graphics object passed into paintComponent g dont go creating your own in paintComponent. Unless of course you're doing if for the reason #HFOE mentioned in below comment :).
No need for this parameter in drawImage(..) unless your JPanel implements on ImageObserver or the image may not be fully loaded when painting occurs. Simply use null.
And just for the cherry on top use some Graphics2D and RenderHints as seen here. This will allow for a better quality image to be drawn and text.
I got it! The main reason for me was no-layout manager and no-declarated size of this. There is my code:
public void draw(){
panel=new JPanel(new BorderLayout()){
#Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(img, 0, 0, null);
}
};
panel.setBounds(0, 0, img.getWidth(), img.getHeight());
panel.setPreferredSize(new Dimension(img.getWidth(),obraz.getHeight()));
JScrollPane scrolls=new JScrollPane(panel,ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
add(scrolls);
validate();
repaint();
}
But if someone will want copy this code in the future, there is one thing to be known- a size of Jpanel isn't refreshing (it's always one size of first opened image), but I have scrolsl and I am satisfied for now ;). Thanks a lot for everyone.

Issues with ImageIcon and images on buttons - JFrame

this has been driving me crazy all day so I figured I'd post it here and see if someone else can work it out. First off I tried to add a background image, the default ImageIcon was not working so I went with overriding the paint method instead. #
public class ImageJPanel extends JPanel {
private static final long serialVersionUID = -1846386687175836809L;
Image image = null;
public ImageJPanel(){
addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent e) {
ImageJPanel.this.repaint();
}
});
}
//Set the image.
public ImageJPanel(Image i) {
image=i;
setOpaque(false);
}
//Overide the paint component.
public void paint(Graphics g) {
if (image!=null) g.drawImage(image, 0, 0, null);
super.paint(g);
}
}
Once I used that it worked fine, however now I want to add images to my buttons but it is not working. Here is how my buttons work:
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Images images = new Images();
JPanel j = new ImageJPanel(images.menuBackground);
j.setLayout(null);
JButton Button_1= new JButton("Button_1",new ImageIcon("images/gui/Button.png"));
Insets insets = j.getInsets();
Dimension size = Button_1.getPreferredSize();
Button_1.setBounds(300 + insets.left, 150+ insets.top, size.width, size.height);
Singleplayer.setSize(200, 50);
j.add(Button_1);
frame.add(j);
frame.setSize(800,600);
frame.setResizable(false);
Button_1.addMouseListener(singleplayerPressed);
frame.setVisible(true);
All my images are .png, could that affect it?
Let's start with this:
public void paint(Graphics g) {
if (image!=null) g.drawImage(image, 0, 0, null);
super.paint(g);
}
This is the wrong approach. Firstly, you really don't want to override the paint method UNLESS you absolutely know that this is the correct approach to your problem (and without knowing more, I'd suggest it isn't).
Secondly, you paint your image on the component, then promptly paint over the top of it...(super.paint(g); can have the ability to paint over your work, I know the panel is opaque, but this is still a very bad approach).
Use paintComponent instead
protected void paintComponent(Graphics g) {
super.paint(g);
if (image!=null) g.drawImage(image, 0, 0, null);
}
PNG images are fine, they are supported by Swing out of the box.
Make sure that your program can see the image. Is it been loaded from the file source or is it a resource within you JAR?
Try this:
System.out.println(new File("images/gui/Button.png").exits());
If your program can see the file, it will return true other wise the program can not see the file and that is your problem.
Try this:
ImageIcon image = new ImageIcon(this.getClass()
.getResource("images/gui/Button.png"));
Side note, you should override paintComponent() not paint(). Also make sure to call super implementation before doing all your painting. For more details see Lesson: Performing Custom Painting tutorial.

Categories

Resources