【问题标题】:Graphics component won't initialize图形组件不会初始化
【发布时间】:2013-11-09 13:48:13
【问题描述】:

我需要编写一个程序来打开图像,然后可以在上面绘图。但是我被卡住了,因为它将我的图形返回为空。这是问题所在的代码块。如果有的话,我可以添加整个内容。

 public void paintComponent(Graphics gd) {
  // super.paintComponent(g);

super.paintComponent(gd);
//gd.drawString("This is my custom Panel!",10,20);
pencil(gd);



    }


  public void pencil(Graphics gd){
     Graphics2D g2 = (Graphics2D)gd;
  System.out.println("g2 " + g2 + "method was called");

 //g2.setColor(Color.yellow);
 //Line2D line = new Line2D();
   g2.drawLine(x1,y1,x2,y2);  
//System.out.println("pencil");


 }



  public void actionPerformed(ActionEvent e) {
  if (e.getSource() == open){
  int returnVal = fc.showOpenDialog(Lab3.this);

  if (returnVal == JFileChooser.APPROVE_OPTION) {
           File file = fc.getSelectedFile();
          try {
                    img=ImageIO.read(file);
                    ImageIcon icon=new ImageIcon(img); // ADDED
                    image.setIcon(icon); // ADDED

                    Dimension imageSize = new           Dimension(icon.getIconWidth(),icon.getIconHeight()); // ADDED
                    image.setPreferredSize(imageSize); // ADDED
                    image.add(hbar, BorderLayout.SOUTH);
                    image.add(vbar, BorderLayout.EAST);
                    image.revalidate(); // ADDED
                    image.repaint(); // ADDED
                    Graphics gd = image.getGraphics();
                }
                catch(IOException e1) {}
            }
}
 if (e.getSource() == pencil){
 try{

     System.out.println("g2" + g2);
     //pencil();
    pencil(g2);
    //g2.draw(new Ellipse2D.Double(0, 100, 30, 30));
     //g2.drawRectanlge(100,100,200,200); 
     }
 catch ( Exception err1 ) {
       System.out.println( err1.getMessage( ) );
   }
 } 

【问题讨论】:

  • 1) 为了尽快获得更好的帮助,请发帖 SSCCE。 2) 对代码块使用一致且符合逻辑的缩进。代码的缩进是为了帮助人们理解程序流程。
  • 听起来您正在尝试在渲染任何内容之前进行 GFX - 不过从目前发布的代码中无法判断。
  • 在处理Graphics 到屏幕或打印机时,您不应该提供自己的Graphics 上下文,而应该让绘图子系统处理它,所以调用@987654327 @ 来自actionListener 不合适
  • 这个example 画在玻璃板上。

标签: java swing


【解决方案1】:

我猜你无法让 Graphics 工作

所以你需要做的是从摇摆中获取你的画布/面板/框架

Canvas canvas = new Canvas();
JFrame frame = new JFrame();

frame.add(canvas);
Graphics g = canvas.getGraphics();

【讨论】:

    猜你喜欢
    • 2020-01-29
    • 1970-01-01
    • 2020-10-24
    • 2012-11-09
    • 2017-07-05
    • 1970-01-01
    • 1970-01-01
    • 2019-01-24
    • 1970-01-01
    相关资源
    最近更新 更多