【发布时间】:2015-11-05 22:26:12
【问题描述】:
我正在尝试创建一个每隔几秒钟绘制 100 条随机线的程序。我想添加一个文本字段,允许用户调整每次刷新之间的时间量。
但是,每当我尝试向我的 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();
}
}
【问题讨论】:
标签: java swing jframe jpanel paintcomponent