Displaying 2D graphics in a JPanel
807603Feb 7 2008 — edited Feb 7 2008I'm new to Java so please bear with me.
I'm trying to write a GUI which controls a 2D graphic drawn on a Panel. The code it too long to post so I've simulated what I'm trying to do in this followowing bit of code -
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
public class BasicPanel {
public JPanel createContentPane() {
JPanel aPanel = new JPanel();
DrawPanel bpanel = new DrawPanel();
aPanel.add(bpanel);
//content panes must be opaque
aPanel.setOpaque(true);
return aPanel;
}
private static void ShowGui() {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("panel test]");
//Create and set up the content pane.
BasicPanel demo = new BasicPanel();
frame.setContentPane(demo.createContentPane());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.setVisible(true);
}
public class DrawPanel extends JPanel {
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
// draw a line
double x1 = 50;
double y1 = 50;
double x2 = 250;
double y2 = 250;
g2d.draw(new Line2D.Double(x1, y1, x2, y2));
// draw rectangle
double x = 50;
double y = 50;
double width = 200;
double height = 200;
Rectangle2D rect =
new Rectangle2D.Double(x, y, width, height);
g2d.draw(rect);
// draw ellipse
Ellipse2D ellipse = new Ellipse2D.Double();
ellipse.setFrame(rect);
g2d.draw(ellipse);
}
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
ShowGui();
}
});
}
}
aPanel would be my existing panel on the GUI and I want the output of DrawPanel to appear on aPanel. It seems basic stuff but it doesn't work and I don't yet understand why not. What have I forgotten to do? Any help would be much appreciated.
TIA