import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.LineBorder;
public class MyProg extends JFrame implements ActionListener {
private JPanel main;
private MyComp myComponent;
private boolean paused;
private Timer timer;
public MyProg() {
super("My Prog");
this.paused = true;
getContentPane().setLayout(
new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
main = new JPanel();
main.setBackground(Color.BLACK);
main.setForeground(Color.YELLOW);
main.setBorder(new LineBorder(Color.BLUE, 8));
main.setPreferredSize(new Dimension(260, 260));
main.setMaximumSize(new Dimension(260, 260));
getContentPane().add(main);
JMenuBar menu = new JMenuBar();
JMenuItem start = new JMenuItem("Start", 'S');
start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
start();
}
});
menu.add(start);
setJMenuBar(menu);
}
public static void main(String[] args) {
MyProg f = new MyProg();
f.setSize(260, 260);
f.setBackground(Color.BLACK);
f.pack();
f.setResizable(false);
f.setVisible(true);
}
public void start() {
myComponent = new MyComp(new Point(15, 15), Color.YELLOW);
main.add(myComponent);
myComponent.setVisible(true);
timer = new Timer(100, this);
this.togglePause();
}
public void actionPerformed(ActionEvent ae) {
myComponent.advance();
}
protected void togglePause() {
paused = !paused;
if (paused)
pause();
else
unpause();
}
public void pause() {
if (timer.isRunning()) {
timer.stop();
}
}
public void unpause() {
if (!paused && !timer.isRunning())
timer.start();
}
}
class MyComp extends Canvas {
public MyComp(Point origin, Color c) {
this.setBackground(c);
this.setBounds(origin.x, origin.y, 0, 0);
}
public void advance() {
Point p = this.getLocation();
p.translate(1, 1);
this.setBounds(p.x,p.y,45,(this.getBounds().height >= 45) ? 45 : this.getBounds().height + 1);
}
public void paint(Graphics g) {
g.fillRect(0, 0, this.getWidth(), this.getHeight());
}
}