如何使用Graphics2D类绘制String?

时间:2015-07-06 16:43:48

标签: java swing paintcomponent

问候,我正在开发一个简单的应用程序来获取无人机的视频反馈。所以这是我的问题。我不知道为什么我不能向我的面板显示字符串“无视频连接”。知道这里发生了什么吗?当我运行这个框架时,它只显示一个没有任何东西的普通空框架。感谢。

代码:

package dronetest;

import com.codeminders.ardrone.ARDrone;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import javax.swing.*;

public class testStringVideo extends javax.swing.JFrame {

    private AtomicReference<BufferedImage> image = new AtomicReference<BufferedImage>();
    private AtomicBoolean preserveAspect = new AtomicBoolean(true);
    private BufferedImage noConnection = new BufferedImage(500, 500, BufferedImage.TYPE_INT_RGB);
    /**
     * Creates new form testStringVideo
     */
    public testStringVideo() {
        initComponents();

        Graphics2D g2d = (Graphics2D) noConnection.getGraphics();
        Font f = g2d.getFont().deriveFont(24.0f);
        System.err.println(f);

        g2d.drawString("No video connection", 40, 100); 
        image.set(noConnection);
        System.err.println(image);
    }

    public void setDrone(ARDrone drone) {
        drone.addImageListener(this);
    }

    public void setPreserveAspect(boolean preserve) {
        preserveAspect.set(preserve);
    }

    public void frameReceived(BufferedImage im) {
        image.set(im);
        repaint();
    }

    public void paintComponent(Graphics g) {
        Graphics2D g2d = (Graphics2D) g;
        g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        int width = getWidth();
        int height = getHeight();
        drawDroneImage(g2d, width, height);
    }

    private void drawDroneImage(Graphics2D g2d, int width, int height) {
        BufferedImage im = image.get();
        if (im == null) {
            return;
        }
        int xPos = 0;
        int yPos = 0;
        if (preserveAspect.get()) {
            g2d.setColor(Color.BLACK);
            g2d.fill3DRect(0, 0, width, height, false);
            float widthUnit = ((float) width / 4.0f);
            float heightAspect = (float) height / widthUnit;
            float heightUnit = ((float) height / 3.0f);
            float widthAspect = (float) width / heightUnit;

            if (widthAspect > 4) {
                xPos = (int) (width - (heightUnit * 4)) / 2;
                width = (int) (heightUnit * 4);
            } else if (heightAspect > 3) {
                yPos = (int) (height - (widthUnit * 3)) / 2;
                height = (int) (widthUnit * 3);
            }
        }
        if (im != null) {
            g2d.drawImage(im, xPos, yPos, width, height, null);
        }
    }  

    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                        javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(testStringVideo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(testStringVideo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(testStringVideo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(testStringVideo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new testStringVideo().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify                     
    private javax.swing.JPanel jPanel1;
    // End of variables declaration                   
}  

2 个答案:

答案 0 :(得分:2)

一般来说,您不直接致电getGraphics()

Graphics2D g2d = (Graphics2D) noConnection.getGraphics();

这为您提供了指向Graphics对象的指针,但在绘制窗口时却没有。

相反,您应该覆盖内部paintComponent()的{​​{1}}方法,例如this tutorial演示(请注意其他人建议的JLabel来电。)

super.paintComponent()

当Swing准备好绘制该组件时,Swing Event Dispatch Thread调用public void paintComponent(Graphics g) { super.paintComponent(g); // Draw Text g.drawString("This is my custom Panel!",10,20); } 方法并传递paintComponent()实例。

有关Oracle网站(以及其他地方)的一些有用的教程可以更详细地介绍:

一定要仔细阅读这些内容; Swing为你做了很多幕后工作。它可以节省你很多时间,但如果你不明白它在做什么,你就会反对它,而不是让它与你一起工作。

答案 1 :(得分:1)

我不熟悉Java 2D,但另一种方法是创建JTextArea并将其添加到testStringVideo。如果您对如何操作感兴趣,请参阅以下一般性说明:

  1. 声明成员变量JTextArea connectionMessage;

  2. 发起它:connectionMessage = new JTextArea("No video connection");

  3. 创建一个方法,在需要时将connectionMessage添加到testStringVideo

  4. 让我知道这是否有效或者您是否还需要帮助!