java gui paintComponent刷新

时间:2016-06-29 01:51:55

标签: java swing user-interface jpanel paintcomponent

我正在学习java gui界面并编写了一个有按钮的程序。每次单击该按钮时,将在屏幕上添加一个随机大小的矩形。但是程序不是将其添加到屏幕上,而是继续删除旧的程序,我希望将其保留在屏幕上。这是我的代码。我试着做paint()但它没有用。提前谢谢。

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;

public class SimpleGui implements ActionListener {
JFrame frame =  new JFrame();
public static void main(String[] args){
    SimpleGui gui = new SimpleGui();
    gui.go();
}

public void go(){
    JButton button = new JButton("Add a rectangle");
    MyDrawPanel panel = new MyDrawPanel();

    button.addActionListener(this);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(BorderLayout.SOUTH, button);
    frame.getContentPane().add(BorderLayout.CENTER, panel);

    frame.setSize(300, 300);
    frame.setVisible(true);
}

public void actionPerformed(ActionEvent event){
    frame.repaint();
}
class MyDrawPanel extends JPanel{
    public void paintComponent(Graphics g){
        g.setColor(Color.blue);

        int height = (int) (Math.random()*120 + 10);
        int width = (int) (Math.random()*120 + 10);

        int x = (int) (Math.random()*40 + 10);
        int y = (int) (Math.random()*40 + 10);
        g.fillRect(x, y, height, width);

    }
}
}

1 个答案:

答案 0 :(得分:3)

你的paintComponent方法被编写为只绘制一个矩形,所以它的行为应该不会让你感到震惊。如果你想要它绘制多个,你有两个选择之一:

  • 创建ArrayList<Rectangle>,并在actionPerformed方法中,向此列表中添加一个新的随机Rectangle,然后调用repaint()。在paintComponent方法中,使用for循环迭代此List,绘制每个Rectangle。
  • 或者您可以将新的随机矩形绘制到paintComponent方法显示的BufferedImage上。

第一种方法是两者中的两种方法更容易,如果你担心程序的响应性,那么第二种方法就更好了,比如在动画程序中。

例如:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.swing.*;

@SuppressWarnings("serial")
public class TwoDrawRectMethods extends JPanel {
    // Array to hold our two drawing JPanels
    private AddRandomRect[] addRandomRects = {
            new DrawList("Using List"), 
            new DrawBufferedImage("Using BufferedImage")};

    // constructor
    public TwoDrawRectMethods() {
        // add drawing rectangles onto GUI
        for (AddRandomRect addRandomRect : addRandomRects) {
            add(addRandomRect);
        }
        // button to tell rectangles to add a new Rectangle
        add(new JButton(new DrawAction("Add New Rectangle")));
    }

    // The button's Action -- an ActionListener on "steroids"
    private class DrawAction extends AbstractAction {
        public DrawAction(String name) {
            super(name);
            int mnemonic = (int) name.charAt(0);
            putValue(MNEMONIC_KEY, mnemonic);
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            // tell both drawing JPanels to add a new rectangle
            for (AddRandomRect addRandomRect : addRandomRects) {
                addRandomRect.addRectangle();
            }
        }
    }

    private static void createAndShowGui() {
        TwoDrawRectMethods mainPanel = new TwoDrawRectMethods();

        JFrame frame = new JFrame("TwoDrawRectMethods");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}

@SuppressWarnings("serial")
class DrawList extends AddRandomRect {
    private static final Color RECT_COLOR = Color.RED;
    private List<Rectangle> rectList = new ArrayList<>();

    public DrawList(String title) {
        super(title);
    }

    @Override
    public void addRectangle() {
        rectList.add(createRandomRect());
        repaint();
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        g2.setColor(RECT_COLOR);
        for (Rectangle rectangle : rectList) {
            g2.draw(rectangle);
        }
    }


}

@SuppressWarnings("serial")
class DrawBufferedImage extends AddRandomRect {
    private static final Color RECT_COLOR = Color.BLUE;
    private BufferedImage img = null;

    public DrawBufferedImage(String title) {
        super(title);
    }

    @Override
    public void addRectangle() {
        if (img == null) {
            img = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
        }
        Rectangle rect = createRandomRect();
        Graphics2D g2 = img.createGraphics();
        g2.setColor(RECT_COLOR);
        g2.draw(rect);
        g2.dispose();
        repaint();
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (img != null) {
            g.drawImage(img, 0, 0, null);
        }
    }

}

@SuppressWarnings("serial")
abstract class AddRandomRect extends JPanel {
    private static final int PREF_W = 500;
    private static final int PREF_H = PREF_W;
    private Random random = new Random();

    public AddRandomRect(String title) {
        setBorder(BorderFactory.createTitledBorder(title));
    }

    abstract void addRectangle();

    protected Rectangle createRandomRect() {
        int x1 = random.nextInt(PREF_W);
        int x2 = random.nextInt(PREF_W);
        int y1 = random.nextInt(PREF_H);
        int y2 = random.nextInt(PREF_H);

        int x = Math.min(x1, x2);
        int y = Math.min(y1, y2);
        int width = Math.abs(x1 - x2);
        int height = Math.abs(y1 - y2);
        return new Rectangle(x, y, width, height);        
    }

    @Override
    public Dimension getPreferredSize() {
        if (isPreferredSizeSet()) {
            return super.getPreferredSize();
        }
        return new Dimension(PREF_W, PREF_H);
    }
}