I am just learning java and have to do something using the java swing library, and the Graphics2D class. Basically I have to draw a construction crane that has multiple parts: a body (the body of the crane), and a number of attached arms (basically it looks like this: https://i.stack.imgur.com/raBxN.jpg).
My question revolves around if I am using the Java swing class correctly? In my code below, I left out unnecessary code, as I just want to make sure my structure is correct (Using JPanel, paintComponent(), etc. correctly). Any help would be appreciated, as I am just learning Java! Thanks guys.
public class CraneSimulator {
...
public JFrame frame;
public MyPanel panel;
public CraneSimulator() {
frame = new JFrame("CraneSimulator");
...
panel = new MyPanel();
frame.add(panel);
}
public static void main(String[] args) {
CraneSimulator simulator = new CraneSimulator();
}
}
class MyPanel extends JPanel {
CraneBody body;
CraneArm arm1;
...
Graphics2D graphics;
public MyPanel() {
body = new CraneBody();
arm1 = new CraneArm(body);
...
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
... }
}
public void mouseReleased(MouseEvent e) {
...
}
});
addMouseMotionListener(new MouseAdapter() {
public void mouseDragged(MouseEvent e) {
...
}
});
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
graphics = (Graphics2D) g;
...
body.paint(g);
arm1.paint(g);
}
}
class CraneBody {
...
public CraneBody() {
....
}
...
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
// Use g2 to actual paint crane Body on screen here (ie. g2.drawRect, etc)
}
}
class CraneArm {
...
public CraneArm() {
....
}
...
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
// Use g2 to actual paint the crane armon screen here (ie. g2.drawRect, etc)
}
}