How to paint inside JPanel

只谈情不闲聊 提交于 2021-01-28 05:25:52

问题


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

}


回答1:


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



来源:https://stackoverflow.com/questions/19251941/how-to-paint-inside-jpanel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!