Reputation: 35
When I run this program all I see is a blank JFrame. I have no idea why the paintComponent method isn't working. Here's my code:
package com.drawing;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MyPaint extends JPanel {
private void go() {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.add(panel);
frame.setVisible(true);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.YELLOW);
g.fillRect(50, 50, 100, 100);
}
public static void main(String[] args) {
My paintTester = new MyPaint();
paintTester.go();
}
}
Upvotes: 1
Views: 1625
Reputation: 159874
You're adding a plain JPanel
to your JFrame
which does not contain your custom paint logic. Remove
JPanel panel = new JPanel();
and add
frame.add(this);
but better to maintain 2 classes: a main class and a custom JPanel
with paint logic for separation of concerns.
Upvotes: 2
Reputation: 14413
You have to do this
private void go() {
JFrame frame = new JFrame();
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.add(this);
frame.pack();
frame.setVisible(true);
}
But i would refactor your class and separate responsabilities..
go()
shouldn't be declared in this class
public class MyPaint extends JPanel {
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.YELLOW);
g.fillRect(50, 50, 100, 100);
}
}
And in another class
// In another class
public static void main(String[] args) {
JPanel paintTester = new MyPaint();
JFrame frame = new JFrame();
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.add(paintTester);
frame.pack();
frame.setVisible(true);
}
Or if you only gonna use this panel in one site you can take approach of anonymous classes
JFrame frame = new JFrame();
frame.add(new JPanel(){
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.YELLOW);
g.fillRect(50, 50, 100, 100);
}
});
Upvotes: 4