0
我試圖創建一個程序,每隔幾秒就繪製100條隨機行。我想添加一個文本字段,允許用戶調整每次刷新之間的時間量。如何創建包含文本框和畫圖組件的JFrame?
但是,每當我嘗試添加更多的組件到我的JFrame中,paintComponent就會完全消失。如何使用文本字段和圖形創建窗口?
這是我迄今爲止
{
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.Timer;
import java.util.*;
public class Screensaver extends JPanel implements ActionListener {
public static void main (String[] args){ //Create Canvas
JFrame one = new JFrame("ScreenSaver");
one.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Screensaver f = new Screensaver();
one.add(f);
one.setSize(600,600);
one.setVisible(true);
}
public void paintComponent (Graphics a){
super.paintComponent(a);
this.setBackground(Color.WHITE);
a.setColor(Color.BLUE); //Outline
Random rand = new Random();
Timer time = new Timer(4000, this);
time.start();
for(int i =0; i<100; i++){
int x1 =rand.nextInt(600);
int y1 =rand.nextInt(600);
int x2 =rand.nextInt(600);
int y2 =rand.nextInt(600);
a.drawLine(x1, y1, x2, y2);
}
}
public void actionPerformed(ActionEvent e) {
repaint();
}
}
非常有幫助。非常感謝! – user5531310