2014-02-23 78 views
-3

我想要得到一个Java 2D图形“你好世界”去,我发现它奇怪的困难(即,我是Googling“java你好世界的例子”的变种,并且空来)。任何人都可以用最简单的世界例子来帮助我吗?简单的Java 2D图形:绘制一个矩形?

编辑

这是一个很好的起点,虽然,"The Java Tutorials: Performing Custom Painting"

+2

参见[演出风俗绘画(http://docs.oracle.com/javase/tutorial/uiswing/painting/index.html) –

+1

所以,毫米,与你的代表。我知道正在发生的一些事情,但是你是否仍然可以扩展/完善这个问题? – user2864740

+2

你的代表有人问这个问题,就像一个热门小伙子问冰,而不是谷歌。 – Smitty

回答

11

要绘制在Swing一个矩形,你应该:

所有的
  • 首先,直接在JFrame中或其他顶级窗口永远不会画。
  • 而是绘制一个JPanel,JComponent或其他最终从JComponent继承的类。
  • 您应该重写paintComponent(Graphics g)方法。
  • 您应该确保调用超级方法
  • 您应该使用JVM为该方法提供的Graphics对象绘制矩形。
  • 您应该阅读Swing教程中的绘画。

清除?

例如,

import java.awt.Dimension; 
import java.awt.Graphics; 
import javax.swing.*; 

public class DrawRect extends JPanel { 
    private static final int RECT_X = 20; 
    private static final int RECT_Y = RECT_X; 
    private static final int RECT_WIDTH = 100; 
    private static final int RECT_HEIGHT = RECT_WIDTH; 

    @Override 
    protected void paintComponent(Graphics g) { 
     super.paintComponent(g); 
     // draw the rectangle here 
     g.drawRect(RECT_X, RECT_Y, RECT_WIDTH, RECT_HEIGHT); 
    } 

    @Override 
    public Dimension getPreferredSize() { 
     // so that our GUI is big enough 
     return new Dimension(RECT_WIDTH + 2 * RECT_X, RECT_HEIGHT + 2 * RECT_Y); 
    } 

    // create the GUI explicitly on the Swing event thread 
    private static void createAndShowGui() { 
     DrawRect mainPanel = new DrawRect(); 

     JFrame frame = new JFrame("DrawRect"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.getContentPane().add(mainPanel); 
     frame.pack(); 
     frame.setLocationByPlatform(true); 
     frame.setVisible(true); 
    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 
     public void run() { 
      createAndShowGui(); 
     } 
     }); 
    } 
} 
+0

很好的答案,但我不确定你需要在构造框架的线程中使用invokeLater,特别是因为它在最后才会显示。 –

3

您需要创建一个从JComponent延伸(或它的子类中的一个,如在JPanel下面的例子),并覆盖paintComponent(Graphics g)的类。这里有一个例子:

class MyPanel extends JPanel { 

    private int squareX = 50; 
    private int squareY = 50; 
    private int squareW = 20; 
    private int squareH = 20; 

    protected void paintComponent(Graphics g) { 
     super.paintComponent(g); // do your superclass's painting routine first, and then paint on top of it. 
     g.setColor(Color.RED); 
     g.fillRect(squareX,squareY,squareW,squareH); 
    } 
} 
+0

很好的例子:1+的投票(惊讶?) –

+0

@HovercraftFullOfEels - 没有。当我看到你们缺乏一个例子时,我决定增加一个答案。当你编辑你的答案来包含一个例子时,我向你投票(尽管我更喜欢我的例子 - 你有很多额外的内容,你必须通过查找你真正想知道的内容。) – ArtOfWarfare

1
class JCanvas extends JComponent 
    { 
     public void paintComponent(Graphics g) 
     { 

     Graphics2D g2 = (Graphics2D) g; 
      super.paintComponent(g); 
      g2.setColor(Color.red); 
      g2.drawRect(10,10,100,100); 


     } 
     } 

enter image description here