我只是在学习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)
}
}
Run Code Online (Sandbox Code Playgroud)
你的代码几乎是完美的。但有几点建议:
有些人可能不同意,但根据您的代码,我会进行这些更改以使其更整洁。
public class CraneSimulator {
...
private JFrame frame = new JFrame("CraneSimulator");
private MyPanel panel = new JPanel();
public CraneSimulator() {
...
frame.add(panel);
}
public static void main(String[] args) {
CraneSimulator simulator = new CraneSimulator();
}
}
class MyPanel extends JPanel {
CraneBody body = new CraneBody();
CraneArm arm1 = new CraneArm(body);
...
MouseAdapter mAdapter = new MouseAdapter() {
public void mousePressed(MouseEvent e) {
...
}
public void mouseReleased(MouseEvent e) {
...
}
public void mouseDragged(MouseEvent e) {
...
}
}
public MyPanel() {
...
addMouseListener(mAdapter);
addMouseMotionListener(mAdapter);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D graphics = (Graphics2D) g;
...
body.paint(graphics);
arm1.paint(graphics);
}
}
class CraneBody {
...
public CraneBody() {
....
}
...
public void paint(Graphics2D g) {
// You don't need to cast a Graphics again.
}
}
class CraneArm {
...
public CraneArm() {
....
}
...
public void paint(Graphics2D g) {
// You don't need to cast a Graphics again.
}
}
Run Code Online (Sandbox Code Playgroud)