0
现在我正在研究计算机科学测试的一些练习题,而且我遇到了一个只能给我带来麻烦的问题。我理解大部分摆动,但我不明白如何在面板上创建和移动形状。这是我迄今为止:如何在JPanel上移动形状?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SwingStarting extends JFrame {
public JPanel innerPanel; // panel containing moving shape
public JButton pauseResumeButton;
public static final int LEFT = 0;
public static final int RIGHT = 1;
public int direction = LEFT;
// The dimensions of the inner panel. To simplify this problem,
// assume the panel will always have these dimensions.
public static final int PANEL_WIDTH = 600;
public static final int PANEL_HEIGHT = 400;
public Timer movementTimer = new Timer(10,new TimerListener());
public SwingStarting() {
innerPanel = new ShapePanel();
innerPanel.setPreferredSize(
new Dimension(PANEL_WIDTH,PANEL_HEIGHT));
innerPanel.setBorder(
BorderFactory.createLineBorder(Color.BLACK, 2));
pauseResumeButton = new JButton("pause");
add(innerPanel, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel(new FlowLayout());
buttonPanel.add(pauseResumeButton);
add(buttonPanel, BorderLayout.SOUTH);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setVisible(true);
movementTimer.start();
} // end constructor
public class ShapePanel extends JPanel {
public void paint(Graphics gc) {
super.paintComponent(gc);
int circleX = 0;
int circleY = 100;
gc.setColor(Color.RED);
gc.fillOval(circleX,circleY,20,20);
}
} // end inner class
public class TimerListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
} // end actionPerformed
} // end inner class
public static void main(String args[]) {
new SwingStarting();
} // end main
}// end class
到目前为止,我创建了一个小红圈。但是,我如何使它横向跨屏?任何帮助是极大的赞赏。
不要重写paint()。相反,你应该重载'paintComponent(...)'。 – camickr 2015-04-01 00:49:16