问题
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
forJPanel
, otherwiseJPanel
with Java2D only to returns zeroDimension
override
paintComponent()
, more see in Oracle tutorialread Oracle tutorial Inintial Thread
you wouldn't
myPanel.setLayout(null);
use Null Layoutframe.setSize(400,400);
forJFrame
,JPanel
etc, becauseJComponents
(override getPreferredSize
) are designated to returns properDimension
to its contianer,JFrame.pack(before JFrame.setVisible)
to calculate, determine proper size for container(s) in pixelsinvoke 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