Learn by practice right? Please critique and suggest anything! Thanks :)
import java.awt.EventQueue;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JFrame;
public class MainWindow
{
public static void main(String[] args)
{
new MainWindow();
}
JFrame frame;
GraphicsPanel gp = new GraphicsPanel();
MainWindow()
{
EventQueue.invokeLater(new Runnable() {
public void run() {
frame = new JFrame("Graphics Practice");
frame.setSize(680, 420);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gp.addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
});
gp.addMouseMotionListener(new MouseMotionListener() {
public void mouseDragged(MouseEvent e) {}
public void mouseMoved(MouseEvent e) {}
});
frame.add(gp);
}
});
}
}
GraphicsPanel:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JPanel;
import javax.swing.Timer;
public class GraphicsPanel extends JPanel {
Test t;
Timer test;
GraphicsPanel() {
t = new Test();
setLayout(new BorderLayout());
add(t, BorderLayout.CENTER);
test = new Timer(17, new Gameloop(this));
test.start();
}
class Gameloop implements ActionListener
{
GraphicsPanel gp;
Gameloop(GraphicsPanel gp) {
this.gp = gp;
}
public void actionPerformed(ActionEvent e) {
try {
t.incX();
gp.repaint();
} catch (Exception ez) { }
}
}
}
Test:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import javax.swing.JComponent;
public class Test extends JComponent
{
Toolkit tk;
Image img;
int x, y;
Test()
{
tk = Toolkit.getDefaultToolkit();
img = tk.getImage(getClass().getResource("images.jpg"));
this.setPreferredSize(new Dimension(15, 15));
}
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(Color.red);
g2d.drawString("x: " + x, 350, 50);
g2d.drawImage(img, x, 80, null);
g2d.dispose();
}
public void incX()
{
x++;
}
}