Java Multithreading with GUI (Kind of Traffic Simulator) - java

I need to implement a solution for a narrow bridge and i am new to java threads and gui.
I have three roads and 1 bridge(has two lane).20 Vehicles for each road should be created randomly and should get passed to bridge depending of the light on its road.
But first I just wanna solve an easy issue which is how can i move a car on this road with thread?(Sleep 1 second and move little bit.)
I thought like that:
I have created the roads with simple PaintComponent function override(I am not sure if its gonna be implemented like that too).
Created a road class and a vehicle class which implements runnable.
I created an array of 20 vehicles in Road class and stuck here.
How should I add this to a JPanel and move it right every 1 seconds?
Am I totally wrong about how to implement that problem because i have background on C family ?
My Code:
public class NarrowBridge {
public static void main(String[] args) {
JFrame myFrame = new JFrame();
PanelSetter newPanel = new PanelSetter();
myFrame.add(newPanel);
myFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
myFrame.setSize(600, 600);
myFrame.setTitle("Narrow Bridge Problem ");
myFrame.setLocationRelativeTo(null);//To centralize the jframe.
myFrame.setVisible(true);
}
}
class PanelSetter extends JPanel {
public Road Road1 = new Road(true);
public Road Road2 = new Road(false);
public Road Road3 = new Road(false);
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
//Fixed Roads Drawing.
g.setColor(Color.BLACK);
g.drawLine(50, 100, 200, 100);
g.drawLine(50, 130, 200, 130);
g.setColor(Color.BLACK);
g.drawLine(50, 210, 200, 210);
g.drawLine(50, 240, 200, 240);
g.setColor(Color.BLACK);
g.drawLine(50, 320, 200, 320);
g.drawLine(50, 350, 200, 350);
//Road 1 Light.
if (Road1.getLight()) {
g.setColor(Color.GREEN);
g.fillOval(180, 70, 20, 20);
} else {
g.setColor(Color.RED);
g.fillOval(180, 70, 20, 20);
}
//Road 2 Light.
if (Road2.getLight()) {
g.setColor(Color.GREEN);
g.fillOval(180, 180, 20, 20);
} else {
g.setColor(Color.RED);
g.fillOval(180, 180, 20, 20);
}
//Road 3 Light.
if (Road3.getLight()) {
g.setColor(Color.GREEN);
g.fillOval(180, 290, 20, 20);
} else {
g.setColor(Color.RED);
g.fillOval(180, 290, 20, 20);
}
}
}
Road is just a simple class which only has boolean light and the thing i tried which is vehicle[] vehicles=new vehicle[20].

Finally i solved my problem with the help of Java Applets.
I am able to pass the applet as a parameter and I am calling it's paint() function and updating screen.

Related

EasterEgg in Java

package easteregg;
import java.awt.Graphics;
import javax.swing.JComponent;
import javax.swing.JFrame;
class MyCanvas extends JComponent {
public void paint(Graphics g) {
g.drawOval (100, 20, 110, 160);
}
}
public class EasterEgg {
public static void main(String[] a) {
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setBounds(30, 30, 300, 300);
window.getContentPane().add(new MyCanvas());
window.setVisible(true);
}
}
my problem is i dont know how to put lines inside the oval
i want to make a easterEgg please help me
i have modified the paint method to draw one pattern please check the below code
public void paint(Graphics g) {
g.drawOval (100, 20, 110, 160);
g.drawLine(120, 40, 140, 60);
g.drawLine(140, 60, 150, 40);
g.drawLine(150, 40, 170, 60);
g.drawLine(170, 60, 190,40);
}
and the output is
this is just a hint to draw lines but better to create one method which will draw that pattern form one end to other end of the oval

java turtle graphics and iterations

import java.awt.*;
public class TurtleGraphicsDemo2 {
public static void main(String[] args) {
World worldObj = new World();
Turtle myrtleTheTurtle = new Turtle(0, 0, worldObj);
drawLine(myrtleTheTurtle, Color.RED, 10, 20, 50, 20); //invokes the first drawLine() method
drawLine(myrtleTheTurtle, 100, 150, 50, -45); //invokes the second drawLine() method
drawLine(myrtleTheTurtle, 100, 150, 100, 60); //invokes the second drawLine() method
drawLine(myrtleTheTurtle, Color.BLUE, 10, 40, 100, 40); //invokes the first drawLine() method
}//end of main method
}//end of class
Here is the error:
TurtleGraphicsDemo2.java:19: error: cannot find symbol
drawLine(myrtleTheTurtle, Color.RED, 10, 20, 50, 20);
^
symbol: method drawLine(Turtle,Color,int,int,int,int)
location: class TurtleGraphicsDemo2
My programming teacher gave us this to experiment with but I get a drawLine error, anyone know why? I do not have much experience in Java, only python. If you can fix this, or know of how I can fix it, thank you. If not, thanks for looking anyway :)
You can draw lines only inside a Canvas, using Graphics2D
class MyCanvas extends Canvas {
public MyCanvas () {
setBackground (Color.GRAY);
setSize(300, 300);
}
public void paint (Graphics g) {
Graphics2D g2;
g2 = (Graphics2D) g;
g2.drawString ("It is a custom canvas area", 70, 70);
}
}

Panel wont show in the window

I am trying to start the program with jcheckbox hat selected and rectangle visible then the Rectangle disappears when the checkbox is unselected and repainted as checkbox is selected again. When I run the program and check the box another check box appears or left of the frame.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.*;
public class Head extends JPanel {
JCheckBox hat;
public Head() {
hat = new JCheckBox("Hat");
hat.setSelected(true);
hat.addItemListener(new CheckSelection());
add(hat);
}
class CheckSelection implements ItemListener {
public void itemStateChanged(ItemEvent ie) {
repaint();
}
}
public void paintComponent(Graphics g) {
setForeground(Color.RED);
g.drawOval(110, 100, 100, 100);
g.drawOval(130, 120, 20, 15);
g.drawOval(170, 120, 20, 15);
g.drawLine(160, 130, 160, 160);
g.drawOval(140, 170, 40, 15);
if (hat.isSelected()) {
g.drawRect(100, 90, 120, 10);
}
}
public static void main(String[] args) {
Head head = new Head();
JFrame f = new JFrame();
f.add(head);
f.setSize(400, 400);
//f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
You've broken the paint chain by not calling the paintComponent's super method
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
setForeground(Color.RED);
g.drawOval(110, 100, 100, 100);
g.drawOval(130, 120, 20, 15);
g.drawOval(170, 120, 20, 15);
g.drawLine(160, 130, 160, 160);
g.drawOval(140, 170, 40, 15);
if (hat.isSelected()) {
g.drawRect(100, 90, 120, 10);
} else {
setForeground(Color.RED);
g.drawOval(110, 100, 100, 100);
g.drawOval(130, 120, 20, 15);
g.drawOval(170, 120, 20, 15);
g.drawLine(160, 130, 160, 160);
g.drawOval(140, 170, 40, 15);
}
}
The Graphics context is a shared resource between components, one of the jobs of paintComponent is to prepare the Graphics for painting, typically by filling it with the background color of the component. So failing to call super.paintComponent means that what ever was previously painted to the Graphics context will still be there
See Painting in AWT and Swing and Performing Custom Painting for more details about how painting works in Swing

Removing a circle from JFrame

I am creating a Towers of Hanoi game and have sucedded in printing the shapes with a time delay (that part of the code has been removed while I try to get all the ovals where they are supposed to be) I am wondering how I would go about removing the circle. As you can see I have tried the clearRect(); method but that doesn't work. Is there a way I can set if the method is visible on JPanel since each circle has its own method? I think that would be the easiest way but if anyone has a better idea go for it! Thanks for any help and I have attached my code
package towersofhanoi;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.Object;
/*g.fillOval(60 = horizontal distance , 540= vertical distance, 400 = width, 60 = height) */
public class TowersOfHanoi extends JPanel {
private int clock = 0;
private Color circles = new Color(176, 56, 251);
public static void main(String[] args) {
// Print the shapes and frame
TowersOfHanoi drawRectangle = new TowersOfHanoi();
JFrame frame = new JFrame("Towers of Hanoi");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(drawRectangle);
frame.setSize(1250, 800);
frame.setVisible(true);
Timer timer = new Timer(1000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
drawRectangle.nextFrame();
drawRectangle.repaint();
}
});
timer.setRepeats(true);
timer.start();
}
public void nextFrame() {
clock++;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
frame1(g);
frame2(g);
frame3(g);
frame4(g);
frame5(g);
frame6(g);
frame7(g);
frame8(g);
frame9(g);
}
private Color frame1(Graphics g) {
Color pegs = new Color(251, 129, 56);
g.setColor(pegs);
// peg 1
g.fillRect(250, 300, 25, 450);
// peg 2
g.fillRect(600, 300, 25, 450);
// peg 3
g.fillRect(950, 300, 25, 450);
// bottom
g.fillRect(200, 700, 825, 50);
// create a color for circles
// cirle 7 (Labeled from bottom to top)
g.setColor(circles);
g.fillOval(60, 640, 400, 60);
g.setColor(Color.BLACK);
g.drawOval(60, 640, 400, 60);
return circles;
}
private void frame2(Graphics g) {
// circle 6
g.setColor(circles);
g.fillOval(85, 580, 350, 60);
g.setColor(Color.BLACK);
g.drawOval(85, 580, 350, 60);
}
private void frame3(Graphics g) {
// circle 5
g.setColor(circles);
g.fillOval(110, 520, 300, 60);
g.setColor(Color.BLACK);
g.drawOval(110, 520, 300, 60);
}
private void frame4(Graphics g) {
// circle 4
g.setColor(circles);
g.fillOval(135, 465, 250, 55);
g.setColor(Color.BLACK);
g.drawOval(135, 465, 250, 55);
}
private void frame5(Graphics g) {
// circle 3
g.setColor(circles);
g.fillOval(160, 420, 200, 45);
g.setColor(Color.BLACK);
g.drawOval(160, 420, 200, 45);
}
private void frame6(Graphics g) {
// circle 2
g.setColor(circles);
g.fillOval(185, 380, 150, 40);
g.setColor(Color.BLACK);
g.drawOval(185, 380, 150, 40);
}
private void frame7(Graphics g) {
// circle 1
g.setColor(circles);
g.fillOval(210, 345, 100, 35);
g.setColor(Color.BLACK);
g.drawOval(210, 345, 100, 35);
}
public void frame8(Graphics g) {
g.clearRect(210, 345, 100, 35);
g.setColor(circles);
g.fillOval(560, 665, 100, 35);
g.setColor(Color.BLACK);
g.drawOval(560, 665, 100, 35);
}
public void frame9(Graphics g) {
g.clearRect(185, 380, 150, 40);
g.setColor(circles);
g.fillOval(890, 660, 150, 40);
g.setColor(Color.BLACK);
g.drawOval(890, 660, 150, 40);
}
}
I am wondering how I would go about removing the circle.
The super.paintComponent(...) will clear the painting on the panel so that is all the is needed.
As you can see I have tried the clearRect();
It is not needed (see my comment above), but then you invoke the fillOval(...) and drawOval(...) methods again so the painting is redone. So the code is doing exactly as you asked it to do.
Is there a way I can set if the method is visible on JPanel
You need a Boolean indicator telling the paint method what to do. Something like:
if (paintOval1)
frame1(g);
if (paintOval2)
frame2(g);
Of course that is approach is very brute force and not a very good approach if for say you have 100 circles to paint. The code become too big.
So, instead you should create a custom class that contains four properties (x, y, width, height, isPainted). Then you create an instance of this class for each circle and add the class to an ArrayList. Something like:
ArrayList<CustomClass> circles = new ArrayList<CustomClass>();
circles.add( new CustomClass(60, 640, 400, 60, true) );
circles.add( new CustomClass(85, 580, 350, 60, true) );
Then in the paintCompnent() method your code becomes simpler:
for (CustomClass circle: circles.get)
{
if (circle.isPainted())
{
g.setColor(...);
g.fillOval(circle.getX(), circle,getY(), circle.getWidth(), circle.getHeight());
...
}
}
Finally you would need a method to change the state of painting a circle. Something like:
pubic void setCirclePainted(int circle, Boolean isPainted)
{
CustomClass circle = circles.get(circle);
circle.setPainted( isPainted );
}
So the key for you is to create your "CustomClass" and give it a proper name. Then you need to implement all the getter/setter methods of the class so you can access the properties of the class.
I actually found that the easiest way for me to understand and do was to use else and else if statements to display the shape based on time. Thanks for the other suggestions though!
public void paintComponent(Graphics g) {
super.paintComponent(g);
frame1(g);
frame2(g);
frame3(g);
frame4(g);
if (clock<= 5) {
frame5(g);
}
else if(clock >= 6) {
frame9(g);
}
frame6(g);
frame7(g);
frame8(g);
}

My java applet isn't appearing

I don't know why but nothing is appearing?
I suppose to have a applet of a house.
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.*;
public class color extends JApplet
{
public void init()
{
addMouseListener(new MyMouseListener());
getContentPane().setBackground(Color.white);
}
public class MyMouseListener implements MouseListener
{
public void mouseClicked(MouseEvent e)
{
int x = e.getX();
int y = e.getY();
boolean closeDoors = true;
if(x>330 && x<280 && y>20 && y<20)
{
closeDoors = false;
repaint();
}
}
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) { }
public void mousePressed(MouseEvent e) { }
public void mouseReleased(MouseEvent e) { }
}
public void paint ( Graphics g, boolean closeDoors)
{
super.paint (g);
do
{
g.drawLine (35, 50, 570, 50);
g.drawLine (35, 50, 250, 0);
g.drawLine (250, 0, 570, 50);
g.drawRect (50, 50, 500, 350);
g.fillRect (100, 75, 80, 80);
g.fillRect (400, 75, 80, 80);
g.fillRect (240, 200, 125, 200);
}
while (closeDoors = true);
if (closeDoors = false);
{
g.drawLine (35, 50, 570, 50);
g.drawLine (35, 50, 250, 0);
g.drawLine (250, 0, 570, 50);
g.drawLine (180, 120, 100, 120);
g.drawLine (400, 120, 480, 120);
g.drawLine (140, 75, 140, 160);
g.drawLine (450, 75, 450, 160);
g.drawRect (50, 50, 500, 350);
g.drawRect (100, 75, 80, 80);
g.drawRect (400, 75, 80, 80);
g.drawRect (240, 200, 125, 200);
g.drawOval (330,280, 20, 20);
}
}
}
You are probably looping inside the paint method. It seems like an infinite loop there.
do
{
g.drawLine (35, 50, 570, 50);
g.drawLine (35, 50, 250, 0);
g.drawLine (250, 0, 570, 50);
g.drawRect (50, 50, 500, 350);
g.fillRect (100, 75, 80, 80);
g.fillRect (400, 75, 80, 80);
g.fillRect (240, 200, 125, 200);
} while (closeDoors = true);
I would replace this with:
if (closeDoors = true)
{
g.drawLine (35, 50, 570, 50);
g.drawLine (35, 50, 250, 0);
g.drawLine (250, 0, 570, 50);
g.drawRect (50, 50, 500, 350);
g.fillRect (100, 75, 80, 80);
g.fillRect (400, 75, 80, 80);
g.fillRect (240, 200, 125, 200);
}
I'll try to help get you on the right track :-)
You may already know this, but if your not using an IDE, I recommend using appletviewer to develop your applets instead of with a browser. Just food for thought :-)
First of all, Toader Mihai Claudiu's suggestion is correct. Change
do
{
g.drawLine (35, 50, 570, 50);
g.drawLine (35, 50, 250, 0);
g.drawLine (250, 0, 570, 50);
g.drawRect (50, 50, 500, 350);
g.fillRect (100, 75, 80, 80);
g.fillRect (400, 75, 80, 80);
g.fillRect (240, 200, 125, 200);
}
while (closeDoors = true);
if (closeDoors = false);
{
into
if (closeDoors)
{
g.drawLine (35, 50, 570, 50);
g.drawLine (35, 50, 250, 0);
g.drawLine (250, 0, 570, 50);
g.drawRect (50, 50, 500, 350);
g.fillRect (100, 75, 80, 80);
g.fillRect (400, 75, 80, 80);
g.fillRect (240, 200, 125, 200);
}
else
{
Otherwise, you're going to be painting as long as closeDoors is true. You just need to paint once. Java will ask you to paint again when it has to (for instance, when you call repaint()).
Also, set closeDoors as a member variable. In other words, have:
public class color extends JApplet
{
public boolean closeDoors = false;
And when you switch the value of closeDoors in the click listener, you can simplify it as:
int x = e.getX();
int y = e.getY();
if(x>330 && x<280 && y>20 && y<20)
{
closeDoors = !closeDoors;
repaint();
}
That will, when you click in your specific area, invert the value of closeDoors. In other words, if closeDoors is true, it will be set to false, and vice versa.
Note, your code if(x>330 && x<280 && y>20 && y<20) probably won't work at all, since y cannot be greater than 20 and less than 20 at the same time, ever. I'll let you play with that to figure out what works :-).
Hope this helps.
Just a minor detail, but you should probably call your class Color instead of color to follow Java's standard naming convention, or call it something else if you don't want to clash with java.awt.Color.
Generally, in Swing you should never override the paint() method but instead paintComponent. (I'm not sure about JApplet, though - I would paint instead on a JPanel inside the applet, not the applet itself.)
And no endless loop in your paint-method - it should return quickly, not work eternally, as the Toader already said.
But this is not your problem, seemingly, as you wrote in a comment:
I get Applet not initializing
Add such (important!) information to the question (it has an edit link for a reason, you know).
Your browser should have a Java console somewhere, use it, and look whether there is some error message. Copy this (including the stacktrace, if any) to your question. This could enable us helping you.
(If you are using OpenJDK with the icedTea-Plugin on Linux, look at ~/.icedteaplugin/java.stderr and ~/.icedteaplugin/java.stdout instead, they didn't yet implement the Java console.)
One more problem. You are overloading not actually overriding paint (or paintComponent). Add #Override and the compiler will tell you of your mistake:
#Override public void paint(Graphics g, boolean closeDoors) { // wont compile
Seems like you need a course in debugging. At the very least put some System.err.printlns in and check the Java Console.

Categories

Resources