我需要从代码内部关闭JFrame到包含的JPanel

时间:2014-04-25 14:38:50

标签: java swing

JPanel的代码     import javax.swing.JFrame;     import java.awt.Graphics;     import java.awt.Canvas;     import java.awt.Color;

import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.Timer;
import java.awt.EventQueue;
import javax.swing.JPanel;


public class Board extends JPanel
implements ActionListener{

private final int B_WIDTH = 500;
private final int B_HEIGHT = 500;
private final int INITIAL_X = 400;
private final int INITIAL_Y = 0;
private final int DELAY = 25;


private Image star;
private Timer timer;
private int x, y;

public Board(){
    loadImage();
    initBoard();
}

public void loadImage(){
    ImageIcon ii = new ImageIcon("star.png");
    star = ii.getImage();
}

public void initBoard() {
    setBackground(Color.BLACK);
    setPreferredSize(new Dimension(B_WIDTH,B_HEIGHT));
    setDoubleBuffered(true);

    x = INITIAL_X;
    y = INITIAL_Y;

    timer = new Timer(DELAY, this);
    timer.start();
}

@Override
public void paintComponent(Graphics g){
    super.paintComponent(g);

    drawStar(g);
}

private void drawStar(Graphics g){
    Graphics2D g2d = (Graphics2D) g;
    g2d.drawImage(star, x, y, this);
    Toolkit.getDefaultToolkit().sync();
    g.dispose();
}

这是我想要关闭JFrame的地方,但我不知道怎么做。 我想从if语句中关闭它。

@Override
public void actionPerformed(ActionEvent e){

    x -= 3;


    if(x < -400){


    }
    repaint();

}

}

对于JFrame     import javax.swing.JFrame;

java.awt.EventQueue;



public class SwingTimer extends JFrame {
public SwingTimer(){
    add(new Board());
    setTitle("FIGHT");
    pack();
    setResizable(false);
    setLocationRelativeTo(null);
    setDefaultCloseOperation(EXIT_ON_CLOSE);

}


public static void FightGraphics(){
    EventQueue.invokeLater(new Runnable(){
        @Override
        public void run(){
            JFrame ex = new SwingTimer();
            ex.setVisible(true);
        }
    });
}
}

1 个答案:

答案 0 :(得分:0)

mb JFrame的dispose()有帮助。检查this