Drawrect not working (Java) - java

This has been driving me absolutely crazy. I can't get this rectangle to appear. I'm new to programming and I'm trying to recreate pong in 2D as a learning experience. Here's the code:
package ping;
import javax.swing.*;
public class Pong extends JFrame implements MouseListener {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* #param args
*/
public Pong(String title) {
this.setTitle(title);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.getContentPane().setBackground(Color.RED);
this.getContentPane().setLayout(null);
this.setSize(500, 500);
Paddles a = new Paddles(), b = new Paddles();
a.setBounds(225, 25, 50, 10); b.setBounds(225, 475, 50, 10);
this.getContentPane().add(a); this.getContentPane().add(b);
a.setVisible(true); b.setVisible(true);
this.getContentPane().addMouseListener(this);
this.setVisible(true);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Pong game = new Pong("Java Pong");}
And then the Paddles class:
import java.awt.Graphics;
import java.awt.Color;
import javax.swing.JComponent;
public class Paddles extends JComponent {
/**
*
*/
private static final long serialVersionUID = 1L;
public Paddles() {}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLACK);
g.drawRect(0,0,0,0);
g.fillRect(0,0,0,0);
System.out.println("paintworks");
System.out.println(Integer.toString(this.getY()));
}
}
Thanks in advance!

You have a zero size rectangle
this is the updated method.
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLACK);
g.drawRect(this.x,this.y,10,10); // look at the api this command is redundant
g.fillRect(this.x,this.y,10,10); // as fill rect will overdraw it anyway.
System.out.println("paintworks");
System.out.println(Integer.toString(this.getY()));
}

g.drawRect(0,0,0,0);
g.fillRect(0,0,0,0);
Both of these lines indicate to draw something of no size. The final two parameters should indicate the width and height.
See the javadoc for more detail.

Related

How can I add objects to the screen when I press the mouse button?

I am currently making a tile based game. Everything so far is working fine. However, I want the player to be able to add objects, like stone or wood to the screen when he/she presses the mouse button. I attempted this myself but it is not working. Here is what I have done, but is not working:
This is my KeyInput class, where all the keyboard and mouse events take place.
public static ArrayList<StoneTile> sTile = new ArrayList<StoneTile>();
public KeyInput(Handler handler) {
this.handler = handler;
}
public void tick(LinkedList<Square> object) {}
public void mousePressed(MouseEvent e){
int mx = e.getX();
int my = e.getY();
System.out.println("Pressed (X,Y): " + mx + " " + my);
sTile.add(new StoneTile(1,mx,my));
if(sTile.add(new StoneTile(1,mx,my))){
System.out.println("ADDED");
}
}
public void mouseReleased(MouseEvent e){
System.out.println("Released");
}
Here is my StoneTile class, this is what I want to add to screen:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.util.LinkedList;
public class StoneTile extends Tile {
Textures tex;
public StoneTile(int id,int x,int y) {
super(Textures.stoneArray[0], id);
Tile.x = x;
Tile.y = y;
}
public static void main(String[] args) {
}
public Rectangle getBounds(){
return new Rectangle(x,y,Tile.TILEWIDTH,Tile.TILEHEIGHT);
}
}
The Textures.stoneArray[0] is simply the image that I want to add to the screen.
The Tile.(instance variable, like x, y, TILEWIDTH, and TILEHEIGHT) is simply a Tile class that contains all the render methods for the tiles (grass, stone, etc). If anything is unclear I will clarify or if you need any code provided, then I will add it in.
Note - The ArrayList was just an idea that I had in mind, if there are more efficient ways of doing this or any better ideas, I am open to all of them.
Here is where I set the MouseListener. I set it in an init() method and then called in a run() method (last line):
private void init() {
BufferedImageLoader loader = new BufferedImageLoader();
level = loader.loadImage("level.png");
world = new worldLoader("res/worlds/world1.txt");
handler = new Handler();
WIDTH = getWidth();
HEIGHT = getHeight();
cam = new Camera(handler, Game.WIDTH / 2, Game.HEIGHT / 2);
setWIDTH(getWidth());
setHEIGHT(getHeight());
tex = new Textures();
//backGround = loader.loadImage("/background.jpg");
handler.addObject(new Coin(100, 100, handler, ObjectId.Coin));
handler.addObject(new newStoneTile(20,20,ObjectId.newStoneTile));
handler.addObject(new player_Square(100,100, handler, ObjectId.player_Square));
//handler.addObject(new OneUp(300, 150, handler, ObjectId.OneUp));
this.addKeyListener(new KeyInput(handler));
this.addMouseListener(new KeyInput(handler));
}
jcomponent, is this what you meant?
public class Window {
private static final long serialVersionUID = -6482107329548182911L;
static final int DimensionX = 600;
static final int DimensionY = 600;
public Window(int w, int h, String title, Game game) {
game.setPreferredSize(new Dimension(w, h));
game.setMaximumSize(new Dimension(w, h));
game.setMinimumSize(new Dimension(w, h));
JFrame frame = new JFrame();
frame.add(game);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
game.start();
}
}
Perhaps the best way to try and answer this question is to give a small example.
Essentially what needs to happen is the following (assuming my understanding of the problem is correct):
User clicks on the JComponent/JPanel to determine where to place a Tile. This will cause a MouseEvent that needs to be listened for and handled.
The JComponent/JPanel needs a MouseListener implementation which will create a new Tile object and add it to the List of the Tile objects. Once this is complete the JComponent/JPanel needs to know to repaint(). You do not override repaint() but rather paintComponent(Graphics g), which will be called by repaint() (eventually).
The paintComponent(Graphics g) method will iterate over the List of Tile objects, drawing them to the JComponent/JPanel using the Graphics context for the component.
To illustrate this I have simplified your problem. Note this isn't the best way to solve the problem since the Model (game logic) and the GUI should be separated, ideally using Model View Controller / Observer pattern.
First and most importantly is the GamePanel class, which extends JPanel. It's sole role in this example is to display the game graphically and handle mouse clicks. i.e. handling the list of tasks noted above.
GamePanel
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JPanel;
public class GamePanel extends JPanel {
private List<Tile> tiles; // Stores the Tile objects to be displayed
/**
* Sole constructor for GamePanel.
*
* #param width the width of the game panel
* #param height the height of the game panel
*/
public GamePanel(int width, int height) {
tiles = new ArrayList<>();
setPreferredSize(new Dimension(width, height));
// Implement mouse events for when the JPanel is 'clicked', only using the
// mouse released operation in this case.
addMouseListener(new MouseListener() {
#Override
public void mouseReleased(MouseEvent e) {
// On mouse release, add a StoneTile (in this case) to the tiles List
tiles.add(new StoneTile(e.getX(), e.getY()));
// Repaint the JPanel, calling paint, paintComponent, etc.
repaint();
}
#Override
public void mouseClicked(MouseEvent e) {
// Do nothing
}
#Override
public void mousePressed(MouseEvent e) {
// Do nothing
}
#Override
public void mouseEntered(MouseEvent e) {
// Do nothing
}
#Override
public void mouseExited(MouseEvent e) {
// Do nothing
}
});
}
/**
* Draws the Tiles to the Game Panel.
*
* #param g the Graphics context in which to paint
*/
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g); // Make sure you do this
// For this example, using black as the color to draw
g.setColor(Color.BLACK);
// Iterate over the tile list and draw them to the JPanel
for (Tile tile : tiles) {
Rectangle tileRect = tile.getBounds();
g.fillRect(tileRect.x, tileRect.y, tileRect.width, tileRect.height);
}
}
}
Second is the GameFrame, which extends JFrame. This is just a basic JFrame which adds a GamePanel object. I've also included the main method which will ensure the GUI is initialized on the Event Dispatch Thread.
GameFrame
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class GameFrame extends JFrame {
private static final String TITLE = "Tile Game"; // Game Frame Window Title
private final JPanel gamePanel;
/**
* Sole constructor for GameFrame.
*
* #param width the width of the game in pixels
* #param height the height of the game in pixels
*/
public GameFrame(int width, int height) {
gamePanel = new GamePanel(width, height);
}
/**
* Performs final configuration and shows the GameFrame.
*/
public void createAndShow() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle(TITLE);
add(gamePanel);
pack();
setVisible(true);
}
/**
* Entry point for the program.
*
* #param args not used
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
GameFrame gameFrame = new GameFrame(640, 480);
gameFrame.createAndShow();
}
});
}
}
Finally, the other classes used in the example for completeness, Tile and StoneTile. Personally I don't see much benefit from using Rectangle inside the model, but each to their own and I wanted to keep the example somewhat similar to your currently implementation.
Tile
import java.awt.Rectangle;
public abstract class Tile {
private int x, y, width, height;
public Tile(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
public Rectangle getBounds() {
return new Rectangle(x, y, width, height);
}
}
StoneTile
public class StoneTile extends Tile {
public StoneTile(int x, int y) {
super(x, y, 100, 100);
}
}
One final comment. I notice that your sTile ArrayList is static, this should probably not be the case as it belongs to the class rather than a particular instance of the class.

how to use the wait(long timeout) on jpanel

I am taking an introductory java class and I have an inheritance related problem. I have to implement a system that has classes for various figures. the superclass is Figures and subclasses are Circle, Box and Rectangle and I am supposed to output the figures in the JPanel. I have designed all the classes and my code is below but I need to define the center() method on the figure class which when called on an object should draw and also erase the object. so within the main method of the JPanel class, I want to use the center() method to draw the three shapes and use the wait(long timeout) method to make the shapes change to random positions after 15 seconds.
import java.awt.Graphics;
import javax.swing.JPanel;
public abstract class Figure extends JPanel {
protected int xCoord;
protected int yCoord;
public Figure() {
}
public void erase() {
}
public void draw() {
}
public void center() {
}
}
the rectangle sub class is:
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
public class Rectangle extends Figure {
int width;
int height;
public Rectangle() {
this.width = 0;
this.height = 0;
}
public Rectangle(int xCoord, int yCoord, int width, int height)
{
this.xCoord = xCoord;
this.yCoord = yCoord;
this.width = width;
this.height = height;
}
public void draw(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLACK);
g.fillRect(xCoord, yCoord, width, height);
}
public void erase(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLACK);
g.fillRect(0, 0, 0, 0);
}
}
the circle subclass:
public class Circle extends Figure {
private int radius;
public Circle ()
{
this.radius = 0;
}
public Circle (int xCoord, int yCoord, int radius)
{
this.xCoord = xCoord;
this.yCoord = yCoord;
this.radius = radius;
}
public void draw(Graphics g){
super.paintComponent(g);
g.setColor(Color.BLACK);
g.fillOval(xCoord, yCoord, radius, radius);
}
public void erase(Graphics g){
super.paintComponent(g);
g.setColor(Color.BLACK);
g.fillOval(0,0,0,0);
}
}
the box subclass:
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
public class Box extends Figure {
private int edgeLength;
public Box() {
this.edgeLength = 0;
}
public Box(int xCoord, int yCoord, int edgeLength)// Creating Rectangle
// Class given width and
// height
{
this.xCoord = xCoord;
this.yCoord = yCoord;
this.edgeLength = edgeLength;
}
public void draw(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLACK);
g.fillRect(xCoord, yCoord, edgeLength, edgeLength);
}
public void erase(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLACK);
g.fillRect(0, 0, 0, 0);
}
}
the JPanel class
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.LayoutManager;
import java.awt.Point;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class SamplePanel extends JPanel {
private static final int PANEL_HEIGHT = 400;
private static final int PANEL_WIDTH = 400;
Rectangle rect = new Rectangle(75, 85, 50,30);
Circle circle = new Circle(275, 75, 50);
Box box = new Box (75, 275, 50);
public SamplePanel() {
setPreferredSize(new Dimension(PANEL_HEIGHT, PANEL_WIDTH));
setBackground(Color.WHITE);
//Rectangle rect = new Rectangle(100, 100, 15,10);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
rect.draw(g);
circle.draw(g);
box.draw(g);
g.drawLine(200, 0, 200, 400);
g.drawLine(0, 200, 400, 200);
}
/**
* #param layout
*/
public SamplePanel(LayoutManager layout) {
super(layout);
}
/**
* #param isDoubleBuffered
*/
public SamplePanel(boolean isDoubleBuffered) {
super(isDoubleBuffered);
}
/**
* #param layout
* #param isDoubleBuffered
*/
public SamplePanel(LayoutManager layout, boolean isDoubleBuffered) {
super(layout, isDoubleBuffered);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Window Title Here");
SamplePanel panel = new SamplePanel();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
frame.pack();
frame.setVisible(true);
Figure box = new Box(75, 275, 50);
}
}
Answer...
How to use Swing Timers
It is safe to use within the context of Swing as it won't block the Event Dispatching Thread while waiting and will generate notifications within the context of the Event Dispatching Thread, making it safe to update the UI from.
Observations...
Your basic design, while correct in concept, is implemented in correctly. I'd would strongly discourage you from using JPanel in this way. Components have a particular life cycle which you're not managing correctly, which could cause no end of issues.
Instead, go right back to basics. What is it the shape should be able to?
public interface Figure {
public void draw(Graphics2D g2d);
public Rectangle getBounds();
public void setBounds(Rectangle bounds);
}
Here, it's capable of been painted and has a concept of size and position (yes, you can use an abstract class, but this removes all requirements on the base implementation, making it far more flexible)
Because I imagine most of the implementations are going to be basically the same, I can use an abstract class to implement the core functionality...
public abstract class AbstractFigure implements Figure {
private Rectangle bounds;
#Override
public Rectangle getBounds() {
return bounds;
}
#Override
public void setBounds(Rectangle bounds) {
this.bounds = bounds;
}
}
Based on your needs, you might be able to create a few abstract classes which implement the functionality different, but the basic idea is to see what functionality is common to all the implementations and reduce the amount of duplicate code you generate.
Then you can start implementing your concrete classes...
public class RectangleFigure extends AbstractFigure {
public RectangleFigure(Rectangle bounds) {
setBounds(bounds);
}
#Override
public void draw(Graphics2D g2d) {
g2d.setColor(Color.BLACK);
g2d.fill(getBounds());
}
}
But where's the "erase" method you ask? Well, erase is just the absence of painting, so, when you want to "erase" a shape, remove it from the painting process and repaint the container, shape is erased
This is suggests to me that you need to have a look at Painting in AWT and Swing and Performing Custom Painting to better understand how painting works in Swing.
"Where's the center method?" I hear you ask. Okay, you "could" have a center method in the Figure, the problem is, Figure has no concept of the parent container, is you'd have to pass the size of the container to it. Not difficult, I'd argue, however, this really isn't a function of the Figure, but a function of the container, so I'd have the center method implemented there, since you want to change the position of the Figures anyway, it makes sense (to me) to all that wrapped up in the container

Why Won't the Screen Change Color

I looked and the codes seems fine to me. Got an error but hopefully it's the source code, not something wrong with the cpu I have nor JDK.
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.*;
import javax.swing.JFrame;
public class Game extends Canvas implements Runnable {
public static int width = 300;
public static int height = width / 16*9;
public static int scale = 3;
private Thread thread;
private boolean running = false;
private JFrame frame;
public synchronized void start() {
running = true;
thread = new Thread(this, "Display");
thread.start();
}
public synchronized void stop() {
running = false;
try{
thread.join();
}catch(InterruptedException e){
e.printStackTrace();
}
}
public void run(){
while(running){
tick();
render();
}
}
public void tick() {
}
public void render() {
BufferStrategy bs = getBufferStrategy();
if(bs==null){
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.setColor(Color.black);
g.fillRect(0, 0, getWidth(), getHeight());
bs.dispose();
bs.show();
}
public Game() {
Dimension size = new Dimension(width * scale, height * scale);
setPreferredSize(size);
frame = new JFrame();
}
public static void main(String[] args) {
Game game = new Game();
game.frame.setResizable(false);
game.frame.setTitle("Title");
game.frame.add(game);
game.frame.pack();
game.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
game.frame.setLocationRelativeTo(null);
game.frame.setVisible(true);
game.start();
}
}
Then I got this error, even when I countlessly modified the source code I had.
Exception in thread "Display" java.lang.NullPointerException
at java.awt.Component$BltBufferStrategy.showSubRegion(Component.java:4307)
at java.awt.Component$BltBufferStrategy.show(Component.java:4255)
at com.thecherno.Rain.Game.render(Game.java:58)
at com.thecherno.Rain.Game.run(Game.java:39)
at java.lang.Thread.run(Thread.java:695)
Im starting to seem if it because of an outdated JDK. Current Version I have is JDK 6.
You state:
What Im trying to do is change color as seen in the render method. The background to be black.
Use Swing components such as a JComponent or JPanel.
Simply call setBackground(Color.BLACK) on the component will do.
You appear to be creating a game loop of some type. Consider using a Swing Timer for this.
e.g.,
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Game2 extends JPanel {
private static final int PREF_W = 300;
private static final int PREF_H = PREF_W / 16 * 9;
private static final int SCALE = 3;
private static final Color BACKGROUND = Color.BLACK;
private static final int TIMER_DELAY = 20;
private Timer swingTimer;
public Game2() {
setBackground(BACKGROUND);
swingTimer = new Timer(TIMER_DELAY, new TimerListener());
swingTimer.start();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// TODO: add any custom painting here
}
#Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W * SCALE, PREF_H * SCALE);
}
private class TimerListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
// TODO add code that gets called in game loop
}
}
private static void createAndShowGui() {
Game2 mainPanel = new Game2();
JFrame frame = new JFrame("Game2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Note that this code is based on your stated requirements and what I'm guessing are other requirements based on your code. If there are further requirements not mentioned, please elaborate them for us.
Try using g.dispose(); followed by bs.show(); and then
g = (Graphics2D)bs.getDrawGraphics();. I know it looks weird, but you are emptying the canvas and then refilling it using your strategy. You may also need to do an initial check for g being null and initialize it before the first display loop.

Stop JComponent from repainting when state changes

I'm sure, this is something like a super stupid standard problem, but I spent hours searching and trying to get this fixed, but it just won't work... I just can't find my mistake here...
I'm trying to build a simple program that prints something on a JComponent. The paintComponent()-Method refers to some variables and I want the JComponent ONLY to repaint, if i say so! But it always repaints whenever i change the variables...
Heres the code of my 2 classes:
import java.awt.Dimension;
import javax.swing.*;
public class SimplePaint extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private PaintingCanvas pc;
public SimplePaint() {
super("SimplePaint");
this.pc = new PaintingCanvas();
this.pc.setPreferredSize(new Dimension(800, 600));
this.add(pc);
this.setResizable(false);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.pack();
this.setVisible(true);
this.setLocationRelativeTo(null);
}
public static void main(String[] args) {
SimplePaint sp = new SimplePaint();
sp.pc.setxStart(50);
sp.pc.setyStart(60);
sp.pc.setxEnd(140);
sp.pc.setyEnd(300);
}
}
and
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.*;
public class PaintingCanvas extends JComponent {
/**
*
*/
private static final long serialVersionUID = 1L;
private int xStart, yStart;
private int xEnd, yEnd;
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.fillRect(xStart, yStart, xEnd, yEnd);
}
/**
* #param xStart the xStart to set
*/
public void setxStart(int xStart) {
this.xStart = xStart;
}
/**
* #param yStart the yStart to set
*/
public void setyStart(int yStart) {
this.yStart = yStart;
}
/**
* #param xEnd the xEnd to set
*/
public void setxEnd(int xEnd) {
this.xEnd = xEnd;
}
/**
* #param yEnd the yEnd to set
*/
public void setyEnd(int yEnd) {
this.yEnd = yEnd;
}
}
What it displays: The Canvas with a rectangle (50, 60, 140, 300)...
What is should display: The blank canvas, and if i then put sp.pc.repaint() or something like that in the main method, it should repaint and therefore show the rectangle...
You cannot make any assumption on when and how many times paintComponent will be called. When making the frame visible, it wille be invoked. If you maximize your frame also, etc... There are many situations when paintComponent will be invoked.
The solution is pretty easy:
Add a flag (boolean drawRectangle = false;) on your PaintingCanvas class
In paintComponent check the value of the flag and draw (or not) the rectangle accordingly
When you want the rectangle to appear, toggle the value of the flag

how do i use an image in java gui

Hi im making a Gui programme using a null layout and a setBounds() method for lay out . In the programme I want 25 strings printed out on the screen in random locations . I know that i could do this with a for loop however i have been trying this to no avail.
public void paint(Graphics g){
super.paint(g);
for(i=0;i<25;i++){
g.drawString("string name",Math.random()*250,Math.random()*250);
g.setColor(Color.RED);
}
}
I have been trying this and it has not been working so my question is is there some better way to do this or am i making some sort of obvious mistake.
You are not using the Math.random() part correctly try this instead:
import java.awt.Color;
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
*
* #author David
*/
public class JavaApplication142 extends JFrame {
private int width = 300, height = 300;
public JavaApplication142() {
createAndShowUI();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JavaApplication142 jApp = new JavaApplication142();
}
});
}
private void createAndShowUI() {
setTitle("Painting");
setSize(width, height);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
addComponentsToContentPane(getContentPane());
setVisible(true);
}
private void addComponentsToContentPane(Container contentPane) {
Panel panel1 = new Panel();
contentPane.add(panel1);
}
class Panel extends JPanel {
private Random rand;
public Panel() {
rand = new Random();
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
for (int i = 0; i < 25; i++) {
g.drawString("string name", (int) rand.nextInt(width), (int) rand.nextInt(height));
g.setColor(Color.RED);
}
}
}
}
This will help to get all the strings drawn within the region of the panel, although strings with varying length might go offscreen, just add some extra code to check the length of the string and set its co-ords appropriately

Categories