Skip to content

Instantly share code, notes, and snippets.

@jacbar
Created January 10, 2011 23:03
Show Gist options
  • Save jacbar/773654 to your computer and use it in GitHub Desktop.
Save jacbar/773654 to your computer and use it in GitHub Desktop.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MainFrame extends JFrame {
MainFrame(){
Rysunek r = new Rysunek();
setSize(500,500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
add(r);
}
public static void main(String[] args){
EventQueue.invokeLater(new Runnable(){
public void run(){
new MainFrame();
}
});
}
}
class Rysunek extends JPanel {
private JTextField xT = new JTextField(5);
private JTextField yT = new JTextField(5);
private Prostokat pr = new Prostokat(100,200,250,250);
private int x = 0;
private int y = 0;
Rysunek(){
super();
setSize(500,500);
JPanel p = new JPanel();
add(new JLabel("x : "));
p.add(xT);
p.add(new JLabel("y: "));
p.add(yT);
add(p,BorderLayout.NORTH);
super.setFocusable(true);
addMouseMotionListener(new MouseMotionListener(){
public void mouseDragged(MouseEvent arg0) {}
public void mouseMoved(MouseEvent e) {
x = e.getX();
y = e.getY();
xT.setText(Integer.toString(x));
yT.setText(Integer.toString(y));
if(pr.isInside(x, y))
pr.setColor(true);
else
pr.setColor(false);
repaint();
}
});
addKeyListener(new KeyListener(){
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
switch(e.getKeyCode()){
case KeyEvent.VK_DOWN : pr.move(0, 5);break;
case KeyEvent.VK_UP : pr.move(0, -5);break;
case KeyEvent.VK_LEFT : pr.move(-5, 0);break;
case KeyEvent.VK_RIGHT : pr.move(5,0);break;
}
if(pr.isInside(x, y))
pr.setColor(true);
else
pr.setColor(false);
repaint();
}
public void keyReleased(KeyEvent arg0) {}
public void keyTyped(KeyEvent arg0) {}
});
addMouseListener(new MouseListener(){
public void mouseClicked(MouseEvent arg0) {}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent arg0) {}
public void mousePressed(MouseEvent arg0) {}
public void mouseReleased(MouseEvent arg0) {}
});
}
public void paintComponent(Graphics g){
super.paintComponent(g);
pr.paint(g);
}
}
class Prostokat{
private int height;
private int width;
private int x;
private int y;
private boolean color = false;
Prostokat(int height, int width, int x, int y){
this.height = height;
this.width = width;
this.x = x;
this.y = y;
}
public boolean isInside(int x, int y){
if((this.x - width/2) <x && x < (this.x + width/2) && (this.y - height/2) < y&& y<(this.y + height/2))
return true;
else
return false;
}
public void setColor(boolean p){
color = p;
}
public void move(int x, int y){
this.x+=x;
this.y+=y;
}
public void paint(Graphics g){
if(color){
g.setColor(Color.BLUE);
g.fillRect(x-width/2, y-height/2, width, height);
}else{
g.setColor(Color.BLACK);
g.drawRect(x-width/2, y-height/2, width, height);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment