Reputation: 3
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MyDrawPanel extends JPanel{
public void paintComponents(Graphics g){
g.setColor(Color.orange);
g.fillRect(20,50,100,100);
}
public static void main(String[] args){
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.getContentPane().add(paintComponents(g));
frame.setVisible(true);
}
}
I think I should add something arguments in frame.getContentPane().add(paintComponents(g));
.
I looked up Graphics
class but I'm still struggling with it. What should be the parameter of it?
Upvotes: 0
Views: 269
Reputation: 26271
Okay, this is what I came up with:
public class MyDrawPanel extends JPanel
{
private static void createAndShowGUI()
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
MyDrawPanel panel = new MyDrawPanel();
panel.setOpaque(true);
frame.getContentPane().add(panel);
frame.setVisible(true);
}
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.orange);
g.fillRect(20,50,100,100);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run()
{
createAndShowGUI();
}
});
}
}
Notes:
There are several problems with your line frame.getContentPane().add(paintComponents(g));
. What you said is "add to the content pane the result of calling paintComponents
on g
. Where did g
come from? You can not used a variable until declared. The result of calling paintComponents
is void
which means the result cannot be used as an argument to a method. Presumably you had compiler errors.
I changed paintComponents
to paintComponent
. The former is used to control painting of subcomponents and in general should not be overridden.
Swing objects should not be created on the main thread. The details are complicated for a beginner (and described here in detail). Mostly you can just memorize the SwingUtilities.invokeLater
pattern used above.
Upvotes: 0
Reputation:
I'm no awt expert, but what I think you want to do is add a Canvas object to your content pane from the JFrame, then paint a Graphics object on it.
Upvotes: 0
Reputation: 35226
try this
public class MyDrawPanel extends JPanel{
MyDrawPanel()
{
setOpaque(true);
}
protected void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.orange);
g.fillRect(20,50,100,100);
}
public static void main(String[] args){
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new MyDrawPanel());
frame.setBounds(10,10,500, 500);
frame.setVisible(true);
}
}
Upvotes: 3