Processing program works until I add it to a webpage - html

I have this .pde program that works perfectly on the Processing software, but when I add it to a webpage it just doesn't load. If I replace the code with any other .pde program it works fine, so inserting .pde programs in an html file is not the issue. I'm not sure if the problem is that it's not loading the external image and file or what. But here's the full code, thank you in advance!
(I also tried converting it to p5.js but it's just way too complicated and I'm not familiar with it!)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>TITOLO</title>
<script src="processing.js" type="text/javascript"></script>
<link rel="stylesheet" href="css/style1.css">
</head>
<body>
<h1>Titolo – HOME</h1>
<div id="programma">
<script src="https://cdnjs.cloudflare.com/ajax/libs/processing.js/1.6.6/processing.min.js"></script>
<canvas id="pjs"></canvas></div>
<script type="application/processing" data-processing-target="pjs">
final int STAGE_WIDTH = 1200;
final int STAGE_HEIGHT = 950;
final int NB_PARTICLES = 60000;
final float MAX_PARTICLE_SPEED = 5;
final int MIN_LIFE_TIME = 20;
final int MAX_LIFE_TIME = 80;
final String IMAGE_PATH = "starrynight.jpg";
myVector tabParticles[];
float particleSize = 1.2;
PImage myImage;
int imageW;
int imageH;
color myPixels[];
FlowField ff;
GUI gui;
void setup()
{
size(1200, 950, P3D);
background(0);
initializeImage();
initializeParticles();
ff = new FlowField(5);
gui = new GUI(this);
gui.setup();
}
void initializeImage()
{
myImage = loadImage(IMAGE_PATH);
imageW = myImage.width;
imageH = myImage.height;
myPixels = new color[imageW * imageH];
myImage.loadPixels();
myPixels = myImage.pixels;
image(myImage, 0, 0);
}
void setParticle(int i) {
tabParticles[i] = new myVector((int)random(imageW), (int)random(imageH));
tabParticles[i].prevX = tabParticles[i].x;
tabParticles[i].prevY = tabParticles[i].y;
tabParticles[i].count = (int)random(MIN_LIFE_TIME, MAX_LIFE_TIME);
tabParticles[i].myColor = myPixels[(int)(tabParticles[i].y)*imageW + (int)(tabParticles[i].x)];
}
void initializeParticles()
{
tabParticles = new myVector[NB_PARTICLES];
for (int i = 0; i < NB_PARTICLES; i++)
{
setParticle(i);
}
}
void draw()
{
ff.setRadius(gui.getR());
ff.setForce(gui.getF());
particleSize = gui.getS();
float vx;
float vy;
PVector v;
for (int i = 0; i < NB_PARTICLES; i++)
{
tabParticles[i].prevX = tabParticles[i].x;
tabParticles[i].prevY = tabParticles[i].y;
v = ff.lookup(tabParticles[i].x, tabParticles[i].y);
vx = v.x;
vy = v.y;
vx = constrain(vx, -MAX_PARTICLE_SPEED, MAX_PARTICLE_SPEED);
vy = constrain(vy, -MAX_PARTICLE_SPEED, MAX_PARTICLE_SPEED);
tabParticles[i].x += vx;
tabParticles[i].y += vy;
tabParticles[i].count--;
if ((tabParticles[i].x < 0) || (tabParticles[i].x > imageW-1) ||
(tabParticles[i].y < 0) || (tabParticles[i].y > imageH-1) ||
tabParticles[i].count < 0) {
setParticle(i);
}
strokeWeight(1.5*particleSize);
stroke(tabParticles[i].myColor, 250);
line(tabParticles[i].prevX, tabParticles[i].prevY, tabParticles[i].x, tabParticles[i].y);
}
ff.updateField();
}
void mouseDragged() {
if(mouseX>950 && mouseY>830) return;
ff.onMouseDrag();
}
void keyPressed() {
//if (key =='s' || key == 'S') {
// ff.saveField();
//}
}
class myVector extends PVector
{
myVector (float p_x, float p_y) {
super(p_x, p_y);
}
float prevX;
float prevY;
int count;
color myColor;
}
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
class FlowField {
PVector[][] field;
PVector[][] tempField;
int cols, rows;
int resolution;
int affectRadius;
float force;
File file = new File(dataPath("field.txt"));
FlowField(int r) {
resolution = r;
cols = 1200 / resolution;
rows = 950 / resolution;
field = new PVector[cols][rows];
tempField = new PVector[cols][rows];
init();
affectRadius = 3;
force = 1;
}
void setRadius(int r) {
affectRadius = r;
}
void setForce(float f) {
force = f;
}
void init() {
try {
for (int i=0; i<cols; i++) {
for (int j=0; j<rows; j++) {
tempField[i][j] = new PVector(0, 0);
}
}
readField();
}
catch(Exception e) {
for (int i=0; i<cols; i++) {
for (int j=0; j<rows; j++) {
field[i][j] = new PVector(0, 0);
}
}
}
}
PVector lookup(float x, float y) {
int column = int(constrain(x/resolution, 0, cols-1));
int row = int(constrain(y/resolution, 0, rows-1));
return PVector.add(field[column][row],tempField[column][row]);
}
void drawBrush() {
pushStyle();
noFill();
stroke(255, 255, 255);
ellipse(mouseX, mouseY, affectRadius*10, affectRadius*10);
popStyle();
}
void drawField(float x, float y, PVector v) {
int column = int(constrain(x/resolution, 0, cols-1));
int row = int(constrain(y/resolution, 0, rows-1));
for (int i=-affectRadius; i<=affectRadius; i++) {
for (int j=-affectRadius; j<=affectRadius; j++) {
if (i*i+j*j<affectRadius*affectRadius) {
try {
tempField[column+i][row+j].add(v).mult(0.9);
}
catch(Exception e) {
}
}
}
}
}
void updateField(){
for (int i=0; i<cols; i++) {
for (int j=0; j<rows; j++) {
tempField[i][j].mult(0.992);
}
}
}
void onMouseDrag() {
PVector direc = new PVector(mouseX-pmouseX, mouseY-pmouseY).normalize();
drawField(pmouseX, pmouseY, direc.mult(force));
}
void saveField() {
try {
FileWriter out = new FileWriter(file);
for (int i=0; i<cols; i++) {
for (int j=0; j<rows; j++) {
out.write(field[i][j].x+","+field[i][j].y+"\t");
}
out.write("\r\n");
}
out.close();
}
catch(Exception e) {
}
}
void readField() throws IOException {
try {
BufferedReader in = new BufferedReader(new FileReader(file));
String line;
for (int i = 0; (line = in.readLine()) != null; i++) {
String[] temp = line.split("\t");
for (int j=0; j<temp.length; j++) {
String[] xy = temp[j].split(",");
float x = Float.parseFloat(xy[0]);
float y = Float.parseFloat(xy[1]);
field[i][j] = new PVector(x, y);
}
}
in.close();
}
catch(Exception e) {
throw new IOException("no field.txt");
}
}
}
import controlP5.*;
class GUI {
ControlP5 cp5;
Slider sliderR;
Slider sliderF;
Slider sliderS;
GUI(PApplet thePApplet){
cp5 = new ControlP5(thePApplet);
}
void setup(){
cp5.setColorBackground(0x141414);
sliderR = cp5.addSlider("Radius")
.setPosition(980,890)
.setRange(1,20)
.setValue(12).setSize(150,25);
sliderF = cp5.addSlider("Force")
.setPosition(980,918)
.setRange(0.1,0.5)
.setValue(0.3).setSize(150,25);
sliderS = cp5.addSlider("Particle Size")
.setPosition(980,862)
.setRange(0.8,2)
.setValue(1.5).setSize(150,25);
}
int getR(){
return int(sliderR.getValue());
}
float getF(){
return sliderF.getValue();
}
float getS(){
return sliderS.getValue();
}
}
</script>
</body>

Related

I have a problem with a mouseclicked funktion in proccessing

In my main class i have made an array to spawn a few green circles. I tried to get the background to change when i clicked on one of them with a boolean which is supposed to come true when clicking while over the circle... I am new to programming as a whole and I am not really sure how to solve this problem.. I dont really know where the data of the x and y positions of the green circles are displayed and how the klicked function is supposed to find them because all of them are created at random positions and in an other class. So here is my code so far:
class Gesicht {
//Eigenschaften
boolean fail = false;
float whEllipse= 200;
float yPos = random(-whEllipse, height);
float xPos = random(-whEllipse, height);
float xSpeed = 1;
float P = 1;
//Constructor
Gesicht() {
// this.yPos = yPos;
// this.xPos = xPos;
}
//Methoden/Funktionen
void move() {
//paint();
xPos += xSpeed;
yPos += (P*sin(radians(xPos))+1); //+1 macht dass sich das Gesicht langsam runter bewegt.
if (xPos>= width+whEllipse/2) {
// P = P+1; Maybe falls ich größere Amplitude will
xPos = -whEllipse/2;
}
if (yPos >= height+whEllipse/2) {
yPos = random(-whEllipse, height/2);
xPos = random(-200, whEllipse/2);
}
}
boolean klicked() {
if (mouseX > xPos-whEllipse/2 && mouseX < xPos+whEllipse/2
&& mouseY > yPos-whEllipse/2 && mouseY < yPos+whEllipse/2
&& mousePressed) {
return true;
}
return false;
}
void klick() {
if (klicked()) {
fail = true;
}
}
void spawn() {
move();
fill(0, 255, 0);
circle(xPos, yPos, whEllipse);
}
}
this is the class where i tried to put my funktions.
int farbe = 255;
Gesicht[] grün;
Gesichter[] rot;
Gesichterer[] blau;
void settings() {
size(700, 700);
}
void setup() {
rot = new Gesichter[10];
for ( int i = 0; i< rot.length; i++) {
rot[i]= new Gesichter();
}
grün = new Gesicht[15];
for ( int i = 0; i< grün.length; i++) {
grün[i]= new Gesicht();
}
blau = new Gesichterer[20];
for ( int i = 0; i< blau.length; i++) {
blau[i]= new Gesichterer();
}
}
void draw() {
background(farbe);
if(variable.klicked()){
background(150,0,0);
}
for ( int i = 0; i< grün.length; i++) {
grün[i].spawn();
}
for ( int i = 0; i< rot.length; i++) {
rot[i].spawn();
}
for (int i = 0; i< blau.length; i++) {
blau[i].spawn();
}
}
And this is my main class.
The funktion never gets true in the moment... I hope someone can help me ://
Would be very grateful.
You might be trying a bit hard without cleaning up your code which on long run leads to more headaches.
I say based on the following:
you have a klicked() but also a klick() method which doesn't do much: klick() should suffice
You only define a Gesicht class, however you additioanlly attempt to instantiate Gesichter and Gesichterer which don't exist (at least not in the code you posted)
if(variable.klicked()){ background(150,0,0); } refers to an unusuable variable called variable (a placeholder perhaps?). Even if that variable existed, the red background would've only briefly flashed while klicked() was true.
You're very close though:
the klicked() method does what you want
farbe already stores the background colour
You could do something like this:
class Gesicht {
//Eigenschaften
boolean fail = false;
float whEllipse= 200;
float yPos = random(-whEllipse, height);
float xPos = random(-whEllipse, height);
float xSpeed = 1;
float P = 1;
//Constructor
Gesicht() {
// this.yPos = yPos;
// this.xPos = xPos;
}
//Methoden/Funktionen
void move() {
//paint();
xPos += xSpeed;
yPos += (P*sin(radians(xPos))+1); //+1 macht dass sich das Gesicht langsam runter bewegt.
if (xPos>= width+whEllipse/2) {
// P = P+1; Maybe falls ich größere Amplitude will
xPos = -whEllipse/2;
}
if (yPos >= height+whEllipse/2) {
yPos = random(-whEllipse, height/2);
xPos = random(-200, whEllipse/2);
}
}
boolean klicked() {
if (mouseX > xPos-whEllipse/2 && mouseX < xPos+whEllipse/2
&& mouseY > yPos-whEllipse/2 && mouseY < yPos+whEllipse/2
&& mousePressed) {
return true;
}
return false;
}
void klick() {
if (klicked()) {
fail = true;
}
}
void spawn() {
move();
fill(0, 255, 0);
circle(xPos, yPos, whEllipse);
}
}
int farbe = 255;
Gesicht[] green;
Gesicht[] rot;
Gesicht[] blau;
void settings() {
size(700, 700);
}
void setup() {
//rot = new Gesicht[10];
//for ( int i = 0; i< rot.length; i++) {
// rot[i]= new Gesicht();
//}
//green = new Gesicht[15];
//for ( int i = 0; i< green.length; i++) {
// green[i]= new Gesicht();
//}
blau = new Gesicht[20];
for ( int i = 0; i< blau.length; i++) {
blau[i]= new Gesicht();
}
}
void draw() {
background(farbe);
//if (variable.klicked()) {
// background(150, 0, 0);
//}
//for ( int i = 0; i< green.length; i++) {
// if(green[i].klicked()){
// farbe = color(red(farbe), random(255), blue(farbe));
// }
// green[i].spawn();
//}
//for ( int i = 0; i< rot.length; i++) {
// rot[i].spawn();
//}
for (int i = 0; i< blau.length; i++) {
if(blau[i].klicked()){
farbe = color(red(farbe), green(farbe), random(255));
}
blau[i].spawn();
}
}
(Only one array of circles is uncommented for simplicity/easy testing. Feel free to adjust as needed)
One final touch you could add, if you want the background to only change once when you click (as opposed to continously while the mouse is pressed), is debouncing. The idea is to use a state/variable to keep track if the button was previously pressed or not to only chance the background once until the states change again. (You could implement this using an extra boolean variable in your class or perhaps simpler, use the mouseClicked() callback to iterate over your array simply to check which instance has been klicked() to change the background accordingly).

Java Applet_Dubble Buffering Does Not Work

I'm coding a JApplet in Java, but dubble buffering doesn't remove the flickering!?
What should I do?
This is the important part of the code, I guess (tell me if you need to know more, please):
// Background (dubble buffering)
private Image backbuffer;
private Graphics backg;
//Init method
// Dubble-Buffering
backbuffer = createImage(getWidth(), getHeight());
backg = backbuffer.getGraphics();
backg.setColor(this.getBackground());
//Overrided update method
public void update( Graphics g ) {
g.drawImage( backbuffer, 0, 0, this );
getToolkit().sync();
}
I appreciate all help I can get! :)
I made an MCVE to give you a better insight of the problem (thanks to Andrew Thompson)!
"Main"-class:
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.Timer;
public class Test extends JApplet implements ActionListener {
JButton start;
int delay;
Timer tm;
// Falling balls
int n; // Total balls
Ball[] ball; // Array with the balls in
int score;
// The amount of balls falling at the same time (increases by one every
// 10:th score)
int ballNr;
// Comment to the game
String comment;
public void init() {
this.setLayout(null);
this.setSize(600, 500);
this.getContentPane().setBackground(Color.cyan);
this.setFocusable(true);
score = 0;
ballNr = 3;
comment = "Avoid the balls!";
// Buttons
start = new JButton("START");
add(start);
start.setBounds(0, 400, 200, 100);
start.addActionListener(this);
// The timer
delay = 12;
tm = new Timer(delay, this);
// The falling balls
n = 12; // Number of balls in total
ball = new Ball[n];
// Declaring twelve new instances of the ball-object with a
// "reference array"
for (int i = 0; i < n; i++) {
ball[i] = new Ball();
}
}
// Paint-method //
public void paint(Graphics g) {
super.paint(g);
// Every 10:th score, the game adds one ball until you reach 100 =
// win! (ballNr + (int)(score * 0.1) -> ballNr increases by one
// every 10:th score
for (int i = 0; i < ballNr + (int) (score * 0.1); i++) {
// Score can't be higher than 100
if (score < 100) {
g.setColor(ball[i].getCol());
g.fillOval(ball[i].getXLoc(), ball[i].getYLoc(),
ball[i].getSize(), ball[i].getSize());
}
}
// Draw the score and the comment
g.setColor(Color.black);
g.setFont(new Font("Arial", Font.BOLD, 24));
g.drawString("SCORE: " + score, 440, 40);
g.setColor(Color.red);
g.setFont(new Font("Arial", Font.BOLD + Font.ITALIC, 28));
g.drawString(comment, 0, 40);
}
// ACTIONLISTENER //
public void actionPerformed(ActionEvent e) {
if (e.getSource() == start) {
tm.start();
this.requestFocusInWindow(); // Make the runner component have focus
}
// Every 10:th score, the game adds one ball until you reach 100 =
// win! (ballNr + (int)(score * 0.1) -> ballNr increases by one
// every 10:th score
for (int i = 0; i < ballNr + (int) (score * 0.1); i++) {
// Score can't pass 100, because then you have won the game
if (score < 100) {
ball[i].setYLoc(ball[i].getYLoc() + ball[i].getVel());
}
}
// If any ball is out of bounds (then the score increases by one)
for (int i = 0; i < n; i++) {
if (outOfBounds(ball[i])) {
ball[i] = new Ball();
}
}
repaint();
}
// If the ball is out of the screen
public boolean outOfBounds(Ball ball) {
if (ball.getYLoc() >= 500) {
score++;
return true;
} else {
return false;
}
}
// Updates new balls
public void updateBalls() {
for (int i = 0; i < n; i++) {
ball[i] = new Ball();
}
}
}
Sub-class
import java.awt.Color;
import java.util.Random;
public class Ball {
// Private variables
private Random r; // Generating random positions and
// sizes;
private int size; // Size of the ball
private int vel; // Ball velocity
private int nrOfCol; // Color code (see ballColor-method)
private Color col;
private int xLoc;
private int yLoc;
// Constructor
public Ball() {
r = new Random();
size = r.nextInt(40) + 10; // 10px - 50 px
vel = r.nextInt(6) + 1; // Speed btw 1-5 px/delay
nrOfCol = r.nextInt(8) + 1; // Specific nr from 1-9
col = ballColor();
xLoc = r.nextInt(550);
yLoc = 0;}
public Ball(int xPos, int yPos, int size, int vel, Color col) {
this.xLoc = xPos;
this.yLoc = yPos;
this.size = size;
this.vel = vel;
this.col = col;
}
// A method to generate different colors of the balls
public Color ballColor() {
Color col;
switch (nrOfCol) {
case 1:
col = Color.black;
break;
case 2:
col = Color.red;
break;
case 3:
col = Color.green;
break;
case 4:
col = Color.yellow;
break;
case 5:
col = Color.pink;
break;
case 6:
col = Color.magenta;
break;
case 7:
col = Color.white;
break;
case 8:
col = Color.orange;
break;
case 9:
col = Color.blue;
break;
default:
col = Color.black;
// All colors except cyan as it is the background color
}
return col;
}
// Getters & setters
public int getXLoc() {
return xLoc;
}
public int getYLoc() {
return yLoc;
}
public void setYLoc(int y) {
yLoc = y;
}
public int getSize() {
return size;
}
public int getVel() {
return vel;
}
public Color getCol() {
return col;
}
}

Map Route with WCF Services

I have use WCF Services in an app.
I draw the line when going from 1 lists the coordinates returned from WCF. Then draw the wrong path. While Windows Phone 7 displays properly, using Polyline.
Shown below are the results that I got wrong:
And I want to display:
This is the code that I handle to draw:
void wcl_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
try
{
if (string.IsNullOrEmpty(e.Result) || e.Error != null)
{
MessageBox.Show("Lỗi kết nối! Hãy thử lại");
waitingPage.Visibility = System.Windows.Visibility.Collapsed;
return;
}
XuLyToaDo route = XuLyToaDo.TaoMapRoute();
//Lay ds diem ve
string Ketqua = XuLyToaDo.DanhSachDiemVe(e.Result);
string[] kq = Ketqua.Split('&');
//Lay thong tin toa do
XuLyToaDo routePushpin = XuLyToaDo.TaoMapRoute();
XuLyToaDo routePolyline = XuLyToaDo.TaoMapRoute();
//MessageBox.Show(kq[0]);
//MessageBox.Show(kq[1]);
//MessageBox.Show(kq[2]);
//Tao ds toa do
List<GeoCoordinate> lsToaDoPushpin = routePushpin.TaoDSToaDo(kq[0]);
List<GeoCoordinate> lsToaDoRoute = routePushpin.TaoDSToaDo(kq[1]);
// Lay ds ten duong
string[] MangTenDiaChi = routePushpin.TaoDSDuong(kq[2]);
if (lsToaDoPushpin == null)
{
MessageBox.Show("Không có thông tin");
waitingPage.Visibility = System.Windows.Visibility.Collapsed;
return;
}
for (int i = 0; i < lsToaDoPushpin.Count - 1; i++)
{
AddRoute(lsToaDoPushpin[i], Colors.Blue);
}
//ve duong di
for (int i = 0; i < lsToaDoPushpin.Count - 2; i++)
{
AddRouteMap(lsToaDoPushpin[i], lsToaDoPushpin[i + 1]);
}
//ve duong di
//MyRouteQuery = new RouteQuery()
//{
// TravelMode = TravelMode.Driving,
// Waypoints = lsToaDoRoute
//};
//MyRouteQuery.QueryCompleted += MyRouteQuery_QueryCompleted;
//MyRouteQuery.QueryAsync();
//Them danh sach tram
int k = 0;
foreach (GeoCoordinate geo in lsToaDoPushpin)
{
if (k == lsToaDoPushpin.Count() - 1)
break;
Pushpin pus = new Pushpin();
string str = "Direc_" + k;
pus.Template = Maps.App.Current.Resources[str] as ControlTemplate;
pus.Tag = k;
pus.Content = k.ToString() + ". " + MangTenDiaChi[k];
pus.Tap += new EventHandler<System.Windows.Input.GestureEventArgs>(pus_Tap);
MyMap.Layers.Add(new MapLayer()
{
new MapOverlay()
{
GeoCoordinate = geo,
PositionOrigin = new Point(0.5,0.5),
Content = pus
}
});
k++;
}
MyMap.Center = lsToaDoPushpin[0];
MyMap.ZoomLevel = 15;
waitingPage.Visibility = System.Windows.Visibility.Collapsed;
}
catch (Exception ex)
{
MessageBox.Show("Lỗi kết nối. Hãy thử lại!!" + ex.Message);
}
}
private void AddRouteMap(GeoCoordinate g1, GeoCoordinate g2)
{
List<GeoCoordinate> lsRoute = new List<GeoCoordinate>();
lsRoute.Add(g1);
lsRoute.Add(g2);
MyRouteQuery = new RouteQuery()
{
TravelMode = TravelMode.Walking,
Waypoints = lsRoute
};
MyRouteQuery.QueryCompleted += MyRouteQuery_QueryCompleted;
MyRouteQuery.QueryAsync();
}
void MyRouteQuery_QueryCompleted(object sender, QueryCompletedEventArgs<Route> e)
{
if (e.Error == null)
{
if (MyMapRoute != null)
AddlstMapRoute(MyMapRoute);
MyRoute = e.Result;
MyMapRoute = new MapRoute(MyRoute);
MyMap.AddRoute(MyMapRoute);
}
}
private void AddlstMapRoute(MapRoute maproute)
{
lsMapRoute.Add(maproute);
}
private void AddRoute(GeoCoordinate geo, Color color)
{
MyMap.Layers.Add(new MapLayer()
{
new MapOverlay()
{
GeoCoordinate = geo,
PositionOrigin = new Point(0.5,0.5),
Content = new Ellipse
{
Fill = new SolidColorBrush(color),
Width =5,
Height = 5
}
}
});
}
void pus_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
e.Handled = true;
Pushpin pus = sender as Pushpin;
ToolTipService.SetToolTip(pus, new ToolTip()
{
DataContext = pus,
Style = Application.Current.Resources["CustomInfoboxStyle"] as Style
});
MessageBox.Show(pus.Content.ToString(), "Thông tin trạm", MessageBoxButton.OK);
}
This is the place where I create database:
How can I fix this?
i guess its due to the fact that your travelmode is set to walking and google seems to think that walking there isnt allowed, so it takes the next possible way. try change the travelmode to driving or so.
greetings lars

Current date wont update

I have 2 buttons one to log in and the other to log out. I would like both of them to show different times but for some reason unknown to me they do not. and when all the info is saved to a file it says null where there's no information. If there is a way to change that it would be greatly appreciated.
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
public class MainGUI extends JFrame {
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date date = new Date();
String[] columnNames = {"ID", "NAME", "COURSE", "Professor", "Reason for Tutor", "Login Time", "Logout Time"};
Object[][] data = new Object[25][7];
// table
JTable table = new JTable(data, columnNames) {
#Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
JFrame frame, frame1;
JPanel buttonPanel, buttonPanel2, tablePanel, addPanel, editPanel;
JLabel labelID, labelName, labelCourse, labelProfessor, labelHelp, labelDate, labelDate2;
JTextField txtID, txtName, txtCourse, txtProfessor, txtHelp, txtDate, txtDate2;
JButton btnAdd, btnEdit, btnDelete, btnSort, btnSave, btnAddInput, btnCancel;
int keyCode, rowIndex, rowNumber, noOfStudents;
MainGUI.ButtonHandler bh = new MainGUI.ButtonHandler();
public MainGUI() {
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.getSelectionModel().addListSelectionListener(new MainGUI.RowListener());
table.getColumnModel().getColumn(1).setPreferredWidth(150);
table.getColumnModel().getColumn(3).setPreferredWidth(100);
table.getColumnModel().getColumn(4).setPreferredWidth(200);
table.getColumnModel().getColumn(5).setPreferredWidth(150);
table.getColumnModel().getColumn(6).setPreferredWidth(150);
table.getTableHeader().setResizingAllowed(false);
table.getTableHeader().setReorderingAllowed(false);
JScrollPane scrollPane = new JScrollPane(table);
btnAdd = new JButton("Login");
btnAdd.addActionListener(bh);
btnEdit = new JButton("EDIT");
btnEdit.addActionListener(bh);
btnEdit.setEnabled(false);
btnDelete = new JButton("DELETE");
btnDelete.addActionListener(bh);
btnDelete.setEnabled(false);
btnSort = new JButton("Logout");
btnSort.addActionListener(bh);
btnSave = new JButton("SAVE");
btnSave.addActionListener(bh);
btnSave.setActionCommand("Save");
btnAddInput = new JButton("Login");
btnAddInput.addActionListener(bh);
btnAddInput.setActionCommand("AddInput");
btnCancel = new JButton("Cancel");
btnCancel.addActionListener(bh);
labelID = new JLabel("ID");
labelName = new JLabel("NAME");
labelCourse = new JLabel("Course");
labelProfessor = new JLabel("Professor");
labelHelp = new JLabel("Reason for Tutoring");
labelDate = new JLabel("Login");
labelDate2 = new JLabel("Logout");
txtID = new JTextField(20);
txtName = new JTextField(20);
txtCourse = new JTextField(20);
txtProfessor = new JTextField(20);
txtHelp = new JTextField(20);
txtDate = new JTextField(20);
txtDate2 = new JTextField(20);
txtID.setDocument(new MainGUI.JTextFieldLimit(15));
txtID.addKeyListener(keyListener);
tablePanel = new JPanel();
tablePanel.setLayout(new BoxLayout(tablePanel, BoxLayout.PAGE_AXIS));
tablePanel.setBorder(BorderFactory.createEmptyBorder(10, 2, 0, 10));
tablePanel.add(table.getTableHeader());
tablePanel.add(table);
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.ipady = 20;
c.insets = new Insets(10, 10, 10, 10);
c.fill = GridBagConstraints.HORIZONTAL;
buttonPanel.add(btnAdd, c);
c.gridx = 0;
c.gridy = 1;
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 20;
c.insets = new Insets(10, 10, 10, 10);
buttonPanel.add(btnEdit, c);
c.gridx = 0;
c.gridy = 2;
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 20;
c.insets = new Insets(10, 10, 10, 10);
buttonPanel.add(btnDelete, c);
c.gridx = 0;
c.gridy = 3;
c.ipady = 20;
c.insets = new Insets(10, 10, 10, 10);
c.fill = GridBagConstraints.HORIZONTAL;
buttonPanel.add(btnSort, c);
c.gridx = 0;
c.gridy = 4;
c.ipady = 20;
c.insets = new Insets(10, 10, 10, 10);
c.fill = GridBagConstraints.HORIZONTAL;
buttonPanel.add(btnSave, c);
frame = new JFrame("Tutoring Database");
frame.setVisible(true);
frame.setResizable(false);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.add(tablePanel, BorderLayout.CENTER);
frame.add(buttonPanel, BorderLayout.EAST);
frame.pack();
addPanel = new JPanel();
addPanel.setLayout(new GridBagLayout());
c.insets = new Insets(1, 0, 1, 1);
c.gridx = 0;
c.gridy = 0;
addPanel.add(labelID, c);
c.gridy = 1;
addPanel.add(labelName, c);
c.gridy = 2;
addPanel.add(labelCourse, c);
c.gridy = 3;
addPanel.add(labelProfessor, c);
c.gridy = 4;
addPanel.add(labelHelp, c);
c.gridy = 5;
addPanel.add(labelDate, c);
c.gridy = 6;
addPanel.add(labelDate2, c);
// text fields
c.gridx = 1;
c.gridy = 0;
c.ipady = 1;
addPanel.add(txtID, c);
c.gridy = 1;
c.ipady = 1;
addPanel.add(txtName, c);
c.gridy = 2;
c.ipady = 1;
addPanel.add(txtCourse, c);
c.gridy = 3;
c.ipady = 1;
addPanel.add(txtProfessor, c);
c.gridy = 4;
c.ipady = 1;
addPanel.add(txtHelp, c);
c.gridy = 5;
c.ipady = 1;
addPanel.add(txtDate, c);
c.gridy = 5;
c.ipady = 1;
addPanel.add(txtDate2, c);
buttonPanel2 = new JPanel();
buttonPanel2.setLayout(new GridLayout(1, 1));
buttonPanel2.add(btnAddInput);
buttonPanel2.add(btnCancel);
frame1 = new JFrame("Student Database");
frame1.setVisible(false);
frame1.setResizable(false);
frame1.setDefaultCloseOperation(HIDE_ON_CLOSE);
frame1.add(addPanel, BorderLayout.CENTER);
frame1.add(buttonPanel2, BorderLayout.PAGE_END);
frame1.pack();
}// end
KeyListener keyListener = new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
keyCode = e.getKeyCode();
if (!(keyCode >= 48 && keyCode <= 57) && !(keyCode >= 96 && keyCode <= 105)
&& !(keyCode >= 37 && keyCode <= 40) && !(keyCode == 127 || keyCode == 8)) {
txtID.setEditable(false);
}
}
#Override
public void keyReleased(KeyEvent e) {
txtID.setEditable(true);
}
};
class RowListener implements ListSelectionListener {
#Override
public void valueChanged(ListSelectionEvent event) {
if (event.getValueIsAdjusting()) {
rowIndex = table.getSelectedRow();
if (data[rowIndex][0] == null || data[rowIndex][0] == "") {
btnEdit.setEnabled(false);
btnDelete.setEnabled(false);
} else {
btnEdit.setEnabled(true);
btnDelete.setEnabled(true);
}
}
}
}
class ButtonHandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Login")) {
txtID.setText("");
txtName.setText("");
txtCourse.setText("");
txtProfessor.setText("");
txtHelp.setText("");
txtDate.setText(dateFormat.format(date));
frame1.setTitle("Add Student data"); // title bar name for add
frame1.setVisible(true);
} else if (e.getActionCommand().equals("EDIT")) {
txtID.setText(data[rowIndex][0] + "");
txtName.setText(data[rowIndex][1] + "");
txtCourse.setText(data[rowIndex][2] + "");
txtProfessor.setText(data[rowIndex][3] + "");
txtHelp.setText(data[rowIndex][4] + "");
txtDate.setText(data[rowIndex][5] + "");
txtID.setEditable(false);
frame1.setTitle("Edit Student data");
btnAddInput.setActionCommand("Edit2");
btnAddInput.setText("ACCEPT");
frame1.setVisible(true);
} else if (e.getActionCommand().equals("DELETE")) {
int confirm = JOptionPane.showConfirmDialog(frame, "ARE YOU SURE?", "CONFIRM",
JOptionPane.YES_NO_OPTION);
if (confirm == 0) {
rowIndex = table.getSelectedRow();
rowNumber = 0;
noOfStudents--;
for (int i = 0; i <= 10; i++) {
if (rowIndex != i && i <= noOfStudents) {
data[rowNumber][0] = data[i][0];
data[rowNumber][1] = data[i][1];
data[rowNumber][2] = data[i][2];
data[rowNumber][3] = data[i][3];
data[rowNumber][4] = data[i][4];
data[rowNumber][5] = data[i][5];
rowNumber++;
} else if (rowIndex != i && i > noOfStudents) {
data[rowNumber][0] = "";
data[rowNumber][1] = "";
data[rowNumber][2] = "";
data[rowNumber][3] = "";
data[rowNumber][4] = "";
data[rowNumber][5] = "";
rowNumber++;
}
}
if (noOfStudents == 1000) {
btnAdd.setEnabled(false);
}
else {
btnAdd.setEnabled(true);
}
if (noOfStudents == 0) {
btnDelete.setEnabled(false);
btnEdit.setEnabled(false);
} else {
btnDelete.setEnabled(true);
btnEdit.setEnabled(true);
}
rowIndex = table.getSelectedRow();
if (data[rowIndex][0] == null || data[rowIndex][0] == "") {
btnEdit.setEnabled(false);
btnDelete.setEnabled(false);
} else {
btnEdit.setEnabled(true);
btnDelete.setEnabled(true);
}
table.updateUI();
}
} else if (e.getActionCommand().equals("AddInput")) {
if (txtID.getText().isEmpty() || txtName.getText().isEmpty()
|| txtCourse.getText().isEmpty()// /
|| txtProfessor.getText().isEmpty() || txtHelp.getText().isEmpty()) {
JOptionPane.showMessageDialog(null, "PLEASE FILL IN THE BLANKS.", "ERROR!",
JOptionPane.ERROR_MESSAGE);
}
else {
int dup = 0;
for (int i = 0; i < 10; i++) {
if (txtID.getText().equals(data[i][0])) {
JOptionPane.showMessageDialog(null, "ID NUMBER ALREADY EXISTS.", "ERROR!",
JOptionPane.ERROR_MESSAGE);
dup++;
}
}
if (dup == 0) {
rowIndex = table.getSelectedRow();
data[noOfStudents][0] = txtID.getText();
data[noOfStudents][1] = txtName.getText();
data[noOfStudents][2] = txtCourse.getText();
data[noOfStudents][3] = txtProfessor.getText();
data[noOfStudents][4] = txtHelp.getText();
data[noOfStudents][5] = txtDate.getText();
table.updateUI();
frame1.dispose();
noOfStudents++;
if (noOfStudents == 50){
btnAdd.setEnabled(false);
}
else {
btnAdd.setEnabled(true);
}
if (data[rowIndex][0] == null) {
btnEdit.setEnabled(false);
btnDelete.setEnabled(false);
} else {
btnEdit.setEnabled(true);
btnDelete.setEnabled(true);
}
}
}
table.updateUI();
}else if(e.getActionCommand().equals("Save")){
try {
PrintWriter out = new PrintWriter("Tutor.txt");
for(int i = 0; i < 25; i++)
{
for(int j = 0; j < 7; j++)
{
out.print(data[i][j]);
out.print(", ");
if(j == 6){
out.println();
}
} out.flush();
}} catch (FileNotFoundException ex) {
}
} else if (e.getActionCommand().equals("Logout")) {
int confirm = JOptionPane.showConfirmDialog(frame, "ARE YOU SURE?", "CONFIRM",
JOptionPane.YES_NO_OPTION);
if (confirm == 0) {
rowIndex = table.getSelectedRow();
rowNumber = 0;
txtDate2.setText(dateFormat.format(date));
}
}
if (txtID.getText().isEmpty() || txtName.getText().isEmpty()
|| txtCourse.getText().isEmpty() || txtProfessor.getText().isEmpty()
|| txtHelp.getText().isEmpty()|| txtHelp.getText().isEmpty()) {
} else {
data[rowIndex][0] = txtID.getText();
data[rowIndex][1] = txtName.getText();
data[rowIndex][2] = txtCourse.getText();
data[rowIndex][3] = txtProfessor.getText();
data[rowIndex][4] = txtHelp.getText();
data[rowIndex][5] = txtDate.getText();
data[rowIndex][6] = txtDate2.getText();
frame1.dispose();
}
table.updateUI();
}
}
class JTextFieldLimit extends PlainDocument {
private int limit;
JTextFieldLimit(int limit) {
super();
this.limit = limit;
}
JTextFieldLimit(int limit, boolean upper) {
super();
this.limit = limit;
}
#Override
public void insertString(int offset, String str, AttributeSet attr)
throws BadLocationException {
if (str == null) {
return;
}
if ((getLength() + str.length()) <= limit) {
super.insertString(offset, str, attr);
}
}
}
public static void main(String[] args) {
new MainGUI();
}
}
Simple answer withing swimming through your ocean of code, you need to create a new date in your actionPerformed whenever you want to show the updated date
example
public void actionPerforemd(ActionEvent e){
...
date = new Date();
// do something with date
...
}

Add items to hashmap in for loop

I'm trying to put items from a csv file in an hashmap. By adding items I mean categorizing them. The csv is filled with the answers from a question list. So the csv is build up like this:
Person Question
- Do you wear glasses
1 Yes
2 Yes
3 No
4 Sometimes
The next step I would like to do is reading the items and put the answer in the hashmap with the key being the name of the answer and the value with the amount of that certain answer.
The hashmap should look like this with the previous example I gave:
Yes, 2
No, 1
Sometimes, 1
I'm looping right now like this:
for (int j = 0; j < dataPersonList.size(); j++)
{
// looping through the csv
while (t.hasNext ())
{
// looping through the hashmap
Map.Entry me = (Map.Entry)t.next();
if (dataPersonVar.glasses.equals(me.getKey()))
{
// if the item in the csv is the same as the item in the hashmap
hm.put(me.getKey(), me.getValue() =+ 1); // the value gets +1
}
else
{
// a new item is made and gets automatically 1
hm.put(dataPersonVar.glasses,1);
}
}
}
But obviously this doesn't work. I'm a starter with hashmaps but really think the hashmap is the solution for my problem. I'm working in Processing. Does anybody have an idea how to solve this? If I'm not clear enough let me know!
Thanks in advance
Edit:
As requested I hereby post the full code:
import java.util.Iterator;
import java.util.Map;
HashMap hm = new HashMap();
import de.bezier.data.*;
int totalParticipants;
int bgWidth = 1000;
int bgHeight = 1000;
int x;
int eSize = 10;
int opacity = 100;
float xLocation;
float yLocation;
String travelType;
int travelTime;
int border=400;
float dataMinLat=1000;
float dataMaxLat;
float dataMinLon=1000;
float dataMaxLon;
float xLocationMM = (5.17880);
float yLocationMM = (52.22541);
ArrayList dataPersonList = new ArrayList();
ArrayList dataFunctionList = new ArrayList(100);
Point[] pointList = new Point[1000];
float angle;
XlsReader reader;
PImage kaart;
void setup ()
{
textSize(10);
size(bgWidth, bgHeight);
background(0);
noStroke();
smooth();
//kaart = loadImage("map.png");
yLocationMM = 0 - yLocationMM;
reader = new XlsReader( this, "MMdata.xls" ); // assumes file to be in the data folder
totalParticipants = reader.getLastRowNum();
for (int i = 1;i < totalParticipants+1; i++) {
DataPerson dataPerson = new DataPerson();
dataPerson.function = reader.getString(i, 23);
dataPerson.firstName = reader.getString(i, 1);
dataPerson.lastName = reader.getString(i, 2);
dataPerson.glasses = reader.getString(i, 20);
dataPerson.longitude = reader.getFloat(i, 55);
dataPerson.latitude = reader.getFloat(i, 54);
dataPerson.location = reader.getString(i, 8);
dataPerson.ownage = reader.getString(i, 14);
dataPerson.traveltime = reader.getInt(i, 31);
dataPerson.establishment = reader.getString(i, 58);
dataPerson.traveltype = reader.getString(i, 17);
dataPersonList.add(dataPerson);
}
for (int i = 0; i < dataPersonList.size(); i++) {
DataPerson person = (DataPerson) dataPersonList.get(i);
for (int j = 0; j < dataFunctionList.size() + 1; j++) {
DataFunction dataFunction = null;
if (j < dataFunctionList.size())
{
dataFunction = (DataFunction) dataFunctionList.get(j);
}
if (dataFunction != null) {
if (person.function.equals(dataFunction.function)) {
dataFunction.persons.add(person);
dataFunction.amount ++;
break;
}
}
else {
dataFunction = new DataFunction();
dataFunction.function = person.function;
dataFunction.amount = 1;
dataFunction.persons.add(person);
dataFunctionList.add(dataFunction);
break;
}
}
}
for (int i = 0; i < dataPersonList.size(); i++) {
DataPerson dataPersonVar = (DataPerson) dataPersonList.get(i);
if (dataPersonVar.longitude > dataMaxLon) {
dataMaxLon = dataPersonVar.longitude;
}
else if (dataPersonVar.longitude < dataMinLon) {
dataMinLon = dataPersonVar.longitude;
}
if (dataPersonVar.latitude > dataMaxLat) {
dataMaxLat = dataPersonVar.latitude;
}
else if (dataPersonVar.latitude < dataMinLat) {
dataMinLat = dataPersonVar.latitude;
}
}
}
class DataPerson
{
String function;
String firstName;
String lastName;
String glasses;
float longitude;
float latitude;
String location;
String ownage;
int traveltime;
String establishment;
String traveltype;
String fullName()
{
return firstName + " " + lastName;
}
}
class DataFunction
{
String function;
int amount;
ArrayList persons = new ArrayList();
String getPersonNames()
{
String output = "";
for (int i = 0; i < persons.size(); i++) {
DataPerson person = (DataPerson) persons.get(i);
output += person.firstName + "(" + person.glasses + ") ";
}
return output;
}
}
class Point
{
float x;
float y;
}
void draw()
{
background(0);
strokeWeight(2);
x=50;
int xText=80;
int procentGlasses;
noStroke();
pushMatrix();
scale(1.40, 0.89);
//image(kaart, -250, -360);
popMatrix();
for (int i = 0; i < dataPersonList.size(); i++) {
DataPerson dataPersonVar = (DataPerson) dataPersonList.get(i);
if (dataPersonVar != null) {
xLocation = map(dataPersonVar.longitude, dataMinLon, dataMaxLon, border, bgWidth-border);
yLocation = map(dataPersonVar.latitude, dataMinLat, dataMinLat+(dataMaxLon-dataMinLon), border, bgHeight-border);
travelType = (dataPersonVar.traveltype);
noFill();
if (travelType.equals("By car")) {
stroke(0, 0, 255, opacity+100);
}
else if (travelType.equals("By public transport")) {
stroke(255, 0, 0, opacity);
}
else {
stroke(255, opacity);
}
//text(dataPersonVar.firstName, xLocation, yLocation);
noStroke();
strokeWeight(4);
stroke(100, 15);
strokeWeight(2);
}
}
for (int i = 0; i < dataPersonList.size(); i++) {
DataPerson dataPersonVar = (DataPerson) dataPersonList.get(i);
if (dataPersonVar != null) {
xLocation = map(dataPersonVar.longitude, dataMinLon, dataMaxLon, border, bgWidth-200);
yLocation = map(dataPersonVar.latitude, dataMinLat, dataMinLat+(dataMaxLon-dataMinLon), border, bgHeight-200);
noStroke();
fill(255, 200);
ellipse(xLocation, yLocation, eSize, eSize);
//println(dataPersonVar.glasses);
Iterator t = hm.entrySet().iterator(); // Get an iterator
for (int j = 0; j < dataPersonList.size(); j++) {
while (t.hasNext ()) {
Map.Entry me = (Map.Entry)t.next();
println("die in de dataPersonshit is "+dataPersonVar.glasses+". En de andere waarde is "+me.getKey());
if (dataPersonVar.glasses.equals(me.getKey())) {
hm.put(me.getKey(), ((Integer)me.getValue()) + 1);
}
else {
hm.put(dataPersonVar.glasses, 1);
//println("YEAH");
}
}
}
/////////drawing the circle///////////////
angle = ((PI*2)/15*1)/dataPersonList.size()*i;
stroke(255, 100, 50, 50);
noFill();
strokeWeight(3);
pointList[i] = new Point();
pointList[i].x = bgWidth/2+sin(angle)*400; // de punt van x = 400 ( het middelpunt van de cirkel ) + sin((360 graden) / het totaal
pointList[i].y = bgHeight/2+cos(angle)*400;
beginShape();
vertex(xLocation, yLocation);
quadraticVertex((xLocation+pointList[i].x)/2, yLocation, pointList[i].x, pointList[i].y);
endShape();
}
}
}
Unfortunately I can't give you the csv but I hope the code at least helps.
You don't really need to iterate over the map to do what you seem to be trying to do. Here is an example with a similar csv as you have described:
import java.util.Map;
Map<String, Integer> answers = new HashMap<String,Integer>();
//String [] fileInput = loadStrings("question.csv");
String [] fileInput = new String [] {
"1,Yes", "2,No", "3,Yes", "4,Sometimes", "5,Yes", "6,No", "7,No", "8,No"
};
for (int i = 0 ; i < fileInput.length; i++) {
String [] line = split(fileInput[i],",");
String newAnswer = line[1];
if(!answers.containsKey(newAnswer)) answers.put(newAnswer,1);
else answers.put(newAnswer,answers.get(newAnswer)+1);
}
println(answers);