call paintcomponent for a jpanel in jframe - java

I have a JFrame with a JPanel on it (JPanel is private in JFrame). Now I want to override JPanel by using paintComponent method.
How can I do that?

When you create your instance of JPanel, (assuming you're doing it this way), do this:
JPanel panel = new JPanel(){
#Override
public void paintComponent(Graphics g){
// paint code
}
};
The other alternative is to create a private class which extends JPanel.
For example:
public class OuterClass{
// fields, constructors, methods etc..
private class MyPanel extends JPanel{
// fields, constructors, methods etc..
#Override
public void paintComponent(Graphics g){
// paint code
}
}
}

not clear from your question, but I think that nothing complicated override paintComponent for Swing JComponents, please avoid to use method paint() for Swing JComponents, use only paintComponent()

Related

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();
}
});
}
}

Drawing on Canvas without extending it?

In order to draw images and or shapes in my JFrame, I use a very common method that works.
I use a class that extends canvss, make my own custom JFrame object then add my own class (which extends camvas). Then, I override the 'paint' method in order to paint on the canvas.
Basicly, here is an example: http://pastebin.com/KhZudT3r
This whole process works perfectly, but I was wondering if there's a way to draw on a jframe (perferebly a canvas) without having to extend the canvas class?
Thanks,
Jake
Try with JPanel and override paintComponent() method for your custom painting.
Don't forget to call super.paintComponent(g) in overridden method.
Never draw directly on JFrame itself instead draw on JPanel and then add it into JFrame
Sample code:
JPanel panel = new JPanel() {
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
//your custom drawing here
}
};

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();
}
});
}
}

Using awt.Graphics in a method

I created a class called Test, most likely where I went wrong.
import javax.swing.JPanel;
import java.awt.*;
public class Test extends JPanel {
Graphics grap;
public void sun()
{
super.paintComponent(grap);
grap.setColor(Color.YELLOW);
grap.fillOval(0,0,20,20);
}
}
As you can see I want to paint a yellow "Oval" in the top left corner of the panel using a method but I did not use a PaintComponent method. Now I try to implement it in my Paint component method which is in a class called Painting.
//import...;
public class Painting extends JPanel{
protected void paintComponent(Graphics g)
{
Test test = new Test();
test.sun();
}
And now i created a main window that will create a panel and display the yellow oval.
//import...
public class main extends JFrame{
public static main(String [] args){
JFrame window = new JFrame();
window.add(new Painting());
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(100,100);
window.setLocationRelativeTo(null);
window.setVisible(true);
}
}
But this does not work. I have a feeling that it is the sun method in test. How would I get this to work? I have looked in all the java books and cant find anything that can help.
Please note that I do not what to add parameters to the method.
Thank You
Tom.
Few points to be noted here:
Never call super.paintComponent by yourself except within the overriden paintComponent method itself.
If you want to do some Graphics activities then override the paintComponent method and draw graphics over there
When you are overriding paintComponent method then the first statement within the method should be super.paintComponent(g).
Now, going by all above points your code should now be like this:
public class Test extends JPanel {
public void paintComponent(Graphics grap)
{
super.paintComponent(grap);
grap.setColor(Color.YELLOW);
grap.fillOval(0,0,20,20);
}
}
And your Painting class should be like this:
public class Painting extends JPanel{
Test test;
public Painting()
{
test = new Test();
setLayout(new BorderLayout());
add(test);
}
}
If i want to draw 50 ovals on different places then i would have a problem with extensive code
Then you would keep a List of the ovals that you want to paint. See Custom Painting Approaches which paints a bunch of Rectangles on a panel. All the code does is loop through the ArrayList to paint the Rectangle. Only a couple of lines of code are required.

Invisible objects because repaint method - Java Swing

The problem comes because I overwrite the paintComponent method of a jPanel, so when I repaint all the objets are hidden till I focus them.
I need to overwrite the paintComponent method cause it's the only one answer I'd found in internet to change the background image of a jFrame.
So firstly I create a jPanel class:
public class JPanelFondoPrincipal extends javax.swing.JPanel {
public JPanelFondoPrincipal(){
this.setSize(800,500);
}
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
Dimension tamanio = getSize();
ImageIcon imagenFondo = new ImageIcon(getClass().getResource("/images/fondo_principal.png"));
g.drawImage(imagenFondo.getImage(),0,0,tamanio.width, tamanio.height, null);
setOpaque(false);
}
}
And in my jPanelForm:
private void formWindowOpened(java.awt.event.WindowEvent evt) {
// TODO add your handling code here:
JPanelFondo p = new JPanelFondo();
this.add(p);
validate();
p.repaint();
}
I'd already tried to add all my Objets (labels, textFields...) to a new Panel so I can add it after repaint, and set all the objets visibles manually but everything is still invisible.
Many thanks, I need to finish the app in 6 days and I'm getting crazy by the minute
EDIT: SOLVED THANKS TO CARDLAYOUT
don't add / remove JPanels or its contents on runtime, use CardLayout instead
your JPanelFondo p = new JPanelFondo(); doesn't corresponding somehow with public class JPanelFondoPrincipal extends javax.swing.JPanel {
for better help sooner edit your question with an SSCCE,
Swing programs should override paintComponent() instead of overriding paint().
http://java.sun.com/products/jfc/tsc/articles/painting/
And you should call super.paintComponent(g); first in overriden paintComponent();
public void paintComponent(Graphics g){
super.paintComponent(g);
Dimension tamanio = getSize();
ImageIcon imagenFondo = new ImageIcon(getClass().getResource("/images/fondo_principal.png"));
g.drawImage(imagenFondo.getImage(),0,0,tamanio.width, tamanio.height, null);
setOpaque(false);
}
Here's the proper way to handle painting onto JPanel component.

Categories

Resources