我是编程的新手,我似乎无法解决这个问题:如何让我的应用框架发生变化?这是一个扫雷游戏。程序逻辑很好,事件正在运行,但框架本身并没有重新绘制......我没有applet的这种问题..我怎样才能使这个工作?
public void paint(Graphics g) {
Graphics2D g2=(Graphics2D)g;
_Main.toPaint(g2);
}
public void update(Graphics g) {
Graphics offgc;
Image offScreen=null;
Dimension d=size();
offScreen=createImage(d.height, d.width);
offgc=offScreen.getGraphics();
offgc.setColor(getBackground());
offgc.fillRect(0, 0, d.width, d.height);
offgc.setColor(getForeground());
paint(offgc);
g.drawImage(offScreen,0,0,this);
}
答案 0 :(得分:1)
似乎你错误地绘制了图形。对于custom paintings,您需要使用JComponent
的{{3}}方法,例如JPanel
,而不是paint()
方法和自定义update()
。要更新组件图形,只需调用repaint()
方法。
以下是为您绘图的简单示例,请尝试检查:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Example extends JPanel{
private Random rand = new Random();
public static void main(String... s){
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final Example example;
f.add(example = new Example());
JButton b = new JButton("repaint");
b.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
example.repaint();
}
});
f.add(b, BorderLayout.SOUTH);
f.setSize(200,200);
f.setVisible(true);
}
public Example(){
setBackground(Color.WHITE);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLACK);
for(int i =0; i<10;i++){
int nextInt = rand.nextInt(getHeight()-10);
int nextInt2 = rand.nextInt(getWidth()-10);
g.fillRect(nextInt2, nextInt, 10, 10);
}
}
}
还阅读Andrew Thompson的推荐。
答案 1 :(得分:0)
尝试使用JFrame
课程。假设您的JFrame
被称为frame
。尝试frame.pack()
,然后frame.repaint()
。唯一的问题是我不知道如何让frame.repaint()
方法在线程中调用自己;它想等到线程终止。