Сейчас я работаю над некоторыми практическими проблемами для теста на компьютерную науку, и я столкнулся с тем, что не дает мне ничего, кроме неприятностей. Я понимаю, что качели по большей части, но я не понимаю, как создавать и перемещать фигуру на панели. Это то, что у меня есть до сих пор:Как перемещать форму через 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
До сих пор я создал небольшой красный круг. Но как мне сделать это поперек экрана по горизонтали? Любая помощь приветствуется.
Не перегружайте краску(). Вместо этого вы должны переопределить 'paintComponent (...)'. – camickr