【问题标题】:Why getGraphics does work inside an ActionPerformed method?为什么 getGraphics 在 ActionPerformed 方法中起作用?
【发布时间】: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


    【解决方案1】:

    我认为这是因为在第一种情况下,new VentanaGrafica().setVisible(true);dibujar() 之后调用,这意味着一旦你使框架可见,panel 将被重新绘制,dibujar() 的效果将被删除在第二种情况下,panel 在您调用 dibujar() 后不会重新绘制。

    如果你想做一些自定义绘画,你将不得不重写paintComponent方法并添加一些逻辑来使组件的状态保持一致。

    这是一个例子:

    public class CustomPanel extends JPanel{
        Color color = Color.WHITE;
        protected void paintComponent(Graphics g){
            super.paintComponent(g);
            g.setColor(color);
            g.fillRect(200,0,120,80);
        }
        public void changeColor(Color color){
            this.color = color;
        }
    }
    

    以下是如何使用此面板:

    CustomPanel panel = new CustomPanel();
    panel.changeColor(Color.RED);
    panel.repaint();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-18
      • 2023-03-03
      • 1970-01-01
      • 2020-10-02
      • 2011-03-04
      • 2019-04-02
      相关资源
      最近更新 更多