자바 움직이는 그래픽을 멈추게 하는 법?
조회수 488회
public class Nba extends JFrame { int x,y,x1,y1; int a = 10; int a1 = 10;
String imgPath = "images/back.jpg";
ImageIcon originIcon = new ImageIcon(imgPath);
Image originImg = originIcon.getImage();
Image changedImg= originImg.getScaledInstance(400, 400, Image.SCALE_SMOOTH );
ImageIcon Icon = new ImageIcon(changedImg);
public Nba() {
setTitle("Free throw");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setContentPane(new Draw());
addKeyListener(new MykeyListener());
setSize(400,430);
setVisible(true);
new Thread(){
public void run(){
while(true){
x+=a;
System.out.println(Nba.this.getWidth());
if(x+10>=Nba.this.getWidth()){
a = -a;
}
if(x < 0){
a = (-a);
}
System.out.println(x);
repaint();
try {
Thread.sleep(40);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
} .start();
while(true) {
x1+=a;
System.out.println(Nba.this.getWidth());
if(x1+50>=Nba.this.getWidth()){
a = -a;
}
if(x1 < 0){
a = (-a);
}
System.out.println(x1);
repaint();
try {
Thread.sleep(65);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new Nba();
File file = new File("sound/throw.wav");
System.out.println(file.exists()); //true
try {
AudioInputStream stream = AudioSystem.getAudioInputStream(file);
Clip clip = AudioSystem.getClip();
clip.open(stream);
clip.start();
} catch(Exception e) {
e.printStackTrace();
}
}
class Draw extends JPanel{
public void paint(Graphics g) {
g.drawImage(Icon.getImage(), 0, 0, null);
g.setColor(Color.red);
g.drawLine(x,y,x,400);
g.drawLine(400, x1, y1, x1);
setOpaque(false); //그림을 표시하게 설정,투명하게 조절
super.paintComponent(g);
}
}
class MykeyListener extends KeyAdapter{
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ENTER) {
int x = e.getID();
int y = e.getID();
int x1 = e.getID();
int y1 = e.getID();
}
}
}
public void actionPerformed(ActionEvent e) {
Object obj = e.getSource();
// if (e.getSource() == ) {
}
}
//}
그래픽으로 이미지를 넣고 그 위에 가로,세로 직선이 자동으로 정해진 범위까지 왔다갔다하는 코드입니다만
이제 키보드에 일정한 키를 입력 받으면 위 2개의 직선이 멈추도록 하고 싶습니다.
이벤트를 사용해야 할 것 같은데 어떤 방법으로 접근해야 할지를 모르겠습니다....
-
(•́ ✖ •̀)
알 수 없는 사용자
댓글 입력