Reputation: 15
I'm trying to create a program that draws 100 random lines every few seconds. I want to add a text field that allows the user to adjust the amount of time in between each refresh.
However, whenever I try to add any more components to my JFrame, the paintComponent disappears completely. How do I create a window with a text field and a drawing?
This is what I have so far
{
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();
}
}
Upvotes: 0
Views: 1107
Reputation: 324128
JTextField textField = new JTextField(10);
one.add(textField, BorderLayout.PAGE_START);
one.add(f, BorderLayout.CENTER);
The default layout manager for a frame is the BorderLayout, so you need to add tomponens to a different area of the layout. Read the section from the Swing tutorial on How to Use BorderLayout for more information and examples. The tutorial also has examples of other layout managers and will show you how to better design your class.
The tutorial also has a section on Custom Painting
your should read because you also should set the preferred size of your custom painting panel.
Upvotes: 1