我正在尝试创建一个程序,每隔几秒绘制 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();
}
}
最佳答案
JTextField textField = new JTextField(10);
one.add(textField, BorderLayout.PAGE_START);
one.add(f, BorderLayout.CENTER);
框架的默认布局管理器是 BorderLayout,因此您需要将 tomponens 添加到布局的不同区域。阅读 Swing 教程中关于 How to Use BorderLayout 的部分了解更多信息和示例。本教程还提供了其他布局管理器的示例,并将向您展示如何更好地设计您的类。
本教程还有一个关于自定义绘画
的部分,您应该阅读,因为您还应该设置自定义绘画面板的首选尺寸。
关于java - 如何创建包含文本框和绘画组件的 JFrame?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33555983/