【发布时间】:2016-05-12 04:51:03
【问题描述】:
为什么在接口 ActionListener 的方法 ActionPerformed 中调用 getGraphics() 时可以使用 getGraphics() 进行绘制,但不能在从构造函数或其他方法调用的方法中进行绘制。这是我制作的代码。为什么在“empezar”和构造函数中忽略了“dibujar”方法的调用,而在ActionListener方法中却没有?
import javax.swing.*;
import java.awt.Dimension;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class VentanaGrafica extends JFrame{
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run(){
new VentanaGrafica().setVisible(true);
}
});
}
public VentanaGrafica(){
empezar();
dibujar();
}
private void empezar(){
setTitle("Graficar con Jpanel");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setMinimumSize(new Dimension(600,600));
setResizable(false);
panel = new JPanel();
panel.setBackground(Color.blue);
panel.setSize(new Dimension(400,400));
boton = new JButton("Este boton");
boton.setFocusable(false);
panel.add(boton);
add(panel);
boton.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
dibujar();
}
});
pack();
dibujar();
}
private void dibujar(){
gc = panel.getGraphics();
gc.setColor(Color.red);
gc.fillRect(200,0,120,80);
}
JPanel panel;
Graphics gc;
JButton boton;
}
我读过 repaint() 方法每隔一段时间就会被调用来重绘,这意味着dibujar() 不会被忽略,但是 repaint() 已经删除了它的工作,但是为什么在 ActionEvent 内部进行调用时它没有发生?执行某种循环或禁止 repaint() 调用是某种隐含的?
【问题讨论】:
标签: java constructor jpanel jbutton actionlistener