Help displaying g.drawString into a JFrame
I wrote a simple program that displays all the prime numbers less than 1000. I want to display the prime numbers in a JFrame. I was able to do so but the String is so long that it continues past the width of the JFrame. Is there any way I can 'wrap' the String down a few coordinates?
Here's the code that I currently have:
import javax.swing.*;
import java.awt.*;
public class Prime extends JPanel
{
public void paintComponent(Graphics g)
{
super.paintComponent(g);
int b;
int width = getWidth(), height = getHeight();
String primes = "";
for (int p = 3; p < 1000; p++)
{
boolean prime = true;
for (b = 2; b < p; b++)
{
if (p % b == 0)
prime = false;
}
if (prime)
{
primes = primes + "" + p;
}
}
g.setColor(Color.blue);
g.drawString(primes,width/50,height/5);
}
}
import javax.swing.*;
public class PrimeT
{
public static void main(String args[])
{
JFrame panel = new JFrame("Prime Numbers");
panel.setContentPane(new Prime());
panel.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel.setSize(1200,1000);
panel.setVisible(true);
}
}
import java.awt.*;
import java.util.*;
import javax.swing.*;
public class PrimeExample implements Runnable {
public void run() {
JTextArea area = new JTextArea(createText());
area.setLineWrap(true);
area.setWrapStyleWord(true);
JFrame f = new JFrame("PrimeExample");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(new JScrollPane(area));
f.setSize(300,200);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
String createText() {
java.util.List < Integer > primes = new ArrayList < Integer > ();
primes.add(2);
for (int p = 3; p < 1000; p++) {
boolean prime = true;
for (int b = 2; b < p; b++) {
if (p % b == 0) {
prime = false;
break;
}
}
if (prime)
primes.add(p);
}
return primes.toString();
}
public static void main(String[] args) {
EventQueue.invokeLater(new PrimeExample());
}
}
> Haha Probably not the best way for me to learn...
> Another question for you though... I haven't explored
> yet to try and figure this out but I will right now.
> So if you have a spare second how would I set up my
> JTextArea where it doesn't fill up the entire JFrame?
> - I guess another way to phrase it How can I
> embed the JTextArea at a specified place inside the
> JFrame?
If you want to place a Component inside a Container specifically at a particular place, then you have to use a null layout manager for the Container and then use setBounds
method to place the component inside the container.
Message was edited by:
qUesT_foR_knOwLeDge