如何创建包含文本框和绘画组件的 JFrame?
How do I create a JFrame containing a text box and paint component?
我正在尝试创建一个每隔几秒绘制 100 条随机线的程序。我想添加一个文本字段,允许用户调整每次刷新之间的时间量。
但是,每当我尝试向我的 JFrame 添加更多组件时,paintComponent 就会完全消失。如何创建带有文本字段和绘图的 window?
这是我目前所拥有的
{
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,因此您需要将连杆添加到布局的不同区域。阅读有关 How to Use BorderLayout 的 Swing 教程部分,了解更多信息和示例。本教程还有其他布局管理器的示例,将向您展示如何更好地设计您的 class.
本教程还有一个部分是关于 Custom Painting
您应该阅读的,因为您还应该设置自定义绘画面板的首选大小。
我正在尝试创建一个每隔几秒绘制 100 条随机线的程序。我想添加一个文本字段,允许用户调整每次刷新之间的时间量。
但是,每当我尝试向我的 JFrame 添加更多组件时,paintComponent 就会完全消失。如何创建带有文本字段和绘图的 window?
这是我目前所拥有的
{
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,因此您需要将连杆添加到布局的不同区域。阅读有关 How to Use BorderLayout 的 Swing 教程部分,了解更多信息和示例。本教程还有其他布局管理器的示例,将向您展示如何更好地设计您的 class.
本教程还有一个部分是关于 Custom Painting
您应该阅读的,因为您还应该设置自定义绘画面板的首选大小。