我只是在学习 java,必须使用 java swing 库和 Graphics2D 类来做一些事情。基本上我必须画一个有多个部分的建筑起重机:一个身体(起重机的身体)和一些附加的手臂(基本上它看起来像这样:http: //i.imgur.com/4YIkYqW.jpg) .
我的问题围绕着我是否正确使用了 Java swing 类?在下面的代码中,我省略了不必要的代码,因为我只是想确保我的结构正确(正确使用 JPanel、paintComponent() 等)。任何帮助将不胜感激,因为我正在学习 Java!多谢你们。
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)
}
}