2014-06-10 76 views
-2

幫我用void paint我已經導入它並且我導入了圖形。我想做一個下拉菜單

+2

你在這裏有什麼問題? –

+0

使用覆蓋'paint(Graphics g)'方法將'Panel'或'JPanel'添加到佈局中。 (你可以閱讀本教程:http://zetcode.com/tutorials/javaswingtutorial/painting/) – kajacx

回答

0
public class TextToGraphicConverter { 

    public static void main(String[] args) throws Exception { 
     BufferedImage image = new TextToGraphicConverter().convertTextToGraphic("my text", new Font("Arial", Font.PLAIN, 18)); 
     //then do what you want with the image 
    } 

    public BufferedImage convertTextToGraphic(String text, Font font) { 

     BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB); 
     Graphics2D g2d = img.createGraphics(); 

     g2d.setFont(font); 
     FontMetrics fm = g2d.getFontMetrics(); 
     int width = fm.stringWidth(text); 
     int height = fm.getHeight(); 
     g2d.dispose(); 

     img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); 

     g2d = img.createGraphics(); 
     g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY); 
     g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); 
     g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY); 
     g2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE); 
     g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); 
     g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); 
     g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); 
     g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE); 
     g2d.setFont(font); 
     fm = g2d.getFontMetrics(); 
     g2d.setColor(Color.BLACK); 
     g2d.drawString(text, 0, fm.getAscent()); 
     g2d.dispose(); 
     return img; 
    } 
} 
+0

非常感謝這很有幫助 – user3725193

+0

@ user3725193,我很高興:)。如果您發現它適合您的需要,請將答案設置爲正確。 –

相關問題