Sam
Sam

Reputation: 374

How to paint inside JPanel

I have a JPanel inside a Jframe.I want to draw a line inside JPanel, using paint(Graphics g) method. But it is not working. Please Someone help me on this issue. Here is the code. Thank you all in advance.

import java.awt.Color;

import java.awt.Graphics;

import javax.swing.JFrame;

import javax.swing.JPanel;

import javax.swing.SwingUtilities;

public class JavaGraph {

JPanel myPanel;

public JPanel createPanel()
{

    myPanel=new JPanel();
    myPanel.setLayout(null);
    //myPanel.setBackground(Color.black);
    return myPanel;

}
public static void  display()
{
    JFrame frame=new JFrame();
    JavaGraph j=new JavaGraph();
    frame.add(j.createPanel());
    frame.setVisible(true);
    frame.setSize(400,400);
    }

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable()
            {
        public void run()
        {
            display();
        }
            });
}

}

Upvotes: 1

Views: 341

Answers (1)

mKorbel
mKorbel

Reputation: 109823

you would

  • override getPreferredSize for JPanel, otherwise JPanel with Java2D only to returns zero Dimension

  • override paintComponent(), more see in Oracle tutorial

  • read Oracle tutorial Inintial Thread

you wouldn't

  • myPanel.setLayout(null); use Null Layout

  • frame.setSize(400,400); for JFrame, JPanel etc, because JComponents (override getPreferredSize) are designated to returns proper Dimension to its contianer, JFrame.pack(before JFrame.setVisible) to calculate, determine proper size for container(s) in pixels

  • invoke any code to set, change or intialize Swing GUI, after frame.setVisible(true); is called

Upvotes: 1

Related Questions