私はjava GUIインターフェイスを学習しており、ボタンを持つプログラムを書いています。ボタンをクリックするたびに、ランダムなサイズの四角形が画面に追加されます。しかし、それを画面に追加するのではなく、古いものを消去したままにしておきます。ここに私のコードです。私はペイントをしようとしたが、それはうまくいかなかった。前もって感謝します。java gui paintComponent refresh
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);
}
}
}
参照[カスタム絵画アプローチ(https://tips4java.wordpress.com/2009/05/08/custom-painting-approaches/)作業例及び長所/短所のために以下に示唆されている2つのアプローチのそれぞれへ – camickr