Java-如何在不丢失现有绘图的情况下绘制JFrame

时间:2015-10-29 23:33:48

标签: java swing paintcomponent repaint

我希望我的java程序能够绘制字符串"你好"随着输入法参数的变化,不会丢失以前的图纸。换句话说,框架必须绘制许多字符串" Hello"一个接一个,直到程序被迫停止。目前它只显示了一个单词" hello"随着它的新y位置改变了。

如何更改下面的程序以绘制" hello"有新y职位?非常感谢您的帮助。

谢谢

import java.awt.*;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import java.util.logging.Level;
import java.util.logging.Logger;
import  javax.swing.*;


public  class test6 extends JPanel  {
      int x=100;
    int y=30;



 String text = null; 



    public static void main (String args[]){

          JFrame frame = new JFrame("Test Game");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      test6 gamePanel = new test6();
      frame.add(gamePanel);
      frame.setSize(400,400);
      frame.setVisible(true);

        }


      @Override
      public  void paintComponent(Graphics g){


        super.paintComponent(g);   


input();


    g.drawString("hello", x, y);

      } 



  void input(){


   try {
              System.out.println("input your command?");
              BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

              text = in.readLine();

        y=y+50;


          } catch (IOException ex) {
              Logger.getLogger(test6.class.getName()).log(Level.SEVERE, null, ex);
          }


 repaint();


}

}

2 个答案:

答案 0 :(得分:2)

paintComponent()的实现中迭代List<Point>,其中每个点都是字符串的leading baseline。从这个example开始,以下迭代方案产生的图像类似于下面所示的图像。

    for (Bauble b : queue) {
        g2d.setColor(b.c);
        //g2d.fillOval(b.x, b.y, b.d, b.d);
        g2d.drawString("Hello", b.x, b.y);
    }

image

答案 1 :(得分:1)

如果要保留已绘制的内容,可以使用新的缓冲图像。创建一个字段:

Image drawing = new BufferedImage(600, 600, BufferedImage.TYPE_INT_ARGB);

然后在你的油漆组件中:

public void paintComponent(Graphics g){
    super.paintComponent(g);
    g.drawImage(drawing, 0, 0, this);
}

然后,当您想要更新图像时,只需绘制它。

public void addText(String s){
    Graphics2D g = drawing.createGraphics();
    g.setColor(Color.WHITE);
    g.drawString(s, x, y);
    g.dispose();
    repaint();
}

然后BufferedImage将累积所有绘制的字符串。

相关问题