file_id
int64 1
46.7k
| content
stringlengths 14
344k
| repo
stringlengths 7
109
| path
stringlengths 8
171
|
---|---|---|---|
2,378 | package gr.uoi.cse.taxcalc.gui.dialogs;
import gr.uoi.cse.taxcalc.util.GUIUtils;
import gr.uoi.cse.taxcalc.io.InputSystem;
import org.xml.sax.SAXException;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.xml.parsers.ParserConfigurationException;
import java.awt.Color;
import java.awt.Font;
import java.awt.Rectangle;
import java.io.File;
import java.io.IOException;
import java.util.List;
public class DataImportDialog extends JDialog {
private JList<String> fileList;
private JButton loadDataButton;
private JButton selectAllButton;
private String folderPath;
public DataImportDialog(final String path) {
setResizable(false);
setModalityType(ModalityType.APPLICATION_MODAL);
setType(Type.POPUP);
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setBounds(100, 100, 486, 332);
getContentPane().setLayout(null);
setLocationRelativeTo(null);
setTitle("Αρχεία φόρτωσης δεδομένων");
folderPath = path;
initElements();
initHandlers();
populateFiles();
}
private void initElements() {
JScrollPane scrollPane = GUIUtils.addScrollPane(getContentPane(),
new Rectangle(10, 11, 250, 258));
fileList = new JList<>();
fileList.setForeground(Color.BLUE);
fileList.setFont(new Font("Tahoma", Font.BOLD, 11));
fileList.setVisibleRowCount(100);
scrollPane.setViewportView(fileList);
loadDataButton = GUIUtils.addButton(getContentPane(),
"<html>Φόρτωση δεδομένων<br>" +
"επιλεγμένων αρχείων</html>",
new Rectangle(270, 11, 198, 68)
);
selectAllButton = GUIUtils.addButton(getContentPane(),
"Επιλογή όλων",
new Rectangle(10, 274, 250, 23)
);
}
private void initHandlers() {
setLoadDataHandler();
setSelectAllHandler();
}
private void setLoadDataHandler() {
loadDataButton.addActionListener(e -> {
List<String> filesToLoad = fileList.getSelectedValuesList();
if (filesToLoad.size() == 0) {
JOptionPane.showMessageDialog(null,
"Δεν έχεις επιλέξει αρχείο(α) απο την λίστα.",
"Σφάλμα",
JOptionPane.WARNING_MESSAGE
);
return;
}
String confirmDialogText = "Φόρτωση δεδομένων φορολογούμενων απο τα ακόλουθα αρχεία:\n";
for (String afmInfoFileName : filesToLoad) {
confirmDialogText += afmInfoFileName + "\n";
}
confirmDialogText += "Είστε σίγουρος?";
int dialogResult = JOptionPane.showConfirmDialog(null,
confirmDialogText,
"Επιβεβαίωση",
JOptionPane.YES_NO_OPTION
);
if (dialogResult == JOptionPane.YES_OPTION) {
try {
InputSystem.importTaxpayers(folderPath, filesToLoad);
} catch (IOException e1) {
JOptionPane.showMessageDialog(null,
"Παρουσιάστικε σφάλμα κατά την ανάγνωση των αρχείων.",
"Σφάλμα",
JOptionPane.WARNING_MESSAGE
);
} catch (SAXException | ParserConfigurationException ex) {
JOptionPane.showMessageDialog(null,
"Παρουσιάστικε σφάλμα κατά την αποκοδικοποίηση των αρχείων.",
"Σφάλμα",
JOptionPane.WARNING_MESSAGE
);
}
dispose();
}
});
}
private void setSelectAllHandler() {
selectAllButton.addActionListener(e ->
fileList.setSelectionInterval(0, fileList.getModel().getSize() - 1)
);
}
private void populateFiles() {
File folder = new File(folderPath);
File[] folderFiles = folder.listFiles((dir, name) ->
(name.toLowerCase().endsWith("_info.txt") || name.toLowerCase().endsWith("_info.xml"))
);
DefaultListModel<String> listModel = new DefaultListModel<>();
if (folderFiles != null) {
for (File file : folderFiles) {
if (file.isFile()) {
listModel.addElement(file.getName());
}
}
}
fileList.setModel(listModel);
}
}
| OrfeasZ/MinnesotaTax | src/main/java/gr/uoi/cse/taxcalc/gui/dialogs/DataImportDialog.java |
2,383 | package manage;
import entities.Custvend;
import entities.Roles;
import helpers.HashinUtils;
import helpers.MailSender;
import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.apache.log4j.Logger;
import sessionsBeans.CustvendFacade;
import sessionsBeans.ProductFacade;
import sessionsBeans.UserAddFacade;
@ManagedBean
@RequestScoped
public class CustvendManage implements Serializable {
final static Logger logger = Logger.getLogger(CustvendManage.class);
@NotNull(message = "Συμπληρώστε το όνομα")
private String fname;
@NotNull(message = "Συμπληρώστε το επίθετο")
private String lname;
@NotNull(message = "Συμπληρώστε το ΑΦΜ")
@Size(min = 10, max = 10, message = "Το ΑΦΜ θα πρέπει να έχει 10 αριθμούς")
private String afm;
@Size(min = 2, message = "Το username θα πρέπει να έχει πάνω από2 στοιχεία")
@NotNull(message = "Συμπληρώστε το username")
private String username;
@Size(min = 5, message = "Το password θα πρέπει να έχει πάνω από 5 στοιχεία")
@NotNull(message = "Συμπληρώστε το password")
private String password;
@Size(min = 5, message = "Το password θα πρέπει να έχει πάνω από 5 στοιχεία")
@NotNull(message = "Συμπληρώστε το password")
private String passwordCheck;
@NotNull(message = "Συμπληρώστε το ΤΚ")
@Size(min = 5, max = 5, message = "Το ΤΚ θα πρέπει να έχει 5 αριθμούς")
private String zip;
@NotNull(message = "Συμπληρώστε την Πόλη")
private String city;
@NotNull(message = "Συμπληρώστε την περιοχή")
private String district;
@NotNull(message = "Συμπληρώστε το email")
private String email;
private String jobname;
@NotNull(message = "Συμπληρώστε την Διεύθυνση")
private String address;
@NotNull(message = "Συμπληρώστε τον Αριθμό Τηλεφώνου")
@Size(min = 10, max = 10, message = "O αριθμός τηλεφώνου θα πρέπει να είναι 10 ψηφία")
private String phone;
private Roles rr;
private List<Roles> roles;
private List<Custvend> custvend;
private HttpServletRequest origRequest = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
private StringBuffer url = origRequest.getRequestURL();
@EJB
UserAddFacade userAddFacade;
@EJB
CustvendFacade custvendFacade;
@EJB
ProductFacade productFacade;
@PostConstruct
void init() {
if(logger.isDebugEnabled()){ logger.debug("Init Manage Users"); }
roles = userAddFacade.findRoles();
//
String urlCompare = "/java-e-commerce/web/register.xhtml";
String urtString = url.toString();
if (urlCompare.equals(urtString)) {
roles.remove(0);
}
}
private Map<String, Object> sessionMap = FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
public String editCustvend() {
FacesContext fc = FacesContext.getCurrentInstance();
Map<String, String> params = fc.getExternalContext().getRequestParameterMap();
int categoryId = Integer.parseInt(params.get("custvendid"));
Custvend u = custvendFacade.searchWithID(categoryId);
sessionMap.put("editCustvend", u);
return "/web/custvendEdit.xhtml?faces-redirect=true";
}
public List<Custvend> getAllCustvendData() {
return custvend = custvendFacade.getAllCustvendFromDB();
}
public long chechIfTheVendorAsycToProduct(Custvend custvend) {
return productFacade.chechIfTheVendorAsycToProductFromDB(custvend);
}
public String deleteCustvend(int id) {
if (custvendFacade.deleteCustvendFacadeFromDB(id) == 1) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Ο χρήστης Διαγράφτηκε επιτυχώς"));
} else {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Ο χρήστης<strong>ΔΕΝ</strong> Διαγράφτηκε επιτυχώς"));
}
return "";
}
public String changeStatusCustvend(int status, int id) {
if (custvendFacade.changeStatusCustvendFromDB(status, id) == 1) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Ο χρήστης άλλαξε κατάσταση επιτυχώς"));
} else {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Ο χρήστης άλλαξε <strong>ΔΕΝ</strong> κατάσταση επιτυχώς"));
}
return "";
}
public String changeRgisterCustvend(int register, int id, Custvend custvend) {
if (custvendFacade.changeRegisterCustvendFromDB(register, id) == 1) {
MailSender mailSend = new MailSender();
if (register == 1) {
MailSender.send(custvend.getEmail(), "ezikos.gr Έγκριση Λογαριασμού", "<h3>Ο λογαριασμός σας στο ezikos.gr Εγκρίθηκε</h3> <br/> Για να συνδεθείτε πατήστε <a href=\"/java-e-commerce/web/login.xhtml\">εδώ</a>");
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Ο χρήστης άλλαξε κατάσταση επιτυχώς. Και θα ενημερωθή με email"));
}
} else {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Ο χρήστης άλλαξε <strong>ΔΕΝ</strong> κατάσταση επιτυχώς"));
}
return "";
}
public String insertCustVend() {
Date date = new Date();
HashinUtils hu = new HashinUtils();
Custvend custvend = new Custvend();
custvend.setFname(fname.trim());
custvend.setLname(lname.trim());
custvend.setAfm(afm.trim());
custvend.setUsername(username.trim());
custvend.setZip(zip.trim());
custvend.setDistrict(district.trim());
custvend.setEmail(email.trim());
custvend.setRoleid(rr);
custvend.setCity(city);
custvend.setAddress(address.trim());
custvend.setPhone(phone.trim());
custvend.setJobname(jobname);
custvend.setBallance(0.0f);
custvend.setBallance((float) 0.0);
custvend.setRemarks("");
if (rr.getRoleid() == 1 || rr.getRoleid() == 2) {
custvend.setIsactive((short) 1);
custvend.setRegister(1);
} else {
custvend.setIsactive((short) 0);
custvend.setRegister(0);
}
custvend.setInsdate(date);
custvend.setPasswd(hu.hashPass(password.trim()));
if(logger.isDebugEnabled()){ logger.debug("AM Validation"); }
if (custvend.getRoleid().getRoleid() == 3 && custvend.getAfm() == null) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Εφόσον είσται προμηθευτής θα πρέπει να εισάγεται ΑΦΜ"));
return "";
}
if(logger.isDebugEnabled()){ logger.debug("Password Validation"); }
if (!password.equals(passwordCheck)) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Τα password δεν ταιριάζουν"));
return "";
}
if(logger.isDebugEnabled()){ logger.debug("Phone Validation"); }
if (custvendFacade.checkIfPhoneNumberExists(phone) > 0) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Ο αριθμός τηλεφώνου που δώσατε υπάρχει."));
return "";
}
if(logger.isDebugEnabled()){ logger.debug("Email Validation"); }
if (custvendFacade.checkIfΕmailExists(email) > 0) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Το email που δώσατε υπάρχει."));
return "";
}
if(logger.isDebugEnabled()){ logger.debug("Username Validation"); }
if (custvendFacade.checkIfUserNameExists(username) > 0) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Το username που δώσατε υπάρχει."));
return "";
}
//mhnhmata από το magaebean στην σελίδα
if (custvendFacade.insertCustVendToDB(custvend)) {
if(logger.isDebugEnabled()){ logger.debug("After adding the user"); }
//TODO change url
String urlCompare = "http://localhost:8080/java-e-commerce/web/register.xhtml";
String urtString = url.toString();
//MailSender mailSend = new MailSender();
if(logger.isDebugEnabled()){ logger.debug("url.toString()" + url.toString()); }
if (urlCompare.equals(urtString)) {
if (rr.getRoleid() == 2) {
if(logger.isDebugEnabled()){ logger.debug("User role = 2 "); }
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Ο λογαριασμό σας δημιουργήθηκε επιτυχώς"));
MailSender.send(custvend.getEmail(), "ezikos.gr Δημιουργία Λογαριασμού", "<h3>Ο λογαριασμός σας στο ezikos.gr δημιουργήθηκε επιτυχώς.</h3> <br/> Για να συνδεθείτε πατήστε <a href=\"/java-e-commerce/web/login.xhtml\">εδώ</a>");
return "login";
} else if (rr.getRoleid() == 3) {
if(logger.isDebugEnabled()){ logger.debug("User role = 3 "); }
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Ο λογαριασμό σας δημιουργήθηκε επιτυχώς. Θα σας αποσταλεί email όταν θα ενεργοποιηθεί"));
return "index";
}
} else {
if(logger.isDebugEnabled()){ logger.debug("User role = 1 "); }
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Ο λογαριασμό σας δημιουργήθηκε επιτυχώς"));
return "custvenAll";
}
}
return "";
}
public List<Custvend> getCustvend() {
return custvend;
}
public void setCustvend(List<Custvend> custvend) {
this.custvend = custvend;
}
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;
}
public String getAfm() {
return afm;
}
public void setAfm(String afm) {
this.afm = afm;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPasswordCheck() {
return passwordCheck;
}
public void setPasswordCheck(String passwordCheck) {
this.passwordCheck = passwordCheck;
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
public String getDistrict() {
return district;
}
public void setDistrict(String district) {
this.district = district;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getJobname() {
return jobname;
}
public void setJobname(String jobname) {
this.jobname = jobname;
}
public Roles getRr() {
return rr;
}
public void setRr(Roles rr) {
this.rr = rr;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public List<Roles> getRoles() {
return roles;
}
public void setRoles(List<Roles> roles) {
this.roles = roles;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
| mixaverros88/dockerized-java-e-commerce-app | src/main/java/manage/CustvendManage.java |
2,386 | package com.mgiandia.library.service;
import com.mgiandia.library.LibraryException;
import com.mgiandia.library.domain.Loan;
import com.mgiandia.library.memorydao.LoanDAOMemory;
import com.mgiandia.library.util.Money;
import com.mgiandia.library.dao.*;
/**
* Η υπηρεσία επιστροφής αντιτύπου.
* @author Νίκος Διαμαντίδης
*
*/
public class ReturnService {
/**
* Πραγματοποιεί την επιστροφή ενός αντιτύπου και
* επιστρέφει το τυχόν πρόστιμο που πρέπει να καταβληθεί.
* @param itemNo Ο αριθμός εισαγωγής του αντιτύπου που επιστρέφεται.
* @return Το πρόστιμο που πρέπει να πληρωθεί ή {@code null}
* αν δεν υπάρχει πρόστιμο.
*/
public Money returnItem(int itemNo) {
LoanDAO loanDAO = new LoanDAOMemory();
Money fine = null;
Loan loan = loanDAO.findPending(itemNo);
if (loan == null) {
throw new LibraryException();
}
loan.returnItem();
if (loan.getOverdue() > 0) {
fine = loan.getFine();
}
loanDAO.save(loan);
return fine;
}
}
| diamantidakos/Library | src/main/java/com/mgiandia/library/service/ReturnService.java |
2,410 | package gr.aueb.cf.ch4;
import java.util.Scanner;
/**
* Ένας μικρός βάτραχος θέλει να περάσει ένα ποτάμι.
* Ο frog βρίσκεται στη θέση X και θέλει να φτάσει στη
* θέση Y (ή σε θέση > Y). Ο frog jumps a fixed distance, D.
*
* Βρίσκει τον ελάχιστο αριθμό jumps που ο small frog πρέπει
* να κάνει ώστε να φτάσει (ή να ξεπεράσει) τον στόχο.
*
* Για παράδειγμα, αν έχουμε:
* X = 10
* Y = 85
* D = 30,
*
* τότε ο small frog θα χρειαστεί 3 jumps, γιατί:
* Starts at 10, και μετά το 1ο jump πάει στη θέση 10 + 30 = 40
* Στο 2ο jump, πάει 40 + 30 = 70
* Και στο 3ο jump, 70 + 30 = 100
*/
public class FrogApp {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int startPointX;
int endPointY;
int jump;
int jumpsCount = 0;
System.out.println("Please type X:, Y: and D:");
startPointX = in.nextInt();
endPointY = in.nextInt();
jump = in.nextInt();
for (int i = startPointX; i < endPointY; i = i + jump) {
jumpsCount++;
}
System.out.println("Jumps Count: " + jumpsCount);
}
}
| Mariamakr/codingfactory23a | src/gr/aueb/cf/ch4/FrogApp.java |
2,411 | package gr.aueb.cf.ch4;
import java.util.Scanner;
/**
Ένας μικρός Βάτραχος θέλει να περάσει ένα ποτάμι
ο Frog βρίσκεται στη θέση 'Χ'
και θέλει να φτάσει στη θέση 'Υ'
ή σε θέση μεγαλύτερη από το 'Υ'.
Ο Frog κάνει jump σε fixed distance 'D'.
Βρίσκει τον ελάχιστο αριθμό jumps που ο Frog
πρέπει να κάνει, ώστε να φτάσει στον στόχο του ή
να τον ξεπεράσει.
Π.χ
X = 10
Y = 85
D = 30
Τότε ο Frog θα χρειαστεί 3 jumps
γιατί θα ξεκινήσει απο το 10 και
μετά το πρώτο jump θα παει
στη θέση 10 + 30 = 40, στο
δεύτερο jump πάει 40 + 30 = 70
και στο 3o jump θα πάει 70 + 30 = 100.
*/
public class FrogApp {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int startPoint;
int endPoint;
int jumpDistance;
int countJumps = 0;
System.out.println("Please give us: start point, end point, jumps: ");
startPoint = in.nextInt();
endPoint = in.nextInt();
jumpDistance = in.nextInt();
for (int i = startPoint; i <= endPoint; i = i + jumpDistance) {
countJumps++;
}
System.out.printf("Start Point: %d End Point: %d Jump Distance: %d, countJumps = %d",
startPoint, endPoint, jumpDistance, countJumps);
}
}
| jordanpapaditsas/codingfactory-java | src/gr/aueb/cf/ch4/FrogApp.java |
2,413 | package projects.project04;
import java.util.Arrays;
/**
* Έστω ένας δισδιάστατος πίνακας που περιέχει τα στοιχεία άφιξης και αναχώρησης
* αυτοκινήτων σε μορφή arr[][] = {{1012, 1136}, {1317, 1417}, {1015, 1020}}
* Αναπτύξτε μία εφαρμογή που διαβάζει να εκτυπώνει τον μέγιστο αριθμό
* αυτοκινήτων που είναι σταθμευμένα το ίδιο χρονικό διάστημα. Για παράδειγμα στον
* παραπάνω πίνακα το αποτέλεσμα θα πρέπει να είναι: 2. Το 1ο αυτοκίνητο αφίχθη
* στις 10:12 και αναχώρησε στις 11:36, το 3ο αυτοκίνητο αφίχθη στις 10:15 και
* αναχώρησε στις 10:20. Επομένως, το 1ο και το 3ο αυτοκίνητο ήταν παρόντα το ίδιο
* χρονικό διάστημα.
*/
public class Project04 {
public static void main(String[] args) {
int[][] arr = {{1012, 1136}, {1317, 1417}, {1015, 1020}, {1117, 1330}, {1220, 1400}};
int[][] inOutTime =new int [arr.length*2][2];
int globalSum =0;
int tmpSum=0;
for (int i =0; i < inOutTime.length; i++){
if((i % 2) == 0){
inOutTime[i][0] = arr[i/2][0];
inOutTime[i][1] = 1;
} else {
inOutTime[i][0] = arr[(i -1)/2][1];
inOutTime[i][1] = 0;
}
}
sortedArr(inOutTime);
// for(int[] row: inOutTime){
// System.out.println(row[0] + " "+ row[1] );
// }
for(int i=0; i< inOutTime.length-1; i++){
//
if(inOutTime[i][1]==1){
tmpSum++;
}
if(inOutTime[i][1]==0){
tmpSum--;
}
if (tmpSum > globalSum){
globalSum = tmpSum;
}
}
System.out.printf("Ο μέγιστος αριθμός παρκαρισμένων αμαξιών είναι: %d", globalSum);
}
public static void sortedArr(int[][] arr){
Arrays.sort(arr, (a1, a2) -> (a1[0] - a2[0]));
}
}
| NikolettaIoan/java-advanced-projects | src/projects/project04/Project04.java |
2,414 | package gr.uoa.di.forms.auth;
import org.hibernate.validator.constraints.NotEmpty;
import javax.validation.constraints.Size;
public class EditProviderProfileForm {
@NotEmpty(message = "Το Εμφανιζόμενο Όνομα είναι υποχρεωτικό.")
@Size(max = 255, message = "Το Εμφανιζόμενο Όνομα δεν πρέπει να υπερβαίνει τους {max} χαρακτήρες.")
private String title;
@NotEmpty(message = "Το Τηλέφωνο είναι υποχρεωτικό.")
@Size(max = 255, message = "Το Τηλέφωνο δεν πρέπει να υπερβαίνει τους {max} χαρακτήρες.")
private String phone;
@Size(max = 255, message = "Το Fax δεν πρέπει να υπερβαίνει τους {max} χαρακτήρες.")
private String fax;
@NotEmpty(message = "Η Διεύθυνση είναι υποχρεωτική.")
@Size(max = 255, message = "Η Διεύθυνση δεν πρέπει να υπερβαίνει τους {max} χαρακτήρες.")
private String address;
@NotEmpty(message = "Ο Ταχυδρομικός Κώδικας είναι υποχρεωτικός.")
@Size(max = 20, message = "Ο Ταχυδρομικός Κώδικας δεν πρέπει να υπερβαίνει τους {max} χαρακτήρες.")
private String zipCode;
@NotEmpty(message = "Η Περιοχή είναι υποχρεωτική.")
@Size(max = 255, message = "Η Περιοχή δεν πρέπει να υπερβαίνει τους {max} χαρακτήρες.")
private String region;
@NotEmpty(message = "Η Πόλη είναι υποχρεωτική.")
@Size(max = 255, message = "Η Πόλη δεν πρέπει να υπερβαίνει τους {max} χαρακτήρες.")
private String city;
private String latitude;
private String longitude;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getFax() {
return fax;
}
public void setFax(String fax) {
this.fax = fax;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
} | taggelos/Ompampassas | src/main/java/gr/uoa/di/forms/auth/EditProviderProfileForm.java |
2,417 | package com.example.skinhealthchecker;
/**
//Οντότητα που διαχειρίζεται τις απαραίτιτες πληροορίες που πρέπει να διατηρεί η εφαρμογή κατα την λειτουργεία της
πχ Language:στην οντότητα αυτή υπάρχουν πληροφορίες για την γλώσσα που είναι ενεργή ,
PID :Το ενεργό profile id
PIDCOUnt:Τελευταίο ganarated profile id
idc:Τελευταίο ganarated mole id
Περιλαμβάνονται συναρτίσεις για την εγραφή και ανάγνωση των τιμών
An object that manipulates the necessary information that the application must have
eg Language: this object has information about the language that is active,
PID: Active profile id
PIDCOUnt: Last ganarated profile's s
ididc: next available mole's id
it Includes readings and writings function for the variables
*/
public class Configurations {
//ondotita gia default ruthmiseis ths efarmoghs
// int AGE=0;
// String SEX="Άνδρας";
// boolean HISTORY =false;
// int idc=1000;
boolean Language;
int PID;
int PIDCOUnt;
// int AGE;
// String SEX;
// boolean HISTORY;
int idc;
public Configurations(){}
public Configurations( int IDm ,int PID1,boolean language1 ,int count){
//public Configurations(int AGE1 , String Sex1 ,Boolean History1 , int IDm){
// AGE=AGE1;
// SEX=Sex1;
// HISTORY=History1;
idc=IDm;PID=PID1; Language= language1;PIDCOUnt= count;
}
public boolean GetLanguage(){
return Language;
}
public void SetLanguage(boolean in){
Language=in;
}
public int GetPIDCOUnt(){
return PIDCOUnt;
}
public void PIDCOUntup() {
PIDCOUnt = PIDCOUnt + 1;
}
public void idup() {
idc = idc + 1;
}
public void SetPIDCOUnt( int in){
PIDCOUnt=in;}
public int GetIdM(){
return idc;
}
public void SetIdM( int in){
idc=in;}
////////
public int GetPID(){
return PID;
}
public void PIDup() {
PID = PID + 1;
}
public void SetPID( int in){
PID=in;}
/**
public int GetAge(){
return AGE;
}
public void SetAge(int in){
AGE=in;
}
public void SetGender(String in){
SEX=in;
}
public String GetGender(){
return SEX;}
public boolean GetHistory(){
return HISTORY;
}
public void SetHistory(boolean in){
HISTORY=in;
}
*/}
| litsakis/SkinHealthChecker | skinHealthChecker/src/main/java/com/example/skinhealthchecker/Configurations.java |
2,418 | package gr.aueb.cf.ch3;
import java.util.Scanner;
/**
* Αποφασίζει αν πρέπει να ανάψουν γτα
* φωτα του αυτοκινητου με βαση 3 μεταβλητες
* αν βρεχει ΚΑΙ ταυτοχρονα ισχυει ενα τουλαχιστον αοπο
* ειναι σκοταδι Η τρεχουμε με πανω απο 100
* τις τιμς τις δινει ο χήστης
*/
public class LightsOnApp {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean isRaining = false;
boolean isDark = false;
boolean isRunning = false;
int speed = 0;
boolean lightsOn = false;
final int MAX_SPEED = 100;
System.out.println("Please insert if it's raining(true/false)");
isRaining = in.nextBoolean();
System.out.println("Please insert if it's dark");
isDark = in.nextBoolean();
System.out.println("Please insert car speed (int)");
speed = in.nextInt();
isRunning = (speed > MAX_SPEED);
lightsOn = isRaining && (isDark || isRunning);
System.out.println("Lights on: " + lightsOn);
}
}
| th-am/codingfactory23 | src/gr/aueb/cf/ch3/LightsOnApp.java |
2,420 | package gr.aueb.cf.ch3;
import java.util.Scanner;
/**
* Αποφασίζει αν πρέπει να ανάψουν τα φώτα ενός αυτοκινήτου
* με βάση τρεις μεταβλητές: αν βρέχει ΚΑΙ ταυτόχρονα :
* είναι σκοτάδι ή τρέχουμε
*/
public class LightsOnApp {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean isRaining = false;
boolean isDark = false;
boolean isRunning = false;
int speed = 0;
boolean lightsOn = false;
final int MAX_SPEED = 100;
System.out.println("Please insert if it is raining (true/false): ");
isRaining = in.nextBoolean();
System.out.println("Please insert if it is dark (true/false): ");
isDark = in.nextBoolean();
System.out.println("Please insert car speed (int): ");
speed = in.nextInt();
isRunning = (speed > MAX_SPEED);
lightsOn = isRaining && (isDark || isRunning);
System.out.println("Lights on: " + lightsOn);
}
}
| kyrkyp/CodingFactoryJava | src/gr/aueb/cf/ch3/LightsOnApp.java |
2,422 | package gr.aueb.cf.ch3;
import java.util.Scanner;
/**
*
* Αποφασίζει αν πρέπει να ανάψουν τα φωτά ενός
* αυτοκινήτου με βάση τρεις μεταβλητές :
* αν βρέχει ΚΑΙ ταυτόχρονα ισχύει ενα απο τα
* επόμενα: είναι σκοτίδι Η' τρέχουμε
* (speed > 100). Τις τιμές αυτές τις λαμβάνουμε
* απο το χρηστή.
*/
public class LightsOnApp {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean isRaining = false;
boolean isDark = false;
boolean isRunning = false;
int speed = 0;
boolean lightsOn = false;
System.out.println("Please insert if its raining (true/false): ");
isRaining = in.nextBoolean();
System.out.println("Please insert if it is dark (true/false): ");
isDark = in.nextBoolean();
System.out.println("Please insert car speed: ");
speed = in.nextInt();
isRunning = (speed > 100);
lightsOn = isRaining && (isDark || isRunning);
System.out.println("Lights On: " + lightsOn);
}
}
| jordanpapaditsas/codingfactory-java | src/gr/aueb/cf/ch3/LightsOnApp.java |
2,423 | package gr.aueb.cf.ch3;
import java.util.Scanner;
/**
* Αποφασίζει αν πρέπει να ανάψουν τα φώτα
* ενός αυτοκινήτου με βάση τρεις μεταβλητές:
* αν βρέχει ΚΑΙ ταυτόχρονα ισχύει ένα τουλάχιστον
* από τα επόμενα: είναι σκοτάδι ή τρέχουμε
* (speed > 100). Τις τιμές αυτές τις λαμβάνουμε
* από τον χρήστη (stdin).
*/
public class LightsOnApp {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean isRaining = false;
boolean isDark = false;
boolean isRunning = false;
int speed = 0;
boolean lightsOn = false;
final int MAX_SPEED = 100;
System.out.println("Please insert if it is raining (true/false)");
isRaining = in.nextBoolean();
System.out.println("Please insert if it is dark (true/false)");
isDark = in.nextBoolean();
System.out.println("Please insert car speed (int)");
speed = in.nextInt();
isRunning = (speed > MAX_SPEED);
lightsOn = isRaining && (isDark || isRunning);
System.out.println("Lights On: " + lightsOn);
}
}
| Mariamakr/codingfactory23a | src/gr/aueb/cf/ch3/LightsOnApp.java |
2,426 | package com.mobile.physiolink.ui.doctor;
import android.os.Bundle;
import androidx.activity.OnBackPressedCallback;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;
import com.mobile.physiolink.R;
import com.mobile.physiolink.databinding.FragmentDoctorNewPatientBinding;
import com.mobile.physiolink.model.user.singleton.UserHolder;
import com.mobile.physiolink.service.api.error.Error;
import com.mobile.physiolink.service.dao.PatientDAO;
import com.mobile.physiolink.service.schemas.PatientSchema;
import com.mobile.physiolink.ui.popup.ConfirmationPopUp;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.ArrayList;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
public class DoctorNewPatientFragment extends Fragment
{
private FragmentDoctorNewPatientBinding binding;
private boolean inputError;
private boolean phoneError;
private boolean AmkaError;
private boolean passwordError;
private boolean emailError;
private boolean postalCodeError;
private boolean address_error;
private final ArrayList<TextInputLayout> allInputsLayouts = new ArrayList<>();
private final ArrayList<TextInputEditText> allInputs = new ArrayList<>();
public DoctorNewPatientFragment()
{
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
/* On back button pressed, Go back to patients fragment */
requireActivity().getOnBackPressedDispatcher().addCallback(this, new OnBackPressedCallback(true)
{
@Override
public void handleOnBackPressed()
{
NavController navController = Navigation.findNavController(getActivity(), R.id.container);
navController.navigate(R.id.action_doctorNewPatientFragment_to_doctorPatientsFragment);
}
});
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
// Inflate the layout for this fragment
binding = FragmentDoctorNewPatientBinding.inflate(inflater, container, false);
allInputsLayouts.add(binding.patientNameInputLayout);
allInputs.add(binding.patientNameInput);
allInputsLayouts.add(binding.patientSurnameInputLayout);
allInputs.add(binding.patientSurnameInput);
allInputsLayouts.add(binding.patientCityInputLayout);
allInputs.add(binding.patientCityInput);
allInputsLayouts.add(binding.patientAddressInputLayout);
allInputs.add(binding.patientAddressInput);
allInputsLayouts.add(binding.patientPostalCodeInputLayout);
allInputs.add(binding.patientPostalCodeInput);
allInputsLayouts.add(binding.patientAmkaInputLayout);
allInputs.add(binding.patientAmkaInput);
allInputsLayouts.add(binding.patientPhoneInputLayout);
allInputs.add(binding.patientPhoneInput);
allInputsLayouts.add(binding.patientEmailInputLayout);
allInputs.add(binding.patientEmailInput);
allInputsLayouts.add(binding.patientUsernameInputLayout);
allInputs.add(binding.patientUsernameInput);
allInputsLayouts.add(binding.patientPasswordInputLayout);
allInputs.add(binding.patientPasswordInput);
for(int j =0; j<allInputsLayouts.size(); j++) {
TextInputLayout currentInputLayout = allInputsLayouts.get(j);
TextInputEditText currentInput = allInputs.get(j);
String passwordPattern = "(?=.*\\d)(?=.*[\\{\\.\\}])";
Pattern PasswordRegex = Pattern.compile(passwordPattern);
String emailPattern = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$";
Pattern emailRegex = Pattern.compile(emailPattern);
currentInput.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (currentInput.getText().length() == 0) {
currentInputLayout.setError("Το πεδίο πρέπει να συμπληρωθεί!");
inputError = true;
} else {
currentInputLayout.setError(null);
currentInputLayout.setHelperText(null);
inputError = false;
}
if (currentInputLayout.equals(binding.patientPhoneInputLayout)) {
if (currentInput.getText().length() != 10 && currentInput.getText().length() != 0) {
currentInputLayout.setError("Ο αριθμός πρέπει να έχει 10 ψηφία!");
phoneError = true;
}else {
currentInputLayout.setError(null);
phoneError = false;
}
} else if (currentInputLayout.equals(binding.patientAmkaInputLayout)) {
if (currentInput.getText().length() != 11) {
currentInputLayout.setError("Το ΑΜΚΑ πρέπει να έχει 11 ψηφία!");
AmkaError = true;
} else {
currentInputLayout.setError(null);
AmkaError = false;
}
} else if (currentInputLayout.equals(binding.patientPasswordInputLayout)){
Matcher matcher = PasswordRegex.matcher(binding.patientPasswordInput.getText().toString());
if(!matcher.find()){
currentInputLayout.setError("Ο κωδικός πρέπει να περιέχει τουλάχιστον έναν αριθμό και έναν ειδικό χαρακτήρα '{' ή '.'");
passwordError = true;
} else{
passwordError = false;
currentInputLayout.setError(null);
}
} else if (currentInputLayout.equals(binding.patientEmailInputLayout)) {
Matcher matcher = emailRegex.matcher(binding.patientEmailInput.getText().toString());
if(!matcher.find()){
currentInputLayout.setError("Μη έγκυρο email");
emailError = true;
}else{
emailError = false;
currentInputLayout.setError(null);
}
} else if (currentInputLayout.equals(binding.patientPostalCodeInputLayout)){
if (currentInput.getText().length() != 5) {
currentInputLayout.setError("Ο ταχυδρομικός κώδικας πρέπει να έχει 5 ψηφία!");
postalCodeError = true;
} else {
currentInputLayout.setError(null);
postalCodeError = false;
}
} else if (currentInputLayout.equals(binding.patientAddressInputLayout)){
if(currentInput.getText().toString().length() == 0){
currentInputLayout.setError("Δεν επιτρέπεται κενή διεύθυνση");
address_error = true;
} else {
address_error = false;
currentInputLayout.setError(null);
}
}
}
@Override
public void afterTextChanged(Editable editable) {
}
});
}
binding.saveNewPatientBtn.setOnClickListener(view ->
{
for(int i = 0; i< allInputs.size(); i++){
if(allInputs.get(i).getText().length() == 0){
allInputsLayouts.get(i).setError("Το πεδίο πρέπει να συμπληρωθεί!");
inputError = true;
}
}
if(binding.patientPostalCodeInput.getText().toString().startsWith("0")){
binding.patientPostalCodeInputLayout.setError("Ο ταχυδρομικός κώδικας δεν είναι έγκυρος!");
postalCodeError = true;
}
if(inputError || phoneError || AmkaError || passwordError || emailError || postalCodeError || address_error){
Toast.makeText(getActivity(), "Πρέπει να συμπληρώσετε σωστά όλα τα υποχρεωτικά πεδία", Toast.LENGTH_SHORT).show();
}
else{
ConfirmationPopUp confirmation = new ConfirmationPopUp("Αποθήκευση",
"Είστε σίγουρος για την επιλογή σας;",
"Ναι", "Οχι");
confirmation.setPositiveOnClick((dialog, which) ->
{
PatientSchema schema = new PatientSchema(binding.patientUsernameInput.getText().toString().trim(),
binding.patientPasswordInput.getText().toString().trim(),
binding.patientNameInput.getText().toString().trim(),
binding.patientSurnameInput.getText().toString().trim(),
binding.patientEmailInput.getText().toString().trim(),
binding.patientPhoneInput.getText().toString().trim(),
binding.patientCityInput.getText().toString().trim(),
binding.patientAddressInput.getText().toString().trim(),
binding.patientPostalCodeInput.getText().toString().trim(),
binding.patientAmkaInput.getText().toString().trim(),
UserHolder.doctor().getId());
FragmentActivity context = getActivity();
PatientDAO.getInstance().create(schema, new Callback() {
@Override
public void onFailure(Call call, IOException e) {call.cancel();}
@Override
public void onResponse(Call call, Response response) throws IOException
{
String res = response.body().string();
context.runOnUiThread(() ->
{
if (res.contains(Error.RESOURCE_EXISTS))
{
Toast.makeText(getActivity(), "Το όνομα χρήστη υπάρχει ήδη",
Toast.LENGTH_SHORT).show();
return;
}
Toast.makeText(getActivity(), "Έγινε αποθήκευση Ασθενή!",
Toast.LENGTH_LONG).show();
NavController navController = Navigation.findNavController(getActivity(), R.id.container);
navController.navigate(R.id.action_doctorNewPatientFragment_to_doctorPatientsFragment);
});
}
});
});
confirmation.setNegativeOnClick(((dialog, which) ->
{
Toast.makeText(getActivity(), "Δεν έγινε αποθήκευση!",
Toast.LENGTH_SHORT).show();
}));
confirmation.show(getActivity().getSupportFragmentManager(), "Confirmation pop up");
}
});
return binding.getRoot();
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
}
} | setokk/PhysioLink | app/src/main/java/com/mobile/physiolink/ui/doctor/DoctorNewPatientFragment.java |
2,427 |
package readcsv;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadCSV
{
public static void main(String[] args)
{
// προσοχή στη γραμμή που ακολουθεί πρέπει να βάλετε (στη μεταβλητή csvFile) το
// ακριβές ΔΙΚΟ ΣΑΣ path για το csv αρχείο που θέλετε να ανοίξετε και να διαβάσετε
String csvFile = "C:\\csvfile2.csv";
String line="";
String csvSplitBy = ",";
try (BufferedReader br = new BufferedReader(new FileReader(csvFile)))
{
while ((line = br.readLine()) != null)
{
String[] allStrings = line.split(csvSplitBy);
System.out.println(allStrings[1]);
}
br.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
| bourakis/Algorithms-Data-Structures | Trees/ReadCSV.java |
2,430 | package gr.aueb.cf.ch10;
/*
* Έστω ένας ταξινομημένος πίνακας με επαναλαμβανόμενα στοιχεία. Γράψτε μία
μέθοδο int[] getLowAndHighIndexOf(int[] arr, int key) που να υπολογίζει και να
επιστρέφει τα low και high index ενός πίνακα arr, για ένα ακέραιο key που λαμβάνει
ως παράμετρο.
Γράψτε και μία main() που να βρίσκει το low και high index για τον πίνακα {0, 1, 4, 4,
4, 6, 7, 8, 8, 8, 8, 8}. Για παράδειγμα, αν δώσουμε ως τιμή το 8, θα πρέπει να
επιστρέφει {7, 11}.
Hint. Ελέγξτε αν το key περιέχεται στον πίνακα και σε ποια θέση. Αν ναι, τότε από τη
θέση αυτή μετρήστε τα στοιχεία όσο υπάρχουν στοιχεία με ίδια τιμή και μέχρι να
βρείτε το τέλος του πίνακα.
* */
public class MiniProject05 {
public static void main(String[] args) {
}
}
| Mariamakr/codingfactory23a | src/gr/aueb/cf/ch10/MiniProject05.java |
2,431 | package gr.aueb.cf.ch10;
/*
* Έστω ένας δισδιάστατος πίνακας που περιέχει τα στοιχεία άφιξης και αναχώρησης
αυτοκινήτων σε μορφή arr[][] = {{1012, 1136}, {1317, 1417}, {1015, 1020}}
Αναπτύξτε μία εφαρμογή που διαβάζει και εκτυπώνει τον μέγιστο αριθμό
αυτοκινήτων που είναι σταθμευμένα το ίδιο χρονικό διάστημα. Για παράδειγμα στον
παραπάνω πίνακα το αποτέλεσμα θα πρέπει να είναι: 2. Το 1ο αυτοκίνητο αφίχθη
στις 10:12 και αναχώρησε στις 11:36, το 3ο αυτοκίνητο αφίχθη στις 10:15 και
αναχώρησε στις 10:20. Επομένως, το 1ο και το 3ο αυτοκίνητο ήταν παρόντα το ίδιο
χρονικό διάστημα.
Hint. Με βάση τον αρχικό πίνακα, δημιουργήστε ένα δυσδιάστατο πίνακα που σε
κάθε γραμμή θα περιέχει δύο πεδία int. Στο πρώτο πεδίο θα εισάγεται η ώρα άφιξης
ή αναχώρησης από τον αρχικό πίνακα και στο 2ο πεδίο θα εισάγεται ο αριθμός 1 αν
πρόκειται για άφιξη και 0 αν πρόκειται για αναχώρηση.
Ταξινομήστε τον πίνακα σε αύξουσα σειρά με βάση την ώρα. Στη συνέχεια
υπολογίστε το μέγιστο αριθμό αυτοκινήτων που είναι σταθμευμένα το ίδιο χρονικό
διάστημα με ένα πέρασμα του πίνακα.
* */
public class MiniProject04 {
public static void main(String[] args) {
}
}
| Mariamakr/codingfactory23a | src/gr/aueb/cf/ch10/MiniProject04.java |
2,432 | package gr.aueb.cf.ch10;
/*
* Έστω ένα θέατρο που έχει θέσεις όπου η κάθε θέση περιγράφεται με ένα χαρακτήρα
που είναι η στήλη και ένα αριθμό που είναι η σειρά. Για παράδειγμα η θέση C2
βρίσκεται στην 2η σειρά και 3η στήλη.
Αναπτύξτε ένα πρόγραμμα διαχείρισης θεάτρου με 30 σειρές και 12 στήλες. Πιο
συγκεκριμένα γράψτε μία μέθοδο void book(char column, int row) που να κάνει book
μία θέση αν δεν είναι ήδη booked και μία μέθοδο void cancel(char column, int row)
που να ακυρώνει την κράτηση μία θέσης αν είναι ήδη booked.
Hint. Υποθέστε ότι ο δυσδιάστατος πίνακας που απεικονίζει το θέατρο είναι ένα
πίνακας από boolean, όπου το true σημαίνει ότι η θέση είναι booked και false ότι δεν
είναι booked. Αρχικά όλες οι θέσεις πρέπει να είναι non-booked.
* */
public class MiniProject10 {
public static void main(String[] args) {
}
}
| Mariamakr/codingfactory23a | src/gr/aueb/cf/ch10/MiniProject10.java |
2,436 | package gr.aueb.cf.ch4;
import java.util.Scanner;
/**
* Ο χρήστης έχει 10 ευκαιρίες για να βρει
* ένα μυστικό κλειδί (int). Αν το βρει
* νωρίτερα από τη 10η φορά, η for θα πρέπει
* να σταματήσει (break)
*/
public class FindTheSecretApp {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
final int SECRET_KEY = 12;
int num;
boolean found = false;
for (int i = 1; i <= 10; i++) {
System.out.println("Please make a guess:");
num = in.nextInt();
if (num == SECRET_KEY) {
found = true;
break;
}
}
if (!found) {
System.out.println("No worries, try again you looser!");
System.exit(1);
}
System.out.println("Success! Play again!");
}
}
| Mariamakr/codingfactory23a | src/gr/aueb/cf/ch4/FindTheSecretApp.java |
2,437 | package gr.aueb.cf.ch4;
import java.util.Scanner;
/**
* Ο χρήστης έχει 10 ευκαιρίες
* για να βρει ένα μυστικό κλειδί.
* Αν το βρει νωρίτερα από τη 10η φορά
* η for θα πρέπει να σταματήσει (break)
*/
public class FindTheSecretApp {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
final int SECRET_KEY = 12;
int num;
boolean found = false;
for (int i = 1; i <= 10; i++) {
System.out.println("Please make a guess: ");
num = in.nextInt();
if (num == SECRET_KEY) {
found = true;
break;
}
}
if (!found) {
System.out.println("No worries, try again!!");
System.exit(1);
}
System.out.println("Success! Play again!");
}
}
| kyrkyp/CodingFactoryJava | src/gr/aueb/cf/ch4/FindTheSecretApp.java |
2,438 | package mvc.com.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import mvc.com.bean.EmpInfo;
import mvc.com.dao.AcceptRejectDAO;
import mvc.com.dao.EmployeeGoalInfoDao;
/**
* Servlet implementation class ApproveRejectRegistrations
*/
@WebServlet("/ApproveRejectRegistrations")
public class ApproveRejectRegistrations extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
String userSession = (String) session.getAttribute("username");
System.out.println("Session: " + userSession);
String operation = request.getParameter("operation");
System.out.println("Operation: " + operation);
AcceptRejectDAO acceptDao = new AcceptRejectDAO();
String successMessage = "Η αποδοχή εγγραφών πραγματοποιήθηκε με επιτυχία!";
String[] inactiveEmployees = request.getParameterValues("inactiveEmployeesCBOX");
String[] inactiveManagers = request.getParameterValues("inactiveManagersCBOX");
if(userSession.equals("admin")){
if(operation.trim().equalsIgnoreCase("ΕΓΚΡΙΣΗ")){
if(inactiveEmployees != null && inactiveManagers != null){
acceptDao.acceptEmployees(inactiveEmployees);
acceptDao.acceptManagers(inactiveManagers);
request.setAttribute("editSuccessMessage", successMessage);
}
else if(inactiveEmployees != null){
acceptDao.acceptEmployees(inactiveEmployees);
request.setAttribute("editSuccessMessage", successMessage);
}
else if(inactiveManagers != null){
acceptDao.acceptManagers(inactiveManagers);
request.setAttribute("editSuccessMessage", successMessage);
}
else if(inactiveEmployees == null && inactiveManagers == null){
request.setAttribute("message", "Πρέπει να επιλέξετε έναν ή περισσότερους εργαζόμενους για να συνεχίσετε.");
}
else{
request.setAttribute("editFailMessage", "Η αποδοχή εγγραφών απέτυχε!");
}
}
request.getRequestDispatcher("/acceptRejectRegistrations.jsp").forward(request, response);
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
| Evrydiki/TrackingEvaluationBonusSystem | src/mvc/com/controller/ApproveRejectRegistrations.java |
2,439 | package gr.aueb.cf.ch4;
import java.util.Scanner;
/**
* Ο χρήστης έχει 10 ευκαιρίες για να
* βρει ενα μυστικό κλειδί (αριθμό)
* Αν το βρει νωρίτερα απο τη 10η φορά
* η for θα πρέπει να σταματήσει (break).
*/
public class JavaSecretGameApp {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
final int SECRET_KEY = 12;
int num;
boolean found = false;
for (int i = 1; i <= 10; i++) {
System.out.println("Please make a guess: ");
num = in.nextInt();
if (num == SECRET_KEY) {
found = true;
break;
}
}
if (!found) {
System.out.println("No worries, play again.");
System.exit(1);
}
System.out.println("Success! Play again!");
}
}
| jordanpapaditsas/codingfactory-java | src/gr/aueb/cf/ch4/JavaSecretGameApp.java |
2,440 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package johnandannandjerry;
import java.util.ArrayList;
import java.util.List;
import johnandannandjerry.models.Cat;
import johnandannandjerry.models.House;
import johnandannandjerry.models.Human;
import johnandannandjerry.models.Mammal;
import johnandannandjerry.models.Mouse;
/**
*
* @author mac
*/
public class JohnAndAnnAndJerry {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// Mammal john = new Human(); // CORRECT
/*
Έστω οτι ο Γιάννης έχει ένα σπίτι.
Το σπίτι χωρίζεται στο κεντρικό μέρος που μένει και την αυλή.
Για να πάει κάποιος στην αυλή πρέπει να ανοίξει μια πόρτα από το εσωτερικό του σπιτιού.
Στο σπίτι μαζί με τον Γιάννη μένει και η γάτα του που λέγεται Άννα.
Κάποια στιγμή ο Γιάννης ανοίγει την μεσόπορτα και η Άννα τρέχει στον κήπο.
Ξαφνικά ο Γιάννης συνειδητοποιεί οτι η Άννα σταμάτησε ξαφνικά και κοιτάζει επίμονα προ μια κατεύθυνση.
Πλησιάζει στην μεσόπορτα ο Γιάννης και βλέπει την Άννα να κοιτάζει ένα ποντίκι τον Τζέρυ.
Ο Τζέρυ κοιτάζει την Άννα και ξεκινάει και τρέχει.
*/
Human john = new Human();
john.setName("John");
Mammal anna = new Cat();
anna.setName("Anna");
Mammal jerry = new Mouse();
jerry.setName("Jerry");
List<Mammal> mammals = new ArrayList<>();
mammals.add(john);
mammals.add(anna);
mammals.add(jerry);
House house = new House("John's House", mammals);
john.opensDoor(house.getGarden().getDoor());
}
}
| davidoster/JohnAndAnnAndJerry | src/johnandannandjerry/JohnAndAnnAndJerry.java |
2,443 | public class StudentsLinkedList extends LinkedList {
public boolean nodeExist(int item) { // Υπέρβαση της μεθόδου της γονικής κλάσης
if (this.isEmpty())
throw new ListEmptyException(MSG_LIST_EMPTY);
Node tmpNode = this.getFirstNode();
while (tmpNode != null)
if (((Student)tmpNode.getItem()).getAM() == item)
return true;
else
tmpNode = tmpNode.getNext();
return false;
} // End of function: nodeExist()
public Object minOfList() { // Υπέρβαση της μεθόδου της γονικής κλάσης
if (this.isEmpty())
throw new ListEmptyException(MSG_LIST_EMPTY);
Object min = this.getFirstNode().getItem();
Node position = this.getFirstNode().getNext();
while (position != null) {
if ((((Student)min).compareTo(position.getItem()) > 0)) // <--- Αλλαγή στο casting στον τύπο αντικειμένου που μας ενδιαφέρει (προεπιλεγμένο: String)
min = position.getItem();
position = position.getNext();
}
return min;
} // End of function: minOfList()
public Object maxOfList() { // Υπέρβαση της μεθόδου της γονικής κλάσης
if (this.isEmpty())
throw new ListEmptyException(MSG_LIST_EMPTY);
Object max = this.getFirstNode().getItem();
Node position = this.getFirstNode().getNext();
while (position != null) {
if ((((Student)max).compareTo(position.getItem()) < 0)) // <--- Αλλαγή στο casting στον τύπο αντικειμένου που μας ενδιαφέρει (προεπιλεγμένο: String)
max = position.getItem();
position = position.getNext();
}
return max;
} // End of function: maxOfList()
public Object minGradeOfList() { // Πρέπει να επιστρέφει τον σπουδαστή και όχι μόνο τον βαθμό του
if (this.isEmpty())
throw new ListEmptyException(MSG_LIST_EMPTY);
double minGrade = ((Student)this.getFirstNode().getItem()).getVathmos(); // <--- Αλλαγή στο casting στον τύπο αντικειμένου που μας ενδιαφέρει (προεπιλεγμένο: Δεν χρειάζεται casting)
Object minStudent = this.getFirstNode().getItem();
Node position = this.getFirstNode().getNext();
while (position != null) {
if ((((Comparable<Double>)minGrade).compareTo(((Student)position.getItem()).getVathmos()) > 0)) {// <--- Αλλαγή στο casting στον τύπο αντικειμένου που μας ενδιαφέρει (προεπιλεγμένο: String)
minGrade = ((Student) position.getItem()).getVathmos();
minStudent = position.getItem();
}
position = position.getNext();
}
return minStudent;
} // End of function: minGradeOfList()
public Object maxGradeOfList() { // Πρέπει να επιστρέφει τον σπουδαστή και όχι μόνο τον βαθμό του
if (this.isEmpty())
throw new ListEmptyException(MSG_LIST_EMPTY);
double maxGrade = ((Student)this.getFirstNode().getItem()).getVathmos(); // <--- Αλλαγή στο casting στον τύπο αντικειμένου που μας ενδιαφέρει (προεπιλεγμένο: Δεν χρειάζεται casting)
Object maxStudent = this.getFirstNode().getItem();
Node position = this.getFirstNode().getNext();
while (position != null) {
if ((((Comparable<Double>)maxGrade).compareTo(((Student)position.getItem()).getVathmos()) < 0)) { // <--- Αλλαγή στο casting στον τύπο αντικειμένου που μας ενδιαφέρει (προεπιλεγμένο: String)
maxGrade = ((Student) position.getItem()).getVathmos();
maxStudent = position.getItem();
}
position = position.getNext();
}
return maxStudent;
} // End of function: maxGradeOfList()
public Object[] minMaxGradeOfList() { // Επιστρέφει πίνακα δυο θέσεων που περιέχει την ελάχιστη και μέγιστη τιμή που θα βρει στη λίστα
if (this.isEmpty())
throw new ListEmptyException(MSG_LIST_EMPTY);
Object[] minMax = new Object[2];
minMax[0] = this.minGradeOfList();
minMax[1] = this.maxGradeOfList();
return minMax;
} // End of function: minMaxGradeOfList()
}
| panosale/DIPAE_DataStructures_3rd_Term | Askisi3.4/src/StudentsLinkedList.java |
2,444 | package com.example.skinhealthchecker;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static android.graphics.Color.RED;
/**
* Ο διαχειριστής των προφίλ ! Ο χρήστης μπορεί να φτιάξει , επιλέξει διαγράψει κάποιο προφίλ .
*
*
*
* The profile manager! The user can make, choose to delete a profile.
*/
public class Users extends Activity implements
CompoundButton.OnCheckedChangeListener {
String TAG;
DatabaseHandler db; // db handler
// TabHost tabHost;
// private Spinner profil ;
private EditText profilname ; // the text input for profile name
private EditText name ;// the text input for user name
private EditText age ;// the text input for user age
private EditText mail ;// the text input for user mail
private EditText phone ;// the text input for user phone number
private Spinner spinner2 ;// spinner that shows saved profiles
private TextView text;// textview that will show a message to user if fills something wrong
private Spinner fullo; // spinner that shows the gender list
private boolean history;
public void onCreate(Bundle savedInstanceState) {
history =false; //on creating profile the bad history will be false by default
TAG = "RESULTS";
Log.i(TAG, "onCreate");
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();// getting intent extras -> but there is no extras here
db = new DatabaseHandler(this);// link the database to handler
Configurations def = db.getDEf(); //gets apps configurations
if (def.GetLanguage())//load the actives language xml
setContentView(R.layout.account);
else
setContentView(R.layout.accounten);
TabHost host = (TabHost)findViewById(R.id.tabHost);// link the the xml contents
host.setup();
// profil = (Spinner) findViewById(R.id.spinner2);
profilname = (EditText) findViewById(R.id.profilname);
name = (EditText) findViewById(R.id.name);
age = (EditText) findViewById(R.id.age);
mail = (EditText) findViewById(R.id.mail);
phone = (EditText) findViewById(R.id.phone);
text= (TextView) findViewById(R.id.textView);
spinner2=(Spinner) findViewById(R.id.spinner2);
// mylist=(ListView)findViewById(R.id.mylist);
// spinnerArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, GetCreatedNames()); //selected item will look like a spinner set from XML
fullo = (Spinner) findViewById(R.id.spinnersex);
//Tab 1
TabHost.TabSpec spec;
if (def.GetLanguage()) {// sets the two tabs using correct active language
spec = host.newTabSpec("Προφίλ");
spec.setContent(R.id.baseone);
spec.setIndicator("Προφίλ");
host.addTab(spec);
//Tab 2
spec = host.newTabSpec("Νέο");
spec.setContent(R.id.basetwo);
spec.setIndicator("Νέο Προφίλ");
host.addTab(spec);
}else
{ spec = host.newTabSpec("Profil");
spec.setContent(R.id.baseone);
spec.setIndicator("Profile");
host.addTab(spec);
//Tab 2
spec = host.newTabSpec("New");
spec.setContent(R.id.basetwo);
spec.setIndicator("New profile");
host.addTab(spec);
}
Button captureButtonU = (Button) findViewById(R.id.gotomain);// on select profile button
captureButtonU.setFocusable(true);
//captureButton.setFocusableInTouchMode(true);
captureButtonU.requestFocus();
captureButtonU.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//
int id=GetSelectedId(String.valueOf(spinner2.getSelectedItem())); // gets the spinner id
if (id>-1) { //if there is no error
Configurations def = db.getDEf(); // gets latest instance of configuration
//String [] profnames = GetCreatedNames();
// String name = profnames[id];
Log.d("profname",db.getProfile(def.GetPID()).GetProfilname());
// Profile pr= db.getProfilebyname(name);
def.SetPID(id); // set the selected id to configurations
db.updateDef(def); // updates configuration
}
Intent intentU = new Intent(getApplicationContext(), CameraActivity.class);// goes to start screen
startActivity(intentU);
//
}
});
Button captureButtonU2 = (Button) findViewById(R.id.save);// saves new profile button
captureButtonU2.setFocusable(true);
//captureButton.setFocusableInTouchMode(true);
captureButtonU2.requestFocus();
captureButtonU2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (
age.getText().toString().isEmpty()||
String.valueOf(fullo.getSelectedItem()).isEmpty()||
name.getText().toString().isEmpty()||
profilname.getText().toString().isEmpty()||
mail.getText().toString().isEmpty()
// || phone.getText().toString().isEmpty()
)// if all data filled (except phone number )
{// prints error
text.setText("Εισάγετε τα στοιχεία του νέου προφίλ σας." +
"\nΠρέπει να συμπληρώσετε όλα τα στοιχεία \n πριν προχωρήσετε !!!!", TextView.BufferType.EDITABLE);
text.setTextColor(RED);
getWindow().getDecorView().findViewById(R.id.base).invalidate();
} else if (( mail.getText().toString().indexOf('@')<1)||(mail.getText().toString().indexOf('@')>=mail.getText().toString().length()-1))
{// if mail is not in right shape shows error
text.setText("Εισάγετε τα στοιχεία του νέου προφίλ σας." +
"\n Το e-mail που δώσατε δεν πρέπει να είναι σωστό !!!!", TextView.BufferType.EDITABLE);
text.setTextColor(RED);
getWindow().getDecorView().findViewById(R.id.base).invalidate();
}
else {
String string = mail.getText().toString();
Pattern pattern = Pattern.compile("([@])");// checks if there is more than one @ in mail
Matcher matcher = pattern.matcher(string);
int count = 0;
while (matcher.find()) count++;
if (count>1) { // if there is many @ prints error
text.setText("Εισάγετε τα στοιχεία του νέου προφίλ σας." +
"\n Το e-mail που δώσατε δεν πρέπει να είναι σωστό !!!!", TextView.BufferType.EDITABLE);
text.setTextColor(RED);
getWindow().getDecorView().findViewById(R.id.base).invalidate();
}else { //if all seems to be right
int id = CreateNewProfile(); // creates new profile
Configurations def = db.getDEf();// gets Configurations instance and activates new id
def.SetPID(id);//
db.updateDef(def);
Intent intentU = new Intent(getApplicationContext(), CameraActivity.class);// go back to start screen
startActivity(intentU);
}
}
}
});
Button captureButtonD = (Button) findViewById(R.id.deleteprofil); // if delete button pressed
captureButtonD.setFocusable(true);
//captureButton.setFocusableInTouchMode(true);
captureButtonD.requestFocus();
captureButtonD.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//
int id;
try{
id=GetSelectedId(String.valueOf(spinner2.getSelectedItem()));} // gets the selected profiles id
catch(NullPointerException e) {
id=0;
}
Log.d("id", Integer.toString(id));
if (id>0) { // if the id is found and there is not the default id (id 0 )
Configurations def = db.getDEf();// gets the configuration
def.SetPID(0); /// set the defaults profile as active
db.updateDef(def);// update configurations
db.deleteProfile(db.getProfile(id));// delete the profile having the id
finish(); // restarts the intent
startActivity(getIntent());
}
}
});
if (db.getProfileCount()>1) {// if there is more profiles except the defaults
ArrayAdapter<String>
spinnerArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, GetCreatedNames()); //selected item will look like a spinner set from XML
// fill the ArrayAdapter with profile names
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(spinnerArrayAdapter);// link the array adapter to spinner
spinner2.setSelection(Getpos()); // sets the active profile as selected
getWindow().getDecorView().findViewById(R.id.baseone).invalidate();//updates grafics
}
}
/*
this function is the checkbutton listener
// on change condition event get as input the id of checkbox which changed
// and the new condition and updates the correct static var .
*/
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) { // if checked sets true
switch (buttonView.getId()) {
case R.id.history:
history = true;
//do stuff
break;
}
}
else
{ switch (buttonView.getId()) {// if not sets false
case R.id.history:
history = false;
//do stuff
break;
}
}}
/*
This function creates a new profile filling it with data that user gave
it returns the id of new profile
*/
public int CreateNewProfile( ){
Configurations def=db.getDEf();// gets the app latest configurations
def.PIDCOUntup(); // creates new id
def.SetPID(GetNewId(def)); //sets the new id to configurations
Profile last = new Profile(); // crates a new instance of profile
db.updateDef(def); // updates the db
Log.d("new profiles id is = ",Integer.toString(GetNewId(def)));
last.SetAge(Integer.parseInt(age.getText().toString()));// fills profile last with data
last.SetIdM(GetNewId(def));
last.SetSex(String.valueOf(fullo.getSelectedItem()));
last.SetHistory(history);
last.SetName(name.getText().toString());
last.SetProfilname(profilname.getText().toString());
last.SetMail(mail.getText().toString());
last.SetPhone(phone.getText().toString());
db.addprofile(last); // adds last to db
// Molestest(last);
return last.GetIdM(); // returns the id
}
public int GetNewId( Configurations def) { // gets the latest id from db
int id = def.GetPIDCOUnt();
return id;
}
/*
this function gets the name of profile as input , finds its id and returns it
*/
public int GetSelectedId(String in ){
List<Profile> myList = new ArrayList<Profile>();
myList =db.getAllProfiles();// get all profiles stored in db
int out=-1;//init
for(int i=myList.size()-1;i>=0;i--){
if (myList.get(i).GetProfilname().equals(in)) { // if the name match any profile name
out = myList.get(i).GetIdM(); //gets its id
break;
}
}
return out;
}
/*
The function GetCreatedNames returns all profile names that is stored in db
in backwards order
*/
public String [] GetCreatedNames( ){
List<Profile> myList = new ArrayList<Profile>();
myList =db.getAllProfiles(); // gets all profiles
String names [] = new String[myList.size()];
int count =0;
for(int i=myList.size()-1;i>=0;i--){
//
names[count]=myList.get(count).GetProfilname();//saves profile names backwards
count++;// names counter
}
return names;
}
/*
The function Getpos returns the position of the active profile in the spinner line
*/
public int Getpos( ){
List<Profile> myList = new ArrayList<Profile>();
myList =db.getAllProfiles();// gets all profiles
String names [] = new String[myList.size()];
int count =0;
for(int i=myList.size()-1;i>=0;i--){
names[count]=myList.get(count).GetProfilname();//saves profile names backwards
count++;// names counter
}
int pos =0; // init the position
Configurations def = db.getDEf();// gets apps configuration
Profile prof = db.getProfile(def.GetPID()); // gets actives profile instance
for (int i=0;i<myList.size();i++) {
if (names[i].equals( prof.GetProfilname())) { //if the name of active profile is equal with any name in the list
Log.d("prof", Integer.toString(i));
pos = i;// returns the position of the name
break;
}
}
return pos;// returns the position of the name
}
@Override
public void onBackPressed() {// when back pressed go to mail activity
Intent intent = new Intent(getApplicationContext(), CameraActivity.class);
startActivity(intent);
}
}
| litsakis/SkinHealthChecker | skinHealthChecker/src/main/java/com/example/skinhealthchecker/Users.java |
2,446 | package javaapplication1;
import java.sql.*;
import javax.swing.*;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Ρωμανός
*/
public class project {
Connection conn=null;
public static Connection ConnectDb() {
try{
// Class.forName("com.mysql.jdbc.Driver"); // Εισαγωγή του connector
Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/erecruit?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC", "", ""); //Eγκαθίδρυση σύνδεσης. Προσοχή καθώς πρέπει να δίνεται τα δικά σας στοιχεία.
JOptionPane.showMessageDialog(null, "Connection to MySQL server/CinemaDB Established Successfully!"); //Μήνυμα επιτυχούς σύνδεσης
return conn;
}
catch(Exception e){ // η κλήση της getConnection του DriverManager πετάει throwable για αυτό χρειάζεται η catch
JOptionPane.showMessageDialog(null,e); // Η οποία θα εκτυπώνει ενα default μήνυμα λάθους.
return null;
}
}
}
| rkapsalis/CEID-projects | Database Lab/src/javaapplication1/project.java |
2,447 | package client;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import engine.Engine;
public class Client {
static Scanner sc = new Scanner(System.in);
static String file;
static String type;
static String alias;
static Engine engine = null;
static List<List<String>> inputSpec;
static List<Engine> engines = new ArrayList<Engine>();
static List<String> listAlias = new ArrayList<String>();
public static void main(String[] args) {
System.out.print("<------------------------- Επεξεργαστής Κειμένου ------------------------->\n");
String option = "0";
while(true) {
System.out.print("\nΕπέλεξε μία από τις παρακάτω επιλογές για να συνεχίσεις:\n");
System.out.print("1. Δημιούργησε ένα καινούριο αρχείο προς επεξεργασία. \n");
System.out.print("2. Φόρτωσε το αρχείο που έχεις δημιουργήσει ή/και χαρακτήρισε την παραγράφους του με βάση τους δωθέντες κανόνες.\n");
System.out.print("3. Εισήγαγε κανόνες για ένα αρχείο (Ύστερα επέλεξε το 2 για να χαρακτηριστούν οι παράγραφοι). \n");
System.out.print("4. Εκτύπωσε τα στατιστικά ενός αρχείου. \n");
System.out.print("5. Εξήγαγε ένα αρχείο σε μορφή Markdown. \n");
System.out.print("6. Εξήγαγε ένα αρχείο σε μορφή PDF. \n");
System.out.print("7. Τερμάτισε το πρόγραμμα. \n");
System.out.print("**Για να μπορέσεις να εκτελέσεις τις επιλογές 2-6 πρέπει να έχεις τουλάχιστον ένα δημιουργημένο αρχείο.** \n");
option = sc.nextLine();
if (option.equals("1")) {
System.out.print("\nΓράψε την πλήρη διαδρομή του αρχείου που θέλεις να εισάγεις. \n");
file = sc.nextLine();
System.out.print("Γράψε τον τύπο του αρχείου που εισήγαγες (RAW ή ANNOTATED). \n");
type = sc.nextLine();
System.out.print("Γράψε το φιλικό όνομα (alias) που θες να δώσεις στο αρχείο (πρέπει να είναι μοναδικό). \n");
alias = sc.nextLine();
listAlias.add(alias);
engine = new Engine(file, type, alias);
engines.add(engine);
List<List<String>> inputAnnSpec = new ArrayList<List<String>>();
if (type.equals("ANNOTATED")) {
System.out.print("Το αρχείο που επιλέξατε είναι επισημειωμένο. \n"
+ "Εισάγετε τους κανόνες που έχετε ήδη δημιουργήσει για το αρχείο (μετά από κάθε κανόνα πατήστε ENTER). \n"
+ "Πρέπει να είναι της μορφής π.χ. \"H1 STARTS_WITH #\". \n"
+ "Όταν ολοκληρώσετε την εισαγωγή γράψτε \"no\". \n");
String addAnnotatedRule = "";
while (!addAnnotatedRule.equals("no")) {
addAnnotatedRule = sc.nextLine();
if (!addAnnotatedRule.equals("no")) {
String [] rule = addAnnotatedRule.split(" ");
List<String> listRule = new ArrayList<String>();
listRule.add(rule[0]);
listRule.add(rule[1]);
listRule.add(rule[2]);
inputAnnSpec.add(listRule);
}
}
System.out.print("\nΕισάγετε τα prefixes πατώντας ENTER μετά από το καθένα, όταν τελειώσετε πληκτρολογήστε \"no\". \n");
String prefix = "";
List<String> prefixes = new ArrayList<String>();
while(!prefix.equals("no")) {
prefix = sc.nextLine();
prefixes.add(prefix);
}
engine.registerInputRuleSetForAnnotatedFiles(inputAnnSpec, prefixes);
}
}
else if (option.equals("2")) {
chooseFile();
engine.loadFileAndCharacterizeBlocks();
}
else if (option.equals("3")) { //Input Rules
chooseFile();
inputSpec = new ArrayList<List<String>>();
String addRule = "";
while(!addRule.equals("no")) {
System.out.print("Θέλεις να εισάγεις κανόνα; Αν ναι γράψε τον κανόνα σε σωστή μορφή και πάτησε ENTER αλλιώς γράψε \"no\". \n");
addRule = sc.nextLine();
if (!addRule.equals("no")) {
String [] rule = addRule.split(" ");
List<String> listRule = new ArrayList<String>();
listRule.add(rule[0]);
listRule.add(rule[1]);
if(rule.length == 3) //all_caps
listRule.add(rule[2]);
inputSpec.add(listRule);
}
}
engine.registerInputRuleSetForPlainFiles(inputSpec);
}
else if (option.equals("4")) { //Statistics
chooseFile();
System.out.print(engine.reportWithStats());
}
else if (option.equals("5")) { //Markdown
chooseFile();
System.out.print("Εισάγετε το πλήρες path του αρχείου στο οποίο θέλετε να εξάγετε το αρχείο εισόδου. \n");
String output = sc.nextLine();
engine.exportMarkDown(output);
}
else if (option.equals("6")) { //Pdf
chooseFile();
System.out.print("Εισάγετε το πλήρες path του αρχείου στο οποίο θέλετε να εξάγετε το αρχείο εισόδου. \n");
String output = sc.nextLine();
engine.exportPdf(output);
}
else if (option.equals("7")) {
System.out.print("\nΤο πρόγραμμα τερματίστηκε.\n");
System.exit(0);
sc.close();
System.out.print("\n<-------------------------------- Τέλος ------------------------------->\n");
}
else {
System.out.print("Η επιλογή που επέλεξες δεν υπάρχει ή δεν έχει διατυπωθεί σωστά. Πληκτρολόγησε έναν αριθμό από 1-7. \n");
}
}
}
private static void chooseFile() {
System.out.print("Επέλεξε ένα από τα υπάρχον αρχεία: \n");
for (int i=0; i<listAlias.size(); i++) {
System.out.print(listAlias.get(i) + "\n");
}
alias = sc.nextLine();
for (int i=0; i<engines.size(); i++) {
if (alias.equals(engines.get(i).getAlias())) {
engine = engines.get(i);
}
}
}
}
| marinapapageorgiou/java-anaptixi-assignment | src/client/Client.java |
2,449 | package com.unipi.p15013p15120.kastropoliteiesv2;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
import java.util.Calendar;
//form gia eggrafi xristi
public class SignUpForm extends AppCompatActivity {
LoginSignUpPage helper;
ImageButton close;
EditText email, pass, usern;
Button submit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme(R.style.SplashScreenAndLoginTheme);
setContentView(R.layout.sign_up_form);
//setSpinnerCalendar();
//panw deksia yparxei koumpi X ws epistrofi sthn prohgoumenh selida (auti tis syndeshs)
close = findViewById(R.id.closeBtn);
close.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
submit = findViewById(R.id.submit);
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
helper = new LoginSignUpPage();
email = findViewById(R.id.email_prompt);
pass = findViewById(R.id.password_prompt);
usern = findViewById(R.id.username_prompt);
if (!email.getText().toString().equals("") &&!pass.getText().toString().equals("") && !(pass.getText().toString().length() <6)) {
//an to email einai valid se morfi kane tin eggrafi
if (helper.isEmailValid(email.getText().toString()))
helper.firebaseAuthEmailSignUp(email.getText().toString(), pass.getText().toString(),usern.getText().toString());//helper.makeToast(getApplicationContext(),helper.firebaseAuthEmailSignUp(email.getText().toString(), pass.getText().toString(),usern.getText().toString()));
else
helper.makeToast(getApplicationContext(),"Το email που εισάγατε δεν είναι σε σωστή μορφή");
}
//an o password einai mikroteros apo 6 psifia den ginetai
else if (pass.getText().toString().length() <6)
helper.makeToast(getApplicationContext(),"Ο κωδικός πρέπει να είναι μεγαλύτερος ή ίσος με 6 ψηφία.");
else
helper.makeToast(getApplicationContext(), "Παρακαλώ εισάγετε τα στοιχεία σας.");
}
});
}
//itan gia na yparxei imerologio gia hmeromhnia gennhshs
private void setSpinnerCalendar()
{
ArrayList<String> years = new ArrayList<String>();
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
for (int i = 1900; i <= thisYear; i++) {
years.add(Integer.toString(i));
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, years);//was this
//Spinner spinYear = findViewById(R.id.spinnerCalendar);
//spinYear.setAdapter(adapter);
}
}
| PetePrattis/Recommendation-System-for-Android-Java-App-that-finds-an-ideal-destination-with-the-kNN-Algorithm | app/src/main/java/com/unipi/p15013p15120/kastropoliteiesv2/SignUpForm.java |
2,450 | /**
* Copyright 2016 SciFY
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.scify.talkandplay.gui.users;
import org.apache.commons.lang3.StringUtils;
import org.scify.talkandplay.gui.MainFrame;
import org.scify.talkandplay.gui.MainPanel;
import org.scify.talkandplay.gui.configuration.ConfigurationPanel;
import org.scify.talkandplay.gui.helpers.GuiHelper;
import org.scify.talkandplay.gui.helpers.UIConstants;
import org.scify.talkandplay.models.User;
import org.scify.talkandplay.models.sensors.KeyboardSensor;
import org.scify.talkandplay.models.sensors.MouseSensor;
import org.scify.talkandplay.models.sensors.Sensor;
import org.scify.talkandplay.services.UserService;
import org.scify.talkandplay.utils.ImageResource;
import org.scify.talkandplay.utils.ResourceManager;
import org.scify.talkandplay.utils.ResourceType;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
public class UserFormPanel extends javax.swing.JPanel {
private ImageResource userImage;
private MainFrame parent;
private UserService userService;
private GuiHelper guiHelper;
private User user;
private Sensor selectionSensor;
private Sensor navigationSensor;
protected ResourceManager rm;
public UserFormPanel(MainFrame parent, User user) {
this.guiHelper = new GuiHelper();
this.parent = parent;
this.user = user;
this.userService = new UserService();
this.rm = ResourceManager.getInstance();
initComponents();
initCustomComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jToolBar1 = new javax.swing.JToolBar();
jButton1 = new javax.swing.JButton();
buttonGroup1 = new ButtonGroup();
buttonGroup2 = new ButtonGroup();
buttonGroup3 = new ButtonGroup();
userPanel = new javax.swing.JPanel();
nameTextField = new JTextField();
uploadImageLabel = new javax.swing.JLabel();
rotationSpeedSlider = new javax.swing.JSlider();
rotationSpeedLabel = new javax.swing.JLabel();
saveAndNextButton = new javax.swing.JButton();
errorLabel = new javax.swing.JLabel();
saveAndBackButton = new javax.swing.JButton();
backButton = new javax.swing.JButton();
nameLabel = new javax.swing.JLabel();
imageLabel = new javax.swing.JLabel();
sensorLabel = new javax.swing.JLabel();
defaultGridSizeLabel = new javax.swing.JLabel();
columnsTextField = new JTextField();
xLabel = new javax.swing.JLabel();
rowsTextField = new JTextField();
tilesLabel = new javax.swing.JLabel();
soundCheckBox = new javax.swing.JCheckBox();
textCheckBox = new javax.swing.JCheckBox();
imageCheckBox = new javax.swing.JCheckBox();
selectionSensorTextField1 = new JTextField();
navigationSensorTextField = new JTextField();
selectionSensorTextField2 = new JTextField();
autoScanRadioButton = new javax.swing.JRadioButton();
manualScanRadioButton = new javax.swing.JRadioButton();
jScrollPane1 = new javax.swing.JScrollPane();
step6ExplTextArea = new javax.swing.JTextArea();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
saveToFileButton = new javax.swing.JButton();
successLabel = new javax.swing.JLabel();
jToolBar1.setRollover(true);
jButton1.setText("jButton1");
userPanel.setBackground(new Color(255, 255, 255));
nameTextField.setBackground(new Color(255, 255, 255));
nameTextField.setForeground(new Color(51, 51, 51));
nameTextField.setText(rm.getTextOfXMLTag("userNamePlaceholder"));
uploadImageLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
uploadImageLabel.setIcon(rm.getImageIcon("no-photo.png", ResourceType.JAR)); // NOI18N
uploadImageLabel.setToolTipText("");
uploadImageLabel.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
uploadImageLabel.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
uploadImageLabel.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
uploadImageLabelMouseClicked(evt);
}
});
rotationSpeedSlider.setBackground(new Color(255, 255, 255));
rotationSpeedSlider.setFont(rotationSpeedSlider.getFont());
rotationSpeedSlider.setForeground(new Color(51, 51, 51));
rotationSpeedSlider.setMajorTickSpacing(1);
rotationSpeedSlider.setMaximum(10);
rotationSpeedSlider.setMinimum(1);
rotationSpeedSlider.setMinorTickSpacing(1);
rotationSpeedSlider.setPaintLabels(true);
rotationSpeedSlider.setSnapToTicks(true);
rotationSpeedSlider.setValue(1);
rotationSpeedLabel.setText("4. " + rm.getTextOfXMLTag("selectRotationSpeed"));
saveAndNextButton.setBackground(new Color(75, 161, 69));
saveAndNextButton.setFont(saveAndNextButton.getFont());
saveAndNextButton.setForeground(new Color(255, 255, 255));
saveAndNextButton.setText(rm.getTextOfXMLTag("saveAndContinue"));
saveAndNextButton.setBorder(null);
saveAndNextButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
saveAndNextButtonActionPerformed(evt);
}
});
errorLabel.setFont(errorLabel.getFont());
errorLabel.setForeground(new Color(153, 0, 0));
errorLabel.setText("error");
saveAndBackButton.setBackground(new Color(75, 161, 69));
saveAndBackButton.setFont(saveAndBackButton.getFont());
saveAndBackButton.setForeground(new Color(255, 255, 255));
saveAndBackButton.setText(rm.getTextOfXMLTag("saveAndExit"));
saveAndBackButton.setBorder(null);
saveAndBackButton.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
saveAndBackButtonMouseClicked(evt);
}
});
backButton.setBackground(new Color(75, 161, 69));
backButton.setFont(backButton.getFont());
backButton.setForeground(new Color(255, 255, 255));
backButton.setText(rm.getTextOfXMLTag("backButton"));
backButton.setBorder(null);
nameLabel.setText("1. " + rm.getTextOfXMLTag("writeUserName"));
imageLabel.setText("2. " + rm.getTextOfXMLTag("uploadUserImage"));
sensorLabel.setText("3. " + rm.getTextOfXMLTag("configureNavigationAndSelection"));
defaultGridSizeLabel.setText("5. " + rm.getTextOfXMLTag("configureMatrixSize"));
columnsTextField.setText("3");
xLabel.setText("x");
rowsTextField.setText("3");
tilesLabel.setText("6. " + rm.getTextOfXMLTag("configureWords"));
soundCheckBox.setBackground(new Color(255, 255, 255));
soundCheckBox.setText(rm.getTextOfXMLTag("sound"));
textCheckBox.setBackground(new Color(255, 255, 255));
textCheckBox.setText(rm.getTextOfXMLTag("verbal"));
imageCheckBox.setBackground(new Color(255, 255, 255));
imageCheckBox.setText(rm.getTextOfXMLTag("image"));
String selectKey = rm.getTextOfXMLTag("selectKey");
selectionSensorTextField1.setText(selectKey);
navigationSensorTextField.setText(selectKey);
selectionSensorTextField2.setText(selectKey);
autoScanRadioButton.setBackground(new Color(255, 255, 255));
autoScanRadioButton.setText(rm.getTextOfXMLTag("automatically"));
manualScanRadioButton.setBackground(new Color(255, 255, 255));
manualScanRadioButton.setText(rm.getTextOfXMLTag("manually"));
step6ExplTextArea.setColumns(20);
step6ExplTextArea.setRows(5);
step6ExplTextArea.setText(rm.getTextOfXMLTag("configureWordsExtra"));
jScrollPane1.setViewportView(step6ExplTextArea);
String selection = rm.getTextOfXMLTag("selection") + ": ";
jLabel1.setText(selection);
jLabel2.setText(selection);
jLabel3.setText(rm.getTextOfXMLTag("navigation") + ":");
saveToFileButton.setBackground(new Color(75, 161, 69));
saveToFileButton.setFont(saveToFileButton.getFont().deriveFont((float) 18));
saveToFileButton.setForeground(new Color(255, 255, 255));
saveToFileButton.setText(rm.getTextOfXMLTag("saveToFile"));
saveToFileButton.setBorder(null);
saveToFileButton.setMaximumSize(new java.awt.Dimension(158, 15));
saveToFileButton.setMinimumSize(new java.awt.Dimension(158, 15));
saveToFileButton.setPreferredSize(new java.awt.Dimension(235, 62));
saveToFileButton.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
saveToFileButtonMouseClicked(evt);
}
});
successLabel.setForeground(new Color(0, 153, 0));
successLabel.setText("success");
successLabel.setToolTipText("");
javax.swing.GroupLayout userPanelLayout = new javax.swing.GroupLayout(userPanel);
userPanel.setLayout(userPanelLayout);
userPanelLayout.setHorizontalGroup(
userPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(userPanelLayout.createSequentialGroup()
.addGroup(userPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(userPanelLayout.createSequentialGroup()
.addGap(19, 19, 19)
.addGroup(userPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(userPanelLayout.createSequentialGroup()
.addComponent(nameLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, userPanelLayout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(saveToFileButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(saveAndBackButton)
.addGap(6, 6, 6)))
.addComponent(saveAndNextButton))
.addGroup(userPanelLayout.createSequentialGroup()
.addGroup(userPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(userPanelLayout.createSequentialGroup()
.addGap(19, 19, 19)
.addGroup(userPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(userPanelLayout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(nameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 223, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(imageLabel)
.addGroup(userPanelLayout.createSequentialGroup()
.addGap(49, 49, 49)
.addComponent(uploadImageLabel)))
.addGap(89, 89, 89)
.addGroup(userPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(sensorLabel)
.addGroup(userPanelLayout.createSequentialGroup()
.addGap(6, 6, 6)
.addGroup(userPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(manualScanRadioButton)
.addComponent(autoScanRadioButton)
.addGroup(userPanelLayout.createSequentialGroup()
.addGap(21, 21, 21)
.addGroup(userPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, userPanelLayout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(selectionSensorTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 178, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(userPanelLayout.createSequentialGroup()
.addGroup(userPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3)
.addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(userPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(selectionSensorTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 178, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(navigationSensorTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 178, javax.swing.GroupLayout.PREFERRED_SIZE)))))))))
.addGroup(userPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(successLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 402, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(160, 160, 160)
.addGroup(userPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(userPanelLayout.createSequentialGroup()
.addGroup(userPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, userPanelLayout.createSequentialGroup()
.addComponent(rotationSpeedSlider, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(26, 26, 26))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, userPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(defaultGridSizeLabel)
.addComponent(rotationSpeedLabel)
.addGroup(userPanelLayout.createSequentialGroup()
.addGap(6, 6, 6)
.addComponent(soundCheckBox)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(textCheckBox)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(imageCheckBox))
.addComponent(tilesLabel))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, userPanelLayout.createSequentialGroup()
.addComponent(rowsTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(xLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(columnsTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(94, 94, 94)))
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(userPanelLayout.createSequentialGroup()
.addGap(6, 6, 6)
.addComponent(jScrollPane1)))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(backButton)
.addGap(56, 56, 56))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, userPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(errorLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
userPanelLayout.setVerticalGroup(
userPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(userPanelLayout.createSequentialGroup()
.addGap(25, 25, 25)
.addGroup(userPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(userPanelLayout.createSequentialGroup()
.addGroup(userPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(userPanelLayout.createSequentialGroup()
.addComponent(nameLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(nameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(userPanelLayout.createSequentialGroup()
.addComponent(rotationSpeedLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(rotationSpeedSlider, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(userPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(userPanelLayout.createSequentialGroup()
.addGap(40, 40, 40)
.addComponent(imageLabel))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, userPanelLayout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(defaultGridSizeLabel)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(userPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(uploadImageLabel)
.addGroup(userPanelLayout.createSequentialGroup()
.addGroup(userPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(xLabel)
.addComponent(columnsTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(rowsTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(30, 30, 30)
.addComponent(tilesLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(userPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(soundCheckBox)
.addComponent(textCheckBox)
.addComponent(imageCheckBox))
.addGap(31, 31, 31)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(0, 60, Short.MAX_VALUE)
.addGroup(userPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(saveAndNextButton)
.addComponent(backButton)
.addComponent(saveAndBackButton)
.addComponent(saveToFileButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(userPanelLayout.createSequentialGroup()
.addComponent(sensorLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(autoScanRadioButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(userPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(userPanelLayout.createSequentialGroup()
.addGroup(userPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(selectionSensorTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1))
.addGap(8, 8, 8)
.addComponent(manualScanRadioButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(userPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(selectionSensorTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(37, 37, 37))
.addGroup(userPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(navigationSensorTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 15, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(errorLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(successLabel)
.addGap(111, 111, 111))))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(userPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(userPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
}// </editor-fold>//GEN-END:initComponents
private void initCustomComponents() {
errorLabel.setVisible(false);
successLabel.setVisible(false);
setUI();
setFocusListeners();
setActionListeners();
if (user != null) {
parent.setPanelTitle(rm.getTextOfXMLTag("editUserModePanelTitle"));
guiHelper.drawButton(saveAndNextButton);
guiHelper.drawButton(saveAndBackButton);
nameTextField.setText(user.getName());
uploadImageLabel.setIcon(guiHelper.getIcon(user.getImage()));
rotationSpeedSlider.setValue(user.getConfiguration().getRotationSpeed());
rowsTextField.setText(String.valueOf(user.getConfiguration().getDefaultGridRow()));
columnsTextField.setText(String.valueOf(user.getConfiguration().getDefaultGridColumn()));
soundCheckBox.setSelected(user.getConfiguration().hasSound());
imageCheckBox.setSelected(user.getConfiguration().hasImage());
textCheckBox.setSelected(user.getConfiguration().hasText());
selectionSensor = user.getConfiguration().getSelectionSensor();
navigationSensor = user.getConfiguration().getNavigationSensor();
//check if auto or manual scanning is set
if (user.getConfiguration().getNavigationSensor() == null) {
autoScanRadioButton.setSelected(true);
enableTextField(selectionSensorTextField1);
disableTextField(selectionSensorTextField2);
disableTextField(navigationSensorTextField);
selectionSensorTextField1.setText(setSensorText(user.getConfiguration().getSelectionSensor()));
} else {
manualScanRadioButton.setSelected(true);
enableTextField(selectionSensorTextField2);
enableTextField(navigationSensorTextField);
disableTextField(selectionSensorTextField1);
selectionSensorTextField2.setText(setSensorText(user.getConfiguration().getSelectionSensor()));
navigationSensorTextField.setText(setSensorText(user.getConfiguration().getNavigationSensor()));
}
} else {
parent.setPanelTitle(rm.getTextOfXMLTag("addUserModePanelTitle"));
saveAndBackButton.setVisible(false);
guiHelper.drawButton(saveAndNextButton);
autoScanRadioButton.setSelected(true);
enableTextField(selectionSensorTextField1);
disableTextField(selectionSensorTextField2);
disableTextField(navigationSensorTextField);
}
guiHelper.drawButton(backButton);
}
private boolean validateUser() {
String name = nameTextField.getText();
//name should not be empty
if (name.isEmpty() || rm.getTextOfXMLTag("userNamePlaceholder").equals(name)) {
errorLabel.setText(rm.getTextOfXMLTag("userNameErrorMessage"));
errorLabel.setVisible(true);
return false;
}
//name should be unique
if (user == null || !name.equals(user.getName())) {
List<User> users = userService.getUsers();
for (User user : users) {
if (user.getName().equals(name)) {
errorLabel.setText(rm.getTextOfXMLTag("userNameErrorMessage2"));
errorLabel.setVisible(true);
return false;
}
}
}
//rows, columns should not be empty, should be integers
if (rowsTextField.getText().isEmpty() || !StringUtils.isNumeric(rowsTextField.getText())
|| (StringUtils.isNumeric(rowsTextField.getText()) && (Integer.parseInt(rowsTextField.getText()) < 2 || Integer.parseInt(rowsTextField.getText()) > 6))
|| columnsTextField.getText().isEmpty() || !StringUtils.isNumeric(columnsTextField.getText())
|| (StringUtils.isNumeric(columnsTextField.getText()) && (Integer.parseInt(columnsTextField.getText()) < 2 || Integer.parseInt(columnsTextField.getText()) > 6))) {
errorLabel.setText(rm.getTextOfXMLTag("rawsAndColumnsErrorMessage"));
errorLabel.setVisible(true);
return false;
}
//sensors should not be null
if (autoScanRadioButton.isSelected() && selectionSensor == null) {
errorLabel.setText(rm.getTextOfXMLTag("selectionButtonErrorMessage"));
errorLabel.setVisible(true);
return false;
} else if (manualScanRadioButton.isSelected() && (selectionSensor == null || navigationSensor == null)) {
errorLabel.setText(rm.getTextOfXMLTag("selectionAndNavigationButtonsErrorMessage"));
errorLabel.setVisible(true);
return false;
}
//selection and navigation sensors should not be the same
if (manualScanRadioButton.isSelected()) {
if (selectionSensor instanceof MouseSensor && navigationSensor instanceof MouseSensor
&& ((MouseSensor) selectionSensor).getButton() == ((MouseSensor) navigationSensor).getButton()
&& ((MouseSensor) selectionSensor).getClickCount() == ((MouseSensor) navigationSensor).getClickCount()) {
errorLabel.setText(rm.getTextOfXMLTag("selectionAndNavigationButtonsErrorMessage2"));
errorLabel.setVisible(true);
return false;
}
if (selectionSensor instanceof KeyboardSensor && navigationSensor instanceof KeyboardSensor
&& ((KeyboardSensor) selectionSensor).getKeyCode() == ((KeyboardSensor) navigationSensor).getKeyCode()) {
errorLabel.setText(rm.getTextOfXMLTag("selectionAndNavigationButtonsErrorMessage2"));
errorLabel.setVisible(true);
return false;
}
}
/* //image or text should be selected
if (!imageCheckBox.isSelected() && !textCheckBox.isSelected()) {
errorLabel.setText("Οι λέξεις θα πρέπει να έχουν τουλάχιστον ένα από τα δύο: λεκτικό, εικόνα");
errorLabel.setVisible(true);
return false;
}*/
return true;
}
private void saveAndNextButtonActionPerformed(ActionEvent evt) {//GEN-FIRST:event_saveAndNextButtonActionPerformed
if (validateUser()) {
User newUser = new User(nameTextField.getText(), userImage);
newUser.getConfiguration().setRotationSpeed(rotationSpeedSlider.getValue());
newUser.getConfiguration().setNavigationSensor(navigationSensor);
newUser.getConfiguration().setSelectionSensor(selectionSensor);
newUser.getConfiguration().setDefaultGridRow(Integer.parseInt(rowsTextField.getText()));
newUser.getConfiguration().setDefaultGridColumn(Integer.parseInt(columnsTextField.getText()));
newUser.getConfiguration().setSound(soundCheckBox.isSelected());
newUser.getConfiguration().setImage(imageCheckBox.isSelected());
newUser.getConfiguration().setText(textCheckBox.isSelected());
try {
userService.update(user, newUser);
parent.changePanel(new ConfigurationPanel(newUser.getName(), parent));
} catch (Exception ex) {
Logger.getLogger(UserFormPanel.class.getName()).log(Level.SEVERE, null, ex);
}
}
}//GEN-LAST:event_saveAndNextButtonActionPerformed
private void uploadImageLabelMouseClicked(MouseEvent evt) {//GEN-FIRST:event_uploadImageLabelMouseClicked
userImage = null;
JFileChooser chooser = new JFileChooser();
chooser.setDialogTitle(rm.getTextOfXMLTag("selectImage"));
chooser.setAcceptAllFileFilterUsed(false);
chooser.setFileFilter(new FileNameExtensionFilter("Image Files", "png", "jpg", "jpeg", "JPG", "JPEG", "gif"));
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
userImage = new ImageResource(chooser.getSelectedFile().getAbsolutePath(), ResourceType.LOCAL);
uploadImageLabel.setIcon(guiHelper.getIcon(userImage));
}
}//GEN-LAST:event_uploadImageLabelMouseClicked
private void saveAndBackButtonMouseClicked(MouseEvent evt) {//GEN-FIRST:event_saveAndBackButtonMouseClicked
if (validateUser()) {
User newUser = new User(nameTextField.getText(), userImage);
newUser.getConfiguration().setRotationSpeed(rotationSpeedSlider.getValue());
newUser.getConfiguration().setNavigationSensor(navigationSensor);
newUser.getConfiguration().setSelectionSensor(selectionSensor);
newUser.getConfiguration().setDefaultGridRow(Integer.parseInt(rowsTextField.getText()));
newUser.getConfiguration().setDefaultGridColumn(Integer.parseInt(columnsTextField.getText()));
newUser.getConfiguration().setSound(soundCheckBox.isSelected());
newUser.getConfiguration().setImage(imageCheckBox.isSelected());
newUser.getConfiguration().setText(textCheckBox.isSelected());
try {
userService.update(user, newUser);
parent.changePanel(new MainPanel(parent, user.getUserOfAccount()));
} catch (Exception ex) {
Logger.getLogger(UserFormPanel.class.getName()).log(Level.SEVERE, null, ex);
}
}
}//GEN-LAST:event_saveAndBackButtonMouseClicked
private void saveToFileButtonMouseClicked(MouseEvent evt) {//GEN-FIRST:event_saveToFileButtonMouseClicked
final JFileChooser chooser = new JFileChooser();
chooser.setDialogTitle(rm.getTextOfXMLTag("chooseDirectory"));
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if (chooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
UserService us = new UserService();
//returns boolean to show success/failure of operation
boolean result = us.storeUserToExternalFile(user.getName(), file.getAbsolutePath());
//on success print success message, else print error message
if (result) {
errorLabel.setVisible(false);
successLabel.setText(rm.getTextOfXMLTag("profileSavedMessage"));
successLabel.setVisible(true);
} else {
successLabel.setVisible(false);
errorLabel.setText(rm.getTextOfXMLTag("profileNotSavedMessage"));
errorLabel.setVisible(true);
}
}
}//GEN-LAST:event_saveToFileButtonMouseClicked
/**
* The action listeners for the text fields and radio buttons
*/
private void setActionListeners() {
selectionSensorTextField1.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent me) {
if (selectionSensorTextField1.isEnabled()) {
selectionSensor = new MouseSensor(me.getButton(), me.getClickCount(), "mouse");
navigationSensor = null;
selectionSensorTextField1.setText(setSensorText(selectionSensor));
}
}
});
selectionSensorTextField1.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent ke) {
if (selectionSensorTextField1.isEnabled()) {
selectionSensor = new KeyboardSensor(ke.getKeyCode(), String.valueOf(ke.getKeyChar()), "keyboard");
navigationSensor = null;
selectionSensorTextField1.setText(setSensorText(selectionSensor));
}
}
});
navigationSensorTextField.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent me) {
if (navigationSensorTextField.isEnabled()) {
navigationSensor = new MouseSensor(me.getButton(), me.getClickCount(), "mouse");
navigationSensorTextField.setText(setSensorText(navigationSensor));
}
}
});
navigationSensorTextField.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent ke) {
if (navigationSensorTextField.isEnabled()) {
navigationSensor = new KeyboardSensor(ke.getKeyCode(), String.valueOf(ke.getKeyChar()), "keyboard");
navigationSensorTextField.setText(setSensorText(navigationSensor));
}
}
});
selectionSensorTextField2.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent me) {
if (selectionSensorTextField2.isEnabled()) {
selectionSensor = new MouseSensor(me.getButton(), me.getClickCount(), "mouse");
selectionSensorTextField2.setText(setSensorText(selectionSensor));
}
}
});
selectionSensorTextField2.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent ke) {
if (selectionSensorTextField2.isEnabled()) {
selectionSensor = new KeyboardSensor(ke.getKeyCode(), String.valueOf(ke.getKeyChar()), "keyboard");
selectionSensorTextField2.setText(setSensorText(selectionSensor));
}
}
});
backButton.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent me) {
parent.changePanel(new MainPanel(parent, user.getUserOfAccount()));
}
});
autoScanRadioButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
if (autoScanRadioButton.isSelected()) {
disableTextField(selectionSensorTextField2);
disableTextField(navigationSensorTextField);
enableTextField(selectionSensorTextField1);
}
}
});
manualScanRadioButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
if (manualScanRadioButton.isSelected()) {
disableTextField(selectionSensorTextField1);
enableTextField(selectionSensorTextField2);
enableTextField(navigationSensorTextField);
}
}
});
}
private void setFocusListeners() {
selectionSensorTextField1.addFocusListener(new FocusAdapter() {
public void focusGained(FocusEvent fe) {
selectionSensorTextField1.setText("");
}
public void focusLost(FocusEvent fe) {
if (selectionSensor == null) {
selectionSensorTextField1.setText(rm.getTextOfXMLTag("selectKey"));
} else {
selectionSensorTextField1.setText(setSensorText(selectionSensor));
}
}
});
navigationSensorTextField.addFocusListener(new FocusAdapter() {
public void focusGained(FocusEvent fe) {
navigationSensorTextField.setText("");
}
public void focusLost(FocusEvent fe) {
if (navigationSensor == null) {
navigationSensorTextField.setText(rm.getTextOfXMLTag("selectKey"));
} else {
navigationSensorTextField.setText(setSensorText(navigationSensor));
}
}
});
selectionSensorTextField2.addFocusListener(new FocusAdapter() {
public void focusGained(FocusEvent fe) {
selectionSensorTextField2.setText("");
}
public void focusLost(FocusEvent fe) {
if (selectionSensor == null) {
selectionSensorTextField2.setText(rm.getTextOfXMLTag("selectKey"));
} else {
selectionSensorTextField2.setText(setSensorText(selectionSensor));
}
}
});
nameTextField.addFocusListener(new FocusAdapter() {
public void focusGained(FocusEvent fe) {
if (rm.getTextOfXMLTag("userNamePlaceholder").equals(nameTextField.getText())) {
nameTextField.setText("");
}
}
public void focusLost(FocusEvent fe) {
if (nameTextField.getText().isEmpty()) {
nameTextField.setText(rm.getTextOfXMLTag("userNamePlaceholder"));
}
}
});
}
private void setUI() {
ButtonGroup scanButtons = new ButtonGroup();
scanButtons.add(autoScanRadioButton);
scanButtons.add(manualScanRadioButton);
//set the titles of the form
nameLabel.setFont(new Font(UIConstants.mainFont, Font.BOLD, 14));
imageLabel.setFont(new Font(UIConstants.mainFont, Font.BOLD, 14));
sensorLabel.setFont(new Font(UIConstants.mainFont, Font.BOLD, 14));
rotationSpeedLabel.setFont(new Font(UIConstants.mainFont, Font.BOLD, 14));
defaultGridSizeLabel.setFont(new Font(UIConstants.mainFont, Font.BOLD, 14));
tilesLabel.setFont(new Font(UIConstants.mainFont, Font.BOLD, 14));
nameTextField.setBorder(BorderFactory.createMatteBorder(0, 0, 2, 0, Color.GRAY));
nameTextField.setFont(new Font(UIConstants.mainFont, Font.ITALIC, 14));
nameTextField.setHorizontalAlignment(JTextField.CENTER);
uploadImageLabel.setFont(new Font(UIConstants.mainFont, Font.BOLD, 14));
rowsTextField.setBorder(BorderFactory.createMatteBorder(0, 0, 2, 0, Color.GRAY));
rowsTextField.setHorizontalAlignment(JTextField.CENTER);
columnsTextField.setBorder(BorderFactory.createMatteBorder(0, 0, 2, 0, Color.GRAY));
columnsTextField.setHorizontalAlignment(JTextField.CENTER);
disableTextField(selectionSensorTextField2);
disableTextField(navigationSensorTextField);
enableTextField(selectionSensorTextField1);
//set the text color
selectionSensorTextField1.setForeground(Color.decode(UIConstants.green));
selectionSensorTextField2.setForeground(Color.decode(UIConstants.green));
navigationSensorTextField.setForeground(Color.decode(UIConstants.green));
selectionSensorTextField1.setHorizontalAlignment(JTextField.CENTER);
selectionSensorTextField2.setHorizontalAlignment(JTextField.CENTER);
navigationSensorTextField.setHorizontalAlignment(JTextField.CENTER);
step6ExplTextArea.setEditable(false);
step6ExplTextArea.setLineWrap(true);
step6ExplTextArea.setWrapStyleWord(true);
step6ExplTextArea.setBorder(BorderFactory.createEmptyBorder());
jScrollPane1.setBorder(null);
imageCheckBox.setSelected(true);
imageCheckBox.setVisible(false);
}
private void disableTextField(JTextField textField) {
textField.setEnabled(false);
textField.setForeground(Color.decode(UIConstants.disabledColor));
textField.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.decode(UIConstants.disabledColor)));
textField.setBorder(BorderFactory.createCompoundBorder(textField.getBorder(), BorderFactory.createEmptyBorder(5, 5, 5, 5)));
}
private void enableTextField(JTextField textField) {
textField.setEnabled(true);
textField.setForeground(Color.decode(UIConstants.green));
textField.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.decode(UIConstants.green)));
textField.setBorder(BorderFactory.createCompoundBorder(textField.getBorder(), BorderFactory.createEmptyBorder(5, 5, 5, 5)));
}
private String setSensorText(Sensor s) {
String text = "";
if (s instanceof MouseSensor) {
MouseSensor sensor = (MouseSensor) s;
text += sensor.getClickCount();
if (sensor.getButton() == 1 && sensor.getClickCount() == 1) {
text += " " + rm.getTextOfXMLTag("leftClick");
} else if (sensor.getButton() == 1 && sensor.getClickCount() > 1) {
text += " " + rm.getTextOfXMLTag("leftClick");
} else if (sensor.getButton() == 2 && sensor.getClickCount() == 1) {
text += " " + rm.getTextOfXMLTag("middleClick");
;
} else if (sensor.getButton() == 2 && sensor.getClickCount() > 1) {
text += " " + rm.getTextOfXMLTag("middleClick");
;
} else if (sensor.getButton() == 3 && sensor.getClickCount() == 1) {
text += " " + rm.getTextOfXMLTag("rightClick");
;
} else if (sensor.getButton() == 3 && sensor.getClickCount() > 1) {
text += " " + rm.getTextOfXMLTag("rightClick");
;
}
} else if (s instanceof KeyboardSensor) {
KeyboardSensor sensor = (KeyboardSensor) s;
text += rm.getTextOfXMLTag("key") + " ";
if (sensor.getKeyCode() == 10) {
text += "enter";
} else if (sensor.getKeyCode() == 32) {
text += "space";
} else {
text += sensor.getKeyChar();
}
}
return text;
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JRadioButton autoScanRadioButton;
private javax.swing.JButton backButton;
private ButtonGroup buttonGroup1;
private ButtonGroup buttonGroup2;
private ButtonGroup buttonGroup3;
private JTextField columnsTextField;
private javax.swing.JLabel defaultGridSizeLabel;
private javax.swing.JLabel errorLabel;
private javax.swing.JCheckBox imageCheckBox;
private javax.swing.JLabel imageLabel;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JToolBar jToolBar1;
private javax.swing.JRadioButton manualScanRadioButton;
private javax.swing.JLabel nameLabel;
private JTextField nameTextField;
private JTextField navigationSensorTextField;
private javax.swing.JLabel rotationSpeedLabel;
private javax.swing.JSlider rotationSpeedSlider;
private JTextField rowsTextField;
private javax.swing.JButton saveAndBackButton;
private javax.swing.JButton saveAndNextButton;
private javax.swing.JButton saveToFileButton;
private JTextField selectionSensorTextField1;
private JTextField selectionSensorTextField2;
private javax.swing.JLabel sensorLabel;
private javax.swing.JCheckBox soundCheckBox;
private javax.swing.JTextArea step6ExplTextArea;
private javax.swing.JLabel successLabel;
private javax.swing.JCheckBox textCheckBox;
private javax.swing.JLabel tilesLabel;
private javax.swing.JLabel uploadImageLabel;
private javax.swing.JPanel userPanel;
private javax.swing.JLabel xLabel;
// End of variables declaration//GEN-END:variables
}
| scify/TalkAndPlay | src/main/java/org/scify/talkandplay/gui/users/UserFormPanel.java |
2,451 | /**
* MIT License
*
* Copyright (c) 2022 Nikolaos Siatras
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package rabbitminer.Stratum;
import java.text.DecimalFormat;
import java.util.HashMap;
import rabbitminer.Cluster.StratumClient.StratumToken;
import rabbitminer.Crypto.CryptoAlgorithms.CryptoAlgorithmsManager;
import rabbitminer.Crypto.CryptoAlgorithms.ECryptoAlgorithm;
import rabbitminer.JSON.JSONSerializer;
/**
*
* @author Nikos Siatras
*/
public class StratumJob
{
protected final ECryptoAlgorithm fCryptoAlgorithm;
protected final StratumToken fStratumToken;
protected int fNOnceRangeFrom = 0, fNOnceRangeTo = 0;
private final DecimalFormat fNonceFormater = new DecimalFormat("###,###.###");
public StratumJob(ECryptoAlgorithm algorithm, StratumToken stratumToken)
{
fCryptoAlgorithm = algorithm;
fStratumToken = stratumToken;
}
public StratumJob(String fromJson)
{
final HashMap map = JSONSerializer.DeserializeObjectToHash(fromJson);
// Πάρε τον αλγοριθμο απο το Json
fCryptoAlgorithm = CryptoAlgorithmsManager.getCryptoAlgorithmEnumFromName((String) map.get("Algorithm"));
// Πάρε το NOnce Range που πρέπει ο Miner να δουλεψει
final String tmpRange = (String) map.get("NOnceRange");
final String[] tmp = tmpRange.split("-");
fNOnceRangeFrom = Integer.parseInt(tmp[0]);
fNOnceRangeTo = Integer.parseInt(tmp[1]);
// Πάρε το Stratum Token
fStratumToken = new StratumToken((String) map.get("StratumToken"));
}
public boolean isRandomXJob()
{
return fCryptoAlgorithm == ECryptoAlgorithm.RandomX;
}
public boolean isSCryptJob()
{
return fCryptoAlgorithm == ECryptoAlgorithm.SCrypt;
}
//////////////////////////////////////////////////////////////////////////////////////////////
// Κοινοί Παράμετροι
//////////////////////////////////////////////////////////////////////////////////////////////
public ECryptoAlgorithm getCryptoAlgorithm()
{
return fCryptoAlgorithm;
}
public StratumToken getToken()
{
return fStratumToken;
}
/**
* Set the NOnceRange for this Job
*
* @param from
* @param to
*/
public void setNOnceRange(int from, int to)
{
fNOnceRangeFrom = from;
fNOnceRangeTo = to;
}
/**
* Return the NOnceRange to scan for this job
*
* @return
*/
public String getNOnceRange()
{
return fNonceFormater.format(fNOnceRangeFrom) + " - " + fNonceFormater.format(fNOnceRangeTo);
}
public int getNOnceRangeFrom()
{
return fNOnceRangeFrom;
}
public int getNOnceRangeTo()
{
return fNOnceRangeTo;
}
/**
* Serialize this Job to JSON
*
* @return
*/
public String toJSON()
{
HashMap map = new HashMap();
map.put("Algorithm", fCryptoAlgorithm.toString());
map.put("NOnceRange", String.valueOf(fNOnceRangeFrom) + "-" + String.valueOf(fNOnceRangeTo));
map.put("StratumToken", fStratumToken.getRawData());
return JSONSerializer.SerializeObject(map);
}
}
| SourceRabbit/Rabbit_Miner | RabbitMiner/src/rabbitminer/Stratum/StratumJob.java |
2,452 | package gr.aueb;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class LoginFrame extends JFrame implements ActionListener {
static String username;
JFrame frm = new JFrame("Filmbro");
JLabel welcomeMess = new JLabel("Hello, log in to your account.");
Container container = getContentPane();
JLabel userLabel = new JLabel("Username:");
JLabel passwordLabel = new JLabel("Password:");
JTextField userTextField = new JTextField(" e.g. Username");
JPasswordField passwordField = new JPasswordField();
DarkButton loginButton = new DarkButton("LOGIN");
DarkButton backButton = new DarkButton("BACK");
JCheckBox showPassword = new JCheckBox("Show Password");
JLabel picLabel = new JLabel(new ImageIcon("logo.png")); // an theloume na baloyme eikona
JMenuBar mb = new JMenuBar();
LoginFrame() {
initComponents();
}
private void initComponents() {
setTitle("Java");
setBounds(10, 10, 600, 600);
frm.setJMenuBar(mb);
setLocationRelativeTo(null); // center the application window
setVisible(true);
setLayoutManager();
setLocationAndSize();
addComponentsToContainer();
addActionEvent();
setBackground(20,20,20);
setFont();
addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
resizeComponents();
}
});
}
public void setLayoutManager() {
container.setLayout(null);
}
private void setBackground(int a, int b, int c) {
container.setBackground(new Color(a, b, c));
showPassword.setBackground(new Color(a, b, c));
}
private void setFont() {
welcomeMess.setFont(new Font("Tahoma", 0, 16));
welcomeMess.setForeground(new Color(230, 120, 50));
userLabel.setForeground(new Color(230, 120, 50));
passwordLabel.setForeground(new Color(230, 120, 50));
showPassword.setForeground(new Color(230, 120, 50));
}
public void setLocationAndSize() {
userLabel.setBounds(50, 150, 100, 30);
passwordLabel.setBounds(50, 200, 100, 30);
userTextField.setBounds(150, 150, 150, 30);
passwordField.setBounds(150, 200, 150, 30);
showPassword.setBounds(150, 240, 150, 30);
loginButton.setBounds(125, 300, 100, 30);
welcomeMess.setBounds(70, 50, 230, 150);
picLabel.setBounds(100, 10, 150, 90);
backButton.setBounds(20, 490, 80, 30);
}
public void addComponentsToContainer() {
container.add(userLabel);
container.add(welcomeMess);
container.add(passwordLabel);
container.add(userTextField);
container.add(passwordField);
container.add(showPassword);
container.add(loginButton);
container.add(picLabel);
container.add(backButton);
}
public void addActionEvent() {
loginButton.addActionListener(this);
showPassword.addActionListener(this);
backButton.addActionListener(this);
userTextField.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
userTextField.setText("");
}
});
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == backButton) {
MenuBar m = new MenuBar(new MenuFrame());
dispose();
}
if (e.getSource() == showPassword) {
if (showPassword.isSelected()) {
passwordField.setEchoChar((char) 0);
}else {
passwordField.setEchoChar('*');
}
}
}
public void resizeComponents() {
int width = this.getWidth();
int centerOffset = width / 4; // Προσαρμόζετε τον παράγοντα ανάλογα με την πόσο πρέπει να μετακινηθούν τα στοιχεία.
userLabel.setBounds(centerOffset, 150, 100, 30);
passwordLabel.setBounds(centerOffset, 200, 100, 30);
userTextField.setBounds(centerOffset + 100, 150, 150, 30);
passwordField.setBounds(centerOffset + 100, 200, 150, 30);
showPassword.setBounds(centerOffset + 100, 240, 150, 30);
loginButton.setBounds(centerOffset +85, 300, 140, 30); // Προσαρμόστε ανάλογα για την ευθυγράμμιση.
welcomeMess.setBounds(centerOffset, 50, 230, 150);
picLabel.setBounds(centerOffset + 50, 10, 150, 90);
backButton.setBounds(20, 490, 80, 30);
}
} | Aglag257/Java2_AIApp | app/src/unused_code/LoginFrame.java |
2,453 | package GameplayAndLogic;
import Cells.DecorativeCell;
import Cells.FinalCell;
import Cells.InitCell;
import Cells.StarCell;
import GameBoardData.GameBoardMap;
import WindowInterface.GamePanel;
import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import javax.swing.BorderFactory;
import javax.swing.JOptionPane;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;
/**
* Gameplay class is responsible for the proper operation of the game, for the
* respect of the rules, the graphical updating of gameBoard with gamePanel, the
* update of game log area, about who win the game, the right set of players,
* when a player has a move available or not, if the move is chosen if it is
* valid, if can play again or not, when can roll the dice and when round must
* change and more.
*
* @author Πλέσσιας Αλέξανδρος (ΑΜ.:2025201100068).
*/
public class Gameplay {
// Basic class fields.
private ArrayList<Player> players;
private Dice gameDice;
private GamePanel gamePanel;
private GameBoardMap gameBoardMap;
private int gameBoardSize;
private int squareSize;
// Init pawns positions
int[] greenInitPos;
int[] redInitPos;
int[] yellowInitPos;
int[] blueInitPos;
// Start positions.
int greenStart;
int redStart;
int yellowStart;
int blueStart;
// Game paths.
ArrayList<Integer> greenPathList;
ArrayList<Integer> redPathList;
ArrayList<Integer> yellowPathList;
ArrayList<Integer> bluePathList;
/**
* Constractor of Gameplay create the dice generate start, init, path
* positions, shuffle players, set all pawn to right init positions and
* start the game log showing the sequence of players.
*
* @param playersTable All active players of game.
* @param gameBoardMap The data/cell stacture structure.
* @param gamePanel The game Panel.
*/
public Gameplay(Player[] playersTable, GameBoardMap gameBoardMap, GamePanel gamePanel) {
// Create arraylist with players
this.players = new ArrayList<>(playersTable.length);
this.players.addAll(Arrays.asList(playersTable));
this.gameBoardMap = gameBoardMap;
this.gamePanel = gamePanel;
// Game dice
this.gameDice = new Dice();
// Initialize gameBoardSize & squareSize
this.gameBoardSize = this.gamePanel.getGameBoard_length();
this.squareSize = this.gamePanel.getSquare_size();
// Initialize init positions, start positions and game paths, created only for active colors
for (Player player : players) {
if (player.getColor() == Color.green) {
greenInitPos = new int[]{gameBoardSize + 2, gameBoardSize + (squareSize - 1), gameBoardSize * (squareSize - 2) + 2, (gameBoardSize * (squareSize - 2)) + (squareSize - 1)};
greenStart = (gameBoardSize * squareSize) + 2;
greenPathList = greenPath(greenStart);
} else if (player.getColor() == Color.red) {
redInitPos = new int[]{gameBoardSize + squareSize + 3 + 2, gameBoardSize * 2 - 1, gameBoardSize * (squareSize - 2) + squareSize + 3 + 2, gameBoardSize * (squareSize - 1) - 1};
redStart = gameBoardSize + squareSize + 3;
redPathList = redPath(redStart);
} else if (player.getColor() == Color.yellow) {
yellowInitPos = new int[]{gameBoardSize * (squareSize + 3 + 1) + 2, gameBoardSize * (squareSize + 3 + 1) + (squareSize - 1), gameBoardSize * (gameBoardSize - 2) + 2, gameBoardSize * (gameBoardSize - 2) + (squareSize - 1)};
yellowStart = (gameBoardSize * (gameBoardSize - 2)) + (squareSize + 1);
yellowPathList = yellowPath(yellowStart);
} else { // (players.get(i).getColor() ==Color.blue)
blueInitPos = new int[]{(gameBoardSize * (squareSize + 3 + 1)) + squareSize + 3 + 2, gameBoardSize * (squareSize + 3 + 2) - 1, gameBoardSize * (gameBoardSize - 2) + (squareSize + 3 + 2), gameBoardSize * (gameBoardSize - 1) - 1};
blueStart = (gameBoardSize * (squareSize + 3)) - 1;
bluePathList = bluePath(blueStart);
}
}
// Shuffle players for create turns.
Collections.shuffle(this.players);
// Initialize each player's pawns.
initPawns(this.players.size(), greenInitPos, redInitPos, yellowInitPos, blueInitPos);
// First info messages for game logs.
gamePanel.getInfoJTextArea().setText("[Σύστημα]: Γίνεται τυχαία επιλογή σειράς.");
for (int i = 0; i < this.players.size(); i++) {
String oldText = gamePanel.getInfoJTextArea().getText();
String newText = "\n[Σύστημα]: Ο " + (i + 1) + "ος Παίκτης θα ειναι ο " + this.players.get(i).getNickname() + " με χρώμα " + this.players.get(i).getColorText() + ".";
gamePanel.getInfoJTextArea().setText(oldText + newText);
}
}
// GETTERS //
/**
* @return The game dice.
*/
public Dice getPlayersDice() {
return gameDice;
}
/**
* @return Arraylist with all players.
*/
public ArrayList<Player> getPlayers() {
return players;
}
// PATHS OF COLORS AND INITIALIZE PAWNS //
/**
* Pawns of each player is added to the appropriate init posiotion.
*
* @param playersNum The number of active players.
* @param greenInitPos // The arraylist with init poitions for green pawns.
* @param redInitPos // The arraylist with init poitions for red pawns.
* @param yellowInitPos // The arraylist with init poitions for yellow
* pawns.
* @param blueInitPos // The arraylist with init poitions for blue pawns.
*/
private void initPawns(int playersNum, int[] greenInitPos, int[] redInitPos, int[] yellowInitPos, int[] blueInitPos) {
for (int i = 0; i < playersNum; i++) {
if (players.get(i).getColor() == Color.green) {
for (int j = 0; j < players.get(i).getPanws().size(); j++) {
players.get(i).setPanws(j, greenInitPos[j]); // give number
gameBoardMap.getCell(greenInitPos[j]).addPawn(players.get(i).getPawn(j));
}
} else if (players.get(i).getColor() == Color.red) {
for (int j = 0; j < players.get(i).getPanws().size(); j++) {
players.get(i).setPanws(j, redInitPos[j]);
gameBoardMap.getCell(redInitPos[j]).addPawn(players.get(i).getPawn(j));
}
} else if (players.get(i).getColor() == Color.yellow) {
for (int j = 0; j < players.get(i).getPanws().size(); j++) {
players.get(i).setPanws(j, yellowInitPos[j]);
gameBoardMap.getCell(yellowInitPos[j]).addPawn(players.get(i).getPawn(j));
}
} else { // players.get(i).getColor()==Color.blue
for (int j = 0; j < players.get(i).getPanws().size(); j++) {
players.get(i).setPanws(j, blueInitPos[j]);
gameBoardMap.getCell(blueInitPos[j]).addPawn(players.get(i).getPawn(j));
}
}
}
}
/**
* Creation of the path with the help of a "virtual transition" from the
* first cell to the last Cell.
*
* @param greenStart The first cell of path.
* @return ArrayList containing the path having to cross the green Pawns.
*/
private ArrayList<Integer> greenPath(int greenStart) {
ArrayList<Integer> greenPathArraylist = new ArrayList<>();
greenPathArraylist.add(greenStart);
for (int i = 0; i < squareSize - 2; i++) {
greenStart++;
greenPathArraylist.add(greenStart);
}
greenStart++;
for (int i = 0; i < squareSize; i++) {
greenStart = greenStart - gameBoardSize;
greenPathArraylist.add(greenStart);
}
greenStart++;
greenPathArraylist.add(greenStart);
greenStart++;
greenPathArraylist.add(greenStart);
for (int i = 0; i < squareSize - 1; i++) {
greenStart = greenStart + gameBoardSize;
greenPathArraylist.add(greenStart);
}
greenStart = greenStart + gameBoardSize;
for (int i = 0; i < squareSize; i++) {
greenStart++;
greenPathArraylist.add(greenStart);
}
greenStart = greenStart + gameBoardSize;
greenPathArraylist.add(greenStart);
greenStart = greenStart + gameBoardSize;
for (int i = 0; i < squareSize; i++) {
greenPathArraylist.add(greenStart);
greenStart--;
}
for (int i = 0; i < squareSize; i++) {
greenStart = greenStart + gameBoardSize;
greenPathArraylist.add(greenStart);
}
greenStart--;
greenPathArraylist.add(greenStart);
greenStart--;
greenPathArraylist.add(greenStart);
for (int i = 0; i < squareSize - 1; i++) {
greenStart = greenStart - gameBoardSize;
greenPathArraylist.add(greenStart);
}
greenStart = greenStart - gameBoardSize;
for (int i = 0; i < squareSize; i++) {
greenStart--;
greenPathArraylist.add(greenStart);
}
greenStart = greenStart - gameBoardSize;
greenPathArraylist.add(greenStart);
for (int i = 0; i < squareSize; i++) {
greenStart++;
greenPathArraylist.add(greenStart);
}
return greenPathArraylist;
}
/**
* Creation of the red path with the help of a "virtual transition" from the
* first cell to the last Cell.
*
* @param redStart The first red cell of path.
* @return ArrayList containing the path having to cross the green Pawns.
*/
private ArrayList<Integer> redPath(int redStart) {
ArrayList<Integer> redPathArraylist = new ArrayList<>();
redPathArraylist.add(redStart);
for (int i = 0; i < squareSize - 2; i++) {
redStart = redStart + gameBoardSize;
redPathArraylist.add(redStart);
}
redStart = redStart + gameBoardSize;
for (int i = 0; i < squareSize; i++) {
redStart++;
redPathArraylist.add(redStart);
}
redStart = redStart + gameBoardSize;
redPathArraylist.add(redStart);
redStart = redStart + gameBoardSize;
redPathArraylist.add(redStart);
for (int i = 0; i < squareSize - 1; i++) {
redStart--;
redPathArraylist.add(redStart);
}
redStart--;
for (int i = 0; i < squareSize; i++) {
redStart = redStart + gameBoardSize;
redPathArraylist.add(redStart);
}
redStart--;
redPathArraylist.add(redStart);
redStart--;
redPathArraylist.add(redStart);
for (int i = 0; i < squareSize - 1; i++) {
redStart = redStart - gameBoardSize;
redPathArraylist.add(redStart);
}
redStart = redStart - gameBoardSize;
for (int i = 0; i < squareSize; i++) {
redStart--;
redPathArraylist.add(redStart);
}
redStart = redStart - gameBoardSize;
redPathArraylist.add(redStart);
redStart = redStart - gameBoardSize;
redPathArraylist.add(redStart);
for (int i = 0; i < squareSize - 1; i++) {
redStart++;
redPathArraylist.add(redStart);
}
redStart++;
for (int i = 0; i < squareSize; i++) {
redStart = redStart - gameBoardSize;
redPathArraylist.add(redStart);
}
redStart++;
redPathArraylist.add(redStart);
for (int i = 0; i < squareSize; i++) {
redStart = redStart + gameBoardSize;
redPathArraylist.add(redStart);
}
return redPathArraylist;
}
/**
* Creation of the yellow path with the help of a "virtual transition" from
* the first cell to the last Cell.
*
* @param yellowStart The first yellow cell of path.
* @return ArrayList containing the path having to cross the green Pawns.
*/
private ArrayList<Integer> yellowPath(int yellowStart) {
ArrayList<Integer> yellowPathArraylist = new ArrayList<>();
yellowPathArraylist.add(yellowStart);
for (int i = 0; i < squareSize - 2; i++) {
yellowStart = yellowStart - gameBoardSize;
yellowPathArraylist.add(yellowStart);
}
yellowStart = yellowStart - gameBoardSize;
for (int i = 0; i < squareSize; i++) {
yellowStart--;
yellowPathArraylist.add(yellowStart);
}
yellowStart = yellowStart - gameBoardSize;
yellowPathArraylist.add(yellowStart);
yellowStart = yellowStart - gameBoardSize;
yellowPathArraylist.add(yellowStart);
for (int i = 0; i < squareSize - 1; i++) {
yellowStart++;
yellowPathArraylist.add(yellowStart);
}
yellowStart++;
for (int i = 0; i < squareSize; i++) {
yellowStart = yellowStart - gameBoardSize;
yellowPathArraylist.add(yellowStart);
}
yellowStart++;
yellowPathArraylist.add(yellowStart);
yellowStart++;
yellowPathArraylist.add(yellowStart);
for (int i = 0; i < squareSize - 1; i++) {
yellowStart = yellowStart + gameBoardSize;
yellowPathArraylist.add(yellowStart);
}
yellowStart = yellowStart + gameBoardSize;
for (int i = 0; i < squareSize; i++) {
yellowStart++;
yellowPathArraylist.add(yellowStart);
}
yellowStart = yellowStart + gameBoardSize;
yellowPathArraylist.add(yellowStart);
yellowStart = yellowStart + gameBoardSize;
yellowPathArraylist.add(yellowStart);
for (int i = 0; i < squareSize - 1; i++) {
yellowStart--;
yellowPathArraylist.add(yellowStart);
}
yellowStart--;
for (int i = 0; i < squareSize; i++) {
yellowStart = yellowStart + gameBoardSize;
yellowPathArraylist.add(yellowStart);
}
yellowStart--;
yellowPathArraylist.add(yellowStart);
for (int i = 0; i < squareSize; i++) {
yellowStart = yellowStart - gameBoardSize;
yellowPathArraylist.add(yellowStart);
}
return yellowPathArraylist;
}
/**
* Creation of the blue path with the help of a "virtual transition" from
* the first cell to the last Cell.
*
* @param blueStart The first blue cell of path.
* @return ArrayList containing the path having to cross the green Pawns.
*/
private ArrayList<Integer> bluePath(int blueStart) {
ArrayList<Integer> bluePathArraylist = new ArrayList<>();
bluePathArraylist.add(blueStart);
for (int i = 0; i < squareSize - 2; i++) {
blueStart--;
bluePathArraylist.add(blueStart);
}
blueStart--;
for (int i = 0; i < squareSize; i++) {
blueStart = blueStart + gameBoardSize;
bluePathArraylist.add(blueStart);
}
blueStart--;
bluePathArraylist.add(blueStart);
blueStart--;
bluePathArraylist.add(blueStart);
for (int i = 0; i < squareSize - 1; i++) {
blueStart = blueStart - gameBoardSize;
bluePathArraylist.add(blueStart);
}
blueStart = blueStart - gameBoardSize;
for (int i = 0; i < squareSize; i++) {
blueStart--;
bluePathArraylist.add(blueStart);
}
blueStart = blueStart - gameBoardSize;
bluePathArraylist.add(blueStart);
blueStart = blueStart - gameBoardSize;
bluePathArraylist.add(blueStart);
for (int i = 0; i < squareSize - 1; i++) {
blueStart++;
bluePathArraylist.add(blueStart);
}
blueStart++;
for (int i = 0; i < squareSize; i++) {
blueStart = blueStart - gameBoardSize;
bluePathArraylist.add(blueStart);
}
blueStart++;
bluePathArraylist.add(blueStart);
blueStart++;
bluePathArraylist.add(blueStart);
for (int i = 0; i < squareSize - 1; i++) {
blueStart = blueStart + gameBoardSize;
bluePathArraylist.add(blueStart);
}
blueStart = blueStart + gameBoardSize;
for (int i = 0; i < squareSize; i++) {
blueStart++;
bluePathArraylist.add(blueStart);
}
blueStart = blueStart + gameBoardSize;
bluePathArraylist.add(blueStart);
for (int i = 0; i < squareSize; i++) {
blueStart--;
bluePathArraylist.add(blueStart);
}
return bluePathArraylist;
}
// MESSAGES UPDATES //
/**
* Update InfoJTextArea about who is playnig now.
*
* @param playerNum The player who is playing now.
*/
public void nowPlayMsgUpdate(int playerNum) {
String oldText = this.gamePanel.getInfoJTextArea().getText();
String newText = ("\n[Σύστημα]: Τώρα παίζει ο " + players.get(playerNum).getNickname() + ".");
gamePanel.getInfoJTextArea().setText(oldText + newText);
}
/**
* Update InfoJTextArea about the moves.
*
* @param player The player who made the move.
* @param pawnNum The player Pawn number.
* @param startPos The start position
* @param finishPos The finish position.
*/
public void movePlayMsgUpdate(Player player, int pawnNum, int startPos, int finishPos) {
String oldText = this.gamePanel.getInfoJTextArea().getText();
String newText = null;
if (startPos == -1) {
newText = ("\n[" + player.getNickname() + "]: Έβγαλα το πιόνι " + (pawnNum + 1) + " από την αφετηρία.");
} else {
newText = ("\n[" + player.getNickname() + "]: Μετακίνησα το πιόνι " + (pawnNum + 1) + " από την θέση " + startPos + " στην θέση " + finishPos + ".");
}
this.gamePanel.getInfoJTextArea().setText(oldText + newText);
}
/**
* Update InfoJTextArea about Star moves.
*
* @param player The player who made the Star move.
* @param finishPos The finish(Next Star) position.
*/
public void starMoveMsgUpdate(Player player, int finishPos) {
String oldText = this.gamePanel.getInfoJTextArea().getText();
String newText = ("\n[Σύστημα]: Ο " + player.getNickname() + " μεταφέρθηκε στο επομενο StarCell στην θέση " + finishPos + ".");
this.gamePanel.getInfoJTextArea().setText(oldText + newText);
}
/**
* Update InfoJTextArea about who caught the pawn of other players and the
* number of pawn.
*
* @param player The player who caught the pawn of the the rival.
* @param catchPlayer The player who has caught.
* @param catchPawnNum The number of the pawn which is caught.
*/
public void catchMsgUpdate(Player player, Player catchPlayer, int catchPawnNum) {
String oldText = this.gamePanel.getInfoJTextArea().getText();
String newText = ("\n[" + player.getNickname() + "]: Έπιασα το πιόνι " + (catchPawnNum + 1) + " του " + catchPlayer.getNickname() + ".");
this.gamePanel.getInfoJTextArea().setText(oldText + newText);
}
/**
* Update InfoJTextArea about the player who play again.
*
* @param player The player who play again.
* @param codeCom if 0 for outside of init area(with 5) else for dice = 6.
*/
public void playAgainMsgUpdate(Player player, int codeCom) {
String oldText = this.gamePanel.getInfoJTextArea().getText();
String newText;
if (codeCom == 0) {
newText = ("\n[Σύστημα]: Ο " + player.getNickname() + " ξαναπαίζει γιατί έβγαλε πιόνι απο την εκκίνηση .");
} else {
newText = ("\n[Σύστημα]: Ο " + player.getNickname() + " ξαναπαίζει γιατί έφερε 6.");
}
this.gamePanel.getInfoJTextArea().setText(oldText + newText);
}
/**
* Update InfoJTextArea about finish of a pawn.
*
* @param player Pawn's owner
* @param curPlayerPawnNum Pawn's number.
*/
public void pawnFinishMsgUpdate(Player player, int curPlayerPawnNum) {
String oldText = this.gamePanel.getInfoJTextArea().getText();
String newText = ("\n[Σύστημα]: To πιόνι " + (curPlayerPawnNum + 1) + " του " + player.getNickname() + " τερμάτισε. ");
this.gamePanel.getInfoJTextArea().setText(oldText + newText);
}
// UTILITIES FUNCTIONS //
/**
* First disable all Cells(except DecorativeCell) and after enable only
* current player's path and init positions.
*
* @param curPlayer The play now/current player.
*/
public void onCurrentOffOther(int curPlayer) {
// Disable all Cells(except DecorativeCell)
for (int i = 1; i < (gameBoardSize * gameBoardSize); i++) {
if (!(gameBoardMap.getCell(i) instanceof DecorativeCell)) {
gameBoardMap.getCell(i).setEnabled(false);
}
}
// Enable current player's path and init positions.
if (players.get(curPlayer).getColor() == Color.green) {
// Enable init pawns
for (int i = 0; i < greenInitPos.length; i++) {
gameBoardMap.getCell(greenInitPos[i]).setEnabled(true);
}
// Enable path cells.
for (Integer greenPathList1 : greenPathList) {
gameBoardMap.getCell(greenPathList1).setEnabled(true);
}
} else if (players.get(curPlayer).getColor() == Color.red) {
// Enable init pawns
for (int i = 0; i < redInitPos.length; i++) {
gameBoardMap.getCell(redInitPos[i]).setEnabled(true);
}
// Enable path cells.
for (Integer redPathList1 : redPathList) {
gameBoardMap.getCell(redPathList1).setEnabled(true);
}
} else if (players.get(curPlayer).getColor() == Color.yellow) {
// Enable init pawns
for (int i = 0; i < yellowInitPos.length; i++) {
gameBoardMap.getCell(yellowInitPos[i]).setEnabled(true);
}
// Enable path cells.
for (Integer yellowPathList1 : yellowPathList) {
gameBoardMap.getCell(yellowPathList1).setEnabled(true);
}
} else if (players.get(curPlayer).getColor() == Color.blue) {
// Enable init pawns
for (int i = 0; i < blueInitPos.length; i++) {
gameBoardMap.getCell(blueInitPos[i]).setEnabled(true);
}
// Enable path cells.
for (Integer bluePathList1 : bluePathList) {
gameBoardMap.getCell(bluePathList1).setEnabled(true);
}
}
}
/**
* Check if player have valid moves. Scan all players pawns for the next
* curPos + dice num one by one with use o check method.
*
* @param curPlayer The play now/current player.
* @return true if have valid moves else false.
*/
public boolean checkValidMoves(int curPlayer) {
int validMoveCounter = 0;
ArrayList<Pawn> curPlayerPwns = players.get(curPlayer).getPanws();
int pawnPos = -1;
ArrayList<Integer> colorPath = null;
// Check for curPlayer color.
if (players.get(curPlayer).getColor() == Color.green) {
colorPath = greenPathList;
} else if (players.get(curPlayer).getColor() == Color.red) {
colorPath = redPathList;
} else if (players.get(curPlayer).getColor() == Color.yellow) {
colorPath = yellowPathList;
} else if (players.get(curPlayer).getColor() == Color.blue) {
colorPath = bluePathList;
}
int curCellPathPos;
// Check every pawn.
for (int i = 0; i < curPlayerPwns.size(); i++) {
// Get pawn's position in colorPath.
pawnPos = players.get(curPlayer).getPawn(i).getPosition();
curCellPathPos = colorPath.indexOf(pawnPos);
if ((gameBoardMap.getCell(pawnPos) instanceof InitCell) && gameDice.getDiceNum() == 5) {
validMoveCounter++;
} else if ((gameBoardMap.getCell(pawnPos) instanceof InitCell) && gameDice.getDiceNum() != 5) {
} else {
// Check for barrier one by one with help of checkCell.
if (gameDice.getDiceNum() <= (colorPath.size() - (curCellPathPos + 1))) {
int eachCellPathCounter = 0; // see it more
for (int j = 1; j <= gameDice.getDiceNum(); j++) {
if (gameBoardMap.getCell(colorPath.get((curCellPathPos) + j)).checkCell(players.get(curPlayer).getPawn(i))) {
eachCellPathCounter++;
}
}
if (gameDice.getDiceNum() == eachCellPathCounter) {
validMoveCounter++;
}
}
}
}
// Msg for infoJTextField about if don't have valid moves.
if (validMoveCounter == 0) {
String oldText = this.gamePanel.getInfoJTextArea().getText();
String newText = ("\n[Σύστημα]: Ο " + players.get(curPlayer).getNickname() + " δεν έχει καμία έγκυρη κίνηση διαθέσιμη.");
this.gamePanel.getInfoJTextArea().setText(oldText + newText);
JOptionPane.showMessageDialog(null, " Ο " + players.get(curPlayer).getNickname() + " δεν έχει καμία \nέγκυρη κίνηση διαθέσιμη ", " Καμία κίνηση διαθέσιμη", JOptionPane.INFORMATION_MESSAGE);
return false;
}
return true;
}
/**
* Activate Listener for Cells with curent player pawns.
*
* @param curPlayer The play now/current player.
*/
public void activeMouseGuide(int curPlayer) {
// Only uniqueeeeeeeeeeeeee positions, not two OR MORE listeners in same Cell FAIL.
for (int i = 1; i < gameBoardSize * gameBoardSize; i++) {
// If cell isn't empty.
if (!gameBoardMap.getCell(i).getCellPawns().isEmpty()) {
// Store fast cells's pawns
HashSet<Pawn> cellPawns = gameBoardMap.getCell(i).getCellPawns();
// Check each pawn/pawns
for (Pawn tempPawnOfCell : cellPawns) {
// If pawn belong to current player.
if (tempPawnOfCell.getOwner() == players.get(curPlayer)) {
int count = -1;
// Take player's all pawns.
ArrayList<Pawn> tempPawns = players.get(curPlayer).getPanws();
// Compare this cell with the others of player is hava the same position
// if have two or more on same cell MUST add only one listener.
for (Pawn tempPawn : tempPawns) {
count++;
if (tempPawn.getPosition() == tempPawnOfCell.getPosition()) {
break;
}
}
// Add Listener to cell based on players's color.
if (players.get(curPlayer).getColor() == Color.green) {
gameBoardMap.getCell(i).addMouseListener(new MouseOverAndClickListener(count, i, gameDice.getDiceNum(), players.get(curPlayer), gameBoardMap, greenPathList));
} else if (players.get(curPlayer).getColor() == Color.red) {
gameBoardMap.getCell(i).addMouseListener(new MouseOverAndClickListener(count, i, gameDice.getDiceNum(), players.get(curPlayer), gameBoardMap, redPathList));
} else if (players.get(curPlayer).getColor() == Color.yellow) {
gameBoardMap.getCell(i).addMouseListener(new MouseOverAndClickListener(count, i, gameDice.getDiceNum(), players.get(curPlayer), gameBoardMap, yellowPathList));
} else if (players.get(curPlayer).getColor() == Color.blue) {
gameBoardMap.getCell(i).addMouseListener(new MouseOverAndClickListener(count, i, gameDice.getDiceNum(), players.get(curPlayer), gameBoardMap, bluePathList));
}
break;
}
}
}
}
}
/**
* Every button have MouseListener in game board now would not have. Do it
* for extra safety reasons.
*/
public void disableMouseGuide() {
// Scan all Cells.
for (int i = 1; i < gameBoardSize * gameBoardSize; i++) {
// If have mouse listeners, remove them all.
for (MouseListener ml : gameBoardMap.getCell(i).getMouseListeners()) {
gameBoardMap.getCell(i).removeMouseListener(ml);
}
}
}
/**
* Check all player's pawns whether located in FinalCell. If have winner
* show a message and close the game.
*/
private void isGameFinished() {
int curPos;
int countFin;
// Scan every player.
for (Player player : this.players) {
countFin = 0;
// Scan player pawns.
for (int j = 0; j < player.getPanws().size(); j++) {
curPos = player.getPawn(j).getPosition();
if (gameBoardMap.getCell(curPos) instanceof FinalCell) {
countFin++;
}
}
if (countFin == player.getPanws().size()) {
// Close application
String oldText = this.gamePanel.getInfoJTextArea().getText();
String newText = ("\n[Σύστημα]: Συγχαρητήρια " + player.getNickname() + " είσαι ο νικητής.");
this.gamePanel.getInfoJTextArea().setText(oldText + newText);
JOptionPane.showMessageDialog(gamePanel, "Συγχαρητήρια " + player.getNickname() + " είσαι ο νικητής.", "Συγχαρητήρια " + player.getNickname(), JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
}
}
// LISTENER //
/**
* MouseOverAndClickListener Class used for detect some mouse events like
* mouseEntered, mouseExited & mousemouseClicked. Used for the mouseOver
* function and for the interface between the player and the gameboard.
*/
private class MouseOverAndClickListener extends MouseAdapter {
// Basic class fields.
private int playerPawnNum;
private int curCellNum;
private int diceNum;
private Player curPlayer;
private GameBoardMap gameBoardMap;
private ArrayList<Integer> colorPath;
/**
* Constractor of MouseOverAndClickListener only initialize the fields of class.
*/
public MouseOverAndClickListener(int playerPawnNum, int curCellNum, int diceNum, Player curPlayer, GameBoardMap gameBoardMap, ArrayList<Integer> colorPath) {
this.playerPawnNum = playerPawnNum;
this.curCellNum = curCellNum;
this.diceNum = diceNum;
this.curPlayer = curPlayer;
this.gameBoardMap = gameBoardMap;
this.colorPath = colorPath;
}
/**
* When mouseEntered check the current Cell and change the current Cell+ dice number Border to
* LineBorder(Color.black, 5) to show where pawn go, in init case show the start position and in
* init case without 5 just disable the init Cell/JButton.
* @param evt Not used.
*/
@Override
public void mouseEntered(MouseEvent evt) {
Border borderMouseOver = new LineBorder(Color.black, 5);
if ((gameBoardMap.getCell(curCellNum) instanceof InitCell) && (gameBoardMap.getCell(curCellNum).getCellPawns().isEmpty())) {
gameBoardMap.getCell(curCellNum).setEnabled(false);
} else if ((gameBoardMap.getCell(curCellNum) instanceof InitCell) && (diceNum == 5)) {
gameBoardMap.getCell(colorPath.get(0)).setBorder(borderMouseOver);
} else if ((gameBoardMap.getCell(curCellNum) instanceof InitCell) && (diceNum != 5)) {
gameBoardMap.getCell(curCellNum).setEnabled(false);
} else if (!(gameBoardMap.getCell(curCellNum).getCellPawns().isEmpty())) { // gia gemata mono.
int curCellPathPos = colorPath.indexOf(curCellNum);
if (diceNum <= (colorPath.size() - (curCellPathPos + 1))) {
gameBoardMap.getCell(colorPath.get(curCellPathPos + diceNum)).setBorder(borderMouseOver);
} else {
//do nothing
}
}
}
/**
* When mouseExited check the current Cell and set the current Cell+ dice number Border to createLineBorder,
* in init case also Border to createLineBorder for start position and in init case without 5 just enable
* again the init Cell/JButton.
* @param evt Not used.
*/
@Override
public void mouseExited(MouseEvent evt) {
if ((gameBoardMap.getCell(curCellNum) instanceof InitCell) && (gameBoardMap.getCell(curCellNum).getCellPawns().isEmpty())) {
gameBoardMap.getCell(curCellNum).setEnabled(false);
gameBoardMap.getCell(colorPath.get(0)).setBorder(BorderFactory.createLineBorder(Color.black));
} else if ((gameBoardMap.getCell(curCellNum) instanceof InitCell) && (diceNum == 5)) {
gameBoardMap.getCell(colorPath.get(0)).setBorder(BorderFactory.createLineBorder(Color.black));
} else if ((gameBoardMap.getCell(curCellNum) instanceof InitCell) && (diceNum != 5)) {
gameBoardMap.getCell(curCellNum).setEnabled(true);
} else { //if (!(gameBoardMap.getCell(curCellNum).getCellPawns().isEmpty())) {
int curCellPathPos = colorPath.indexOf(curCellNum);
if (diceNum <= (colorPath.size() - (curCellPathPos + 1))) {
gameBoardMap.getCell(colorPath.get(curCellPathPos + diceNum)).setBorder(BorderFactory.createLineBorder(Color.black));
} else {
// Do nothnig
}
}
}
/**
* When mouseClicked control all the possible scenarios and essentially applied the logic of the
* game more specific check if to move from InitCell or StarCell, if moves are valid, if you have
* the exact number for the FinalCell, if can play again, if there is barrier, if caught pawn go
* to InitCell of rival, inform user via game logs text field, which button should be enabled or
* not and maybe more.
* @param evt Not used.
*/
@Override
public void mouseClicked(MouseEvent evt) {
// Take clicked cell available pawns.
HashSet<Pawn> cellPawns = gameBoardMap.getCell(curCellNum).getCellPawns();
Pawn playerPawn = null;
// I want to take my pawn (my color pawn) this used for case of Cicle or barier_simple_cell.
Iterator iter = cellPawns.iterator();
while (iter.hasNext()) {
playerPawn = (Pawn) iter.next();
if (playerPawn.getOwner().getColor() == curPlayer.getColor()) {
break;
}
}
// Check if is empty
if (playerPawn != null) {
if ((gameBoardMap.getCell(curCellNum) instanceof InitCell) && diceNum == 5) {
if (gameBoardMap.getCell(colorPath.get(0)).checkCell(playerPawn)) {
gameBoardMap.getCell(curCellNum).removePawn(playerPawn); // Remove from old.
// Update pawn munber via player's pawns.
curPlayer.setPanws(playerPawnNum, colorPath.get(0));
playerPawn.setPosition(colorPath.get(0));
Pawn catchPawn = gameBoardMap.getCell(colorPath.get(0)).addPawn(playerPawn); // Add to new.
gameBoardMap.getCell(colorPath.get(0)).setBorder(BorderFactory.createLineBorder(Color.black));
movePlayMsgUpdate(curPlayer, playerPawnNum, -1, colorPath.get(0));
if (catchPawn != null) { // If Thhere are others pawns.
ArrayList<Pawn> catchPlayerPwans = catchPawn.getOwner().getPanws();
int catchPawnPos = -1;
for (Pawn catchPlayerPwan : catchPlayerPwans) {
catchPawnPos++;
if (catchPlayerPwan == catchPawn) {
break;
}
}
catchMsgUpdate(curPlayer, catchPawn.getOwner(), catchPawnPos);
if (catchPawn.getOwner().getColor() == Color.green) {
catchPawn.getOwner().getPawn(catchPawnPos).setPosition(greenInitPos[catchPawnPos]);
gameBoardMap.getCell(greenInitPos[catchPawnPos]).addPawn(catchPawn);
} else if (catchPawn.getOwner().getColor() == Color.red) {
catchPawn.getOwner().getPawn(catchPawnPos).setPosition(redInitPos[catchPawnPos]);
gameBoardMap.getCell(redInitPos[catchPawnPos]).addPawn(catchPawn);
} else if (catchPawn.getOwner().getColor() == Color.yellow) {
catchPawn.getOwner().getPawn(catchPawnPos).setPosition(yellowInitPos[catchPawnPos]);
gameBoardMap.getCell(yellowInitPos[catchPawnPos]).addPawn(catchPawn);
} else if (catchPawn.getOwner().getColor() == Color.blue) {
catchPawn.getOwner().getPawn(catchPawnPos).setPosition(blueInitPos[catchPawnPos]);
gameBoardMap.getCell(blueInitPos[catchPawnPos]).addPawn(catchPawn);
}
}
// Play again.
disableMouseGuide();
playAgainMsgUpdate(curPlayer, 0);
gamePanel.getDiceImgLabel().setIcon(null);
gamePanel.getDiceButton().setEnabled(true);
gamePanel.getFinishMoveJButton().setEnabled(false);
} else {
JOptionPane.showMessageDialog(null, " Δεν μπορείς να μετακινήσεις τι πιόνι διότι,\n εχει δημιουργηθεί φραγμα. ", " Αδύνατη Κίνηση ", JOptionPane.INFORMATION_MESSAGE);
gameBoardMap.getCell(colorPath.get(0)).setBorder(BorderFactory.createLineBorder(Color.black));
gamePanel.getFinishMoveJButton().doClick();
}
} else if ((gameBoardMap.getCell(curCellNum) instanceof InitCell) && diceNum != 5) {
JOptionPane.showMessageDialog(null, " Δεν μπορείς να μετακινήσεις πιόνι που είναι σε αρχική θέση, \n χωρίς να έχεις φέρει 5. ", " Αδύνατη Κίνηση ", JOptionPane.INFORMATION_MESSAGE);
} else {
int curCellPathPos = colorPath.indexOf(curCellNum);
if (diceNum <= (colorPath.size() - (curCellPathPos + 1))) {
int eachCellPathCounter = 0;
for (int j = 1; j <= gameDice.getDiceNum(); j++) {
if (gameBoardMap.getCell(colorPath.get((curCellPathPos) + j)).checkCell(curPlayer.getPawn(playerPawnNum))) {
eachCellPathCounter++;
}
}
if (gameDice.getDiceNum() == eachCellPathCounter) {
if (gameBoardMap.getCell(colorPath.get(curCellPathPos + diceNum)).checkCell(playerPawn)) {
gameBoardMap.getCell(curCellNum).removePawn(playerPawn); // Remove from old.
// Update pawn munber via player's pawns.
curPlayer.setPanws(playerPawnNum, colorPath.get(curCellPathPos + diceNum));
playerPawn.setPosition(colorPath.get(curCellPathPos + diceNum));
Pawn catchPawn = gameBoardMap.getCell(colorPath.get(curCellPathPos + diceNum)).addPawn(playerPawn); // Add to new.
gameBoardMap.getCell(colorPath.get(curCellPathPos + diceNum)).setBorder(BorderFactory.createLineBorder(Color.black));
movePlayMsgUpdate(curPlayer, playerPawnNum, colorPath.get(curCellPathPos), colorPath.get(curCellPathPos + diceNum));
// If have pawn move to init area of otherPlayer.
if (catchPawn != null) { // There are others pawns.
ArrayList<Pawn> catchPlayerPwans = catchPawn.getOwner().getPanws();
int catchPawnPos = -1;
for (Pawn catchPlayerPwan : catchPlayerPwans) {
catchPawnPos++;
if (catchPlayerPwan == catchPawn) {
break;
}
}
catchMsgUpdate(curPlayer, catchPawn.getOwner(), catchPawnPos);
if (catchPawn.getOwner().getColor() == Color.green) {
catchPawn.getOwner().getPawn(catchPawnPos).setPosition(greenInitPos[catchPawnPos]);
gameBoardMap.getCell(greenInitPos[catchPawnPos]).addPawn(catchPawn);
} else if (catchPawn.getOwner().getColor() == Color.red) {
catchPawn.getOwner().getPawn(catchPawnPos).setPosition(redInitPos[catchPawnPos]);
gameBoardMap.getCell(redInitPos[catchPawnPos]).addPawn(catchPawn);
} else if (catchPawn.getOwner().getColor() == Color.yellow) {
catchPawn.getOwner().getPawn(catchPawnPos).setPosition(yellowInitPos[catchPawnPos]);
gameBoardMap.getCell(yellowInitPos[catchPawnPos]).addPawn(catchPawn);
} else if (catchPawn.getOwner().getColor() == Color.blue) {
catchPawn.getOwner().getPawn(catchPawnPos).setPosition(blueInitPos[catchPawnPos]);
gameBoardMap.getCell(blueInitPos[catchPawnPos]).addPawn(catchPawn);
}
}
// Star case
boolean existNextStar = false;
if ((gameBoardMap.getCell(colorPath.get(curCellPathPos + diceNum))) instanceof StarCell) {
int count = 0;
for (int i = (curCellPathPos + diceNum); i < (colorPath.size() - 1); i++) {
count++;
if (gameBoardMap.getCell(colorPath.get(curCellPathPos + diceNum + count)) instanceof StarCell) {
existNextStar = true;
break;
}
}
if (existNextStar == true) {
int starCellNum = colorPath.get(curCellPathPos + diceNum + count);
gameBoardMap.getCell(colorPath.get(curCellPathPos + diceNum)).removePawn(playerPawn); // REMOVE FROM OLD
// Update pawn munber via player's pawns.
curPlayer.setPanws(playerPawnNum, starCellNum);
playerPawn.setPosition(starCellNum);
Pawn catchStarPawn = gameBoardMap.getCell(starCellNum).addPawn(playerPawn); //add to new & return content.
starMoveMsgUpdate(curPlayer, (colorPath.get(curCellPathPos + diceNum + count)));
JOptionPane.showMessageDialog(null, curPlayer.getNickname() + ", μεταφέρθηκες στο επόμενο StarCell.", " StarCell Κίνηση ", JOptionPane.INFORMATION_MESSAGE);
// in have pawn in moved star cell, go old to init area of otherPlayer.
if (catchStarPawn != null) { // there are others pawns
ArrayList<Pawn> catchPlayerPwans = catchStarPawn.getOwner().getPanws();
int catchStarPawnPos = -1;
for (Pawn catchPlayerPwan : catchPlayerPwans) {
catchStarPawnPos++;
if (catchPlayerPwan == catchStarPawn) {
break;
}
}
catchMsgUpdate(curPlayer, catchStarPawn.getOwner(), catchStarPawnPos);
if (catchStarPawn.getOwner().getColor() == Color.green) {
catchStarPawn.getOwner().getPawn(catchStarPawnPos).setPosition(greenInitPos[catchStarPawnPos]);
gameBoardMap.getCell(greenInitPos[catchStarPawnPos]).addPawn(catchStarPawn);
} else if (catchStarPawn.getOwner().getColor() == Color.red) {
catchStarPawn.getOwner().getPawn(catchStarPawnPos).setPosition(redInitPos[catchStarPawnPos]);
gameBoardMap.getCell(redInitPos[catchStarPawnPos]).addPawn(catchStarPawn);
} else if (catchStarPawn.getOwner().getColor() == Color.yellow) {
catchStarPawn.getOwner().getPawn(catchStarPawnPos).setPosition(yellowInitPos[catchStarPawnPos]);
gameBoardMap.getCell(yellowInitPos[catchStarPawnPos]).addPawn(catchStarPawn);
} else if (catchStarPawn.getOwner().getColor() == Color.blue) {
catchStarPawn.getOwner().getPawn(catchStarPawnPos).setPosition(blueInitPos[catchStarPawnPos]);
gameBoardMap.getCell(blueInitPos[catchStarPawnPos]).addPawn(catchStarPawn);
}
}
} else {
JOptionPane.showMessageDialog(null, curPlayer.getNickname() + ", δεν μπορείς να μετακινηθείς στο επόμενο StarCell μιας \n και εισαι ήδη στο τελευταίο της διαδρομής σου. ", " Αδύνατη Κίνηση ", JOptionPane.INFORMATION_MESSAGE);
}
}
if (gameBoardMap.getCell(colorPath.get(curCellPathPos + diceNum)) instanceof FinalCell) {
int playersPawnNum = -1;
ArrayList<Pawn> myPawns = curPlayer.getPanws();
for (Pawn myPawns1 : myPawns) {
playersPawnNum++;
if (myPawns1 == playerPawn) {
break;
}
}
pawnFinishMsgUpdate(curPlayer, playersPawnNum);
}
} else {
JOptionPane.showMessageDialog(null, " Δεν μπορείς να μετακινήσεις τι πιόνι διότι,\n εχει δημιουργηθεί φράγμα. ", " Αδύνατη Κίνηση ", JOptionPane.INFORMATION_MESSAGE);
gameBoardMap.getCell(colorPath.get(curCellPathPos + diceNum)).setBorder(BorderFactory.createLineBorder(Color.black));
}
} else {
JOptionPane.showMessageDialog(null, " Δεν μπορείς να μετακινήσεις τι πιόνι διότι,\n εχει δημιουργηθεί φράγμα. ", " Αδύνατη Κίνηση ", JOptionPane.INFORMATION_MESSAGE);
gameBoardMap.getCell(colorPath.get(curCellPathPos + diceNum)).setBorder(BorderFactory.createLineBorder(Color.black));
}
} else {
JOptionPane.showMessageDialog(null, " Πρέπει να φέρεις τον ακριβή αριθμό του κεντρικού κελιού δηλαδή " + ((colorPath.size()) - (curCellPathPos + 1)) + ".", " Αδύνατη Κίνηση ", JOptionPane.INFORMATION_MESSAGE);
}
// Play again ig dicenum == 6.
if (diceNum == 6) {
disableMouseGuide();
playAgainMsgUpdate(curPlayer, 1);
gamePanel.getDiceImgLabel().setIcon(null);
gamePanel.getDiceButton().setEnabled(true);
gamePanel.getFinishMoveJButton().setEnabled(false);
gamePanel.getDiceButton().setEnabled(true);
gamePanel.getFinishMoveJButton().setEnabled(false);
}
gamePanel.getFinishMoveJButton().doClick();
}
} else {
// Donothing.
}
isGameFinished();
}
}
}
| AlexandrosPlessias/Ludo-Griniaris-Game | src/GameplayAndLogic/Gameplay.java |
2,455 | package com.example.demo.booking;
import com.example.demo.config.InfoResponse;
import com.example.demo.trip.Trip;
import com.example.demo.trip.TripRepository;
import com.example.demo.user.Citizen;
import com.example.demo.user.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import java.time.LocalDate;
@Service
public class BookingService {
@Autowired
private BookingRepository bookingRepository;
@Autowired
private TripRepository tripRepository;
public ResponseEntity<?> insertBooking(BookingRequest bookingRequest, User user) {
int seats = bookingRequest.getSeats();
if (seats < 1) {
return ResponseEntity.status(HttpStatus.FORBIDDEN).body(new InfoResponse("Ο αριθμός συμμετοχών πρέπει να είναι μεγαλύτερος του μηδενός"));
}
Trip trip = tripRepository.findById(bookingRequest.getTripID()).orElse(null);
if (trip == null) {
return ResponseEntity.status(HttpStatus.FORBIDDEN).body(new InfoResponse("Δεν υπάρχει η εκδρομή"));
}
if (trip.getAvailableSeats() - seats < 0) {
return ResponseEntity.status(HttpStatus.FORBIDDEN).body(new InfoResponse("Δεν υπάρχουν διαθέσιμες θέσεις"));
}
LocalDate today = LocalDate.now();
if (today.isAfter(trip.getStartDate())) {
return ResponseEntity.status(HttpStatus.FORBIDDEN).body(new InfoResponse("Δεν μπορείτε πλέον να κλείσετε θέση"));
}
trip.setBookedSeats(trip.getBookedSeats() + seats);
tripRepository.save(trip);
Booking booking = new Booking(trip, (Citizen) user, seats);
bookingRepository.save(booking);
return ResponseEntity.ok().body(new InfoResponse("Ολοκληρώθηκε με επιτυχία"));
}
} | iliananat/Excursion-Organization-System | demo/src/main/java/com/example/demo/booking/BookingService.java |
2,458 | package view;
import com.google.gson.*;
import java.awt.*;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.text.ParseException;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import model.AddDataController;
import model.QueriesSQL;
import static view.Helper.getJsonStrFromApiURL;
import static view.Helper.getUrlStrForDateRange;
import static view.Helper.jokerJsonSingleDrawToObject;
/**
* @author Athanasios Theodoropoulos
* @author Alexandros Dimitrakopoulos
* @author Odysseas Raftopoulos
* @author Xristoforos Ampelas
*/
public class WindowManageData
{
// Variables declaration
private String firstDrawDate;
private int firstDrawId;
private int lastDrawId = 0;
private String lastSearchjsonStr;
private List<String> lastSearchjsonStrList = new ArrayList<>();
private final JDialog dialog;
private final JComboBox comboBoxGameSelect;
private final JLabel labelDrawInfo;
private final JRadioButton radioButtonSingleDraw;
private final JTextField textFieldDrawId;
private final JTextField textFieldDate1;
private final JTextField textFieldDate2;
private final JComboBox comboBoxPredefinedRange;
private final JTextField textFieldDBDate1;
private final JTextField textFieldDBDate2;
private final JButton buttonDelAllForSelGameInDB;
private final JPanel viewPanelCards;
private final JLabel labelDrawValue;
private final JLabel labelDateValue;
private final JLabel labelwinNum1Value;
private final JLabel labelwinNum2Value;
private final JLabel labelwinNum3Value;
private final JLabel labelwinNum4Value;
private final JLabel labelwinNum5Value;
private final JLabel labelwinNum6Value;
private final JLabel labelTotalColumnsValue;
private final JTable jokerSDTable;
private final DefaultTableModel modeljokerDRTable;
private final JTable jokerDRTable;
// Methods
/**
* Stores the date of the 1st draw of the selected game to the variable firstDrawDate.
* firstDrawDate is used for checking if the dates are valid. This method is called
* when the window is first opened and every time a different game is selected.
*/
private void findDateOfFirstDraw()
{
// The 1st draw can be found from: "https://api.opap.gr/draws/v3.0/{gameId}/1".
// Kino is an exception. It's earliest data are from about 3 years in the past.
if (comboBoxGameSelect.getSelectedItem().equals("Κίνο"))
{
// Current local date
LocalDate dateNow = LocalDate.now();
// Date format
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
firstDrawDate = formatter.format(dateNow.minusYears(3));
}
switch (comboBoxGameSelect.getSelectedItem().toString())
{
case "Powerspin": firstDrawDate = "2020-06-30"; break;
case "Super3": firstDrawDate = "2002-11-25"; break;
case "Πρότο": firstDrawDate = "2000-01-01"; break;
case "Λόττο": firstDrawDate = "2000-01-01"; break;
case "Τζόκερ": firstDrawDate = "2000-01-01"; break;
case "Extra5": firstDrawDate = "2002-11-25"; break;
}
}
/**
* Stores the id of the 1st draw of the selected game to the variable firstDrawId.
* firstDrawId is used for checking if the drawId is valid. For every game it is
* equal to 1, except for Kino. This method is called when the window is first opened
* and every time a different game is selected.
*/
private void findIdOfFirstDraw()
{
// Kino's earliest data are from about 3 years in the past.
if (comboBoxGameSelect.getSelectedItem().equals("Κίνο"))
{
// Current local date
LocalDate dateNow = LocalDate.now();
// Date format
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
// Early Kino draw date - 3 years ago
String date = formatter.format(dateNow.minusYears(3));
// URL string
String urlStr = "https://api.opap.gr/draws/v3.0/1100/draw-date/"+date+"/"+date;
try
{
// Get json string from the API
String jsonStr = getJsonStrFromApiURL(urlStr);
// Parse jsonStr into json element and get an object structure
JsonElement jElement = new JsonParser().parse(jsonStr);
JsonObject jObject = jElement.getAsJsonObject();
// Get the last draw object
JsonArray content = jObject.getAsJsonArray("content");
// Get the drawId
firstDrawId = content.get(0).getAsJsonObject().get("drawId").getAsInt();
}
catch (Exception ex) { /* Silently continue */ }
}
else
{
firstDrawId = 1;
}
}
/**
* Uses the API "https://api.opap.gr/draws/v3.0/{gameId}/last-result-and-active" to
* find the id of the latest draw of the selected game and stores it in the variable
* lastDrawId. Optionally it populates the textFieldDrawId. This method is called when
* the window is first opened and every time a different game is selected. It is also
* called when trying to use the API, if lastDrawId == 0, and is basically used
* to check the internet connection to the API.
* @param populateTextFieldDrawId When true, it populates the textFieldDrawId.
*/
private void findLastDrawId(boolean populateTextFieldDrawId)
{
// Get selected game id
String gId = null;
switch (comboBoxGameSelect.getSelectedItem().toString())
{
case "Κίνο": gId = "1100"; break;
case "Powerspin": gId = "1110"; break;
case "Super3": gId = "2100"; break;
case "Πρότο": gId = "2101"; break;
case "Λόττο": gId = "5103"; break;
case "Τζόκερ": gId = "5104"; break;
case "Extra5": gId = "5106"; break;
}
// URL string
String urlStr = "https://api.opap.gr/draws/v3.0/"+gId+"/last-result-and-active";
try
{
// Get json string from the API
String jsonStr = getJsonStrFromApiURL(urlStr);
// Parse jsonStr into json element and get an object structure
JsonElement jElement = new JsonParser().parse(jsonStr);
JsonObject jObject = jElement.getAsJsonObject();
// Get the last draw object
JsonObject lastDraw = jObject.getAsJsonObject("last");
// Get the drawId from the last draw
lastDrawId = lastDraw.get("drawId").getAsInt();
// Populate textFieldDrawId
if (populateTextFieldDrawId)
{
textFieldDrawId.setText(String.valueOf(lastDrawId));
}
}
catch (Exception ex) { /* Silently continue */ }
}
/**
* Sets the text of buttonDelAllForSelGameInDB according to what game is selected
* in comboBoxGameSelect. This method is called when the window is first opened and
* every time a different game is selected.
*/
private void setTextOfButtonDelAllForSelGameInDB()
{
String text = "Διαγραφή όλων για το " + comboBoxGameSelect.getSelectedItem().toString();
buttonDelAllForSelGameInDB.setText(text);
}
/**
* Uses the API "https://api.opap.gr/draws/v3.0/{gameId}/last-result-and-active" to
* find the dates of the last and next draws of the selected game and shows it in
* labelDrawInfo. This method is called when the window is first opened and every time
* a different game is selected.
*/
private void showDrawInfo()
{
// Date format
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
// Variables to gather data
String gName;
String lastDrawDate;
String nextDrawDate;
// Get selected game id
String gId = null;
switch (comboBoxGameSelect.getSelectedItem().toString())
{
case "Κίνο": gId = "1100"; break;
case "Powerspin": gId = "1110"; break;
case "Super3": gId = "2100"; break;
case "Πρότο": gId = "2101"; break;
case "Λόττο": gId = "5103"; break;
case "Τζόκερ": gId = "5104"; break;
case "Extra5": gId = "5106"; break;
}
// Selected game name
gName = comboBoxGameSelect.getSelectedItem().toString();
// URL string
String urlStr = "https://api.opap.gr/draws/v3.0/"+gId+"/last-result-and-active";
try
{
// Get json string from the API
String jsonStr = getJsonStrFromApiURL(urlStr);
// Parse jsonStr into json element and get an object structure
JsonElement jElement = new JsonParser().parse(jsonStr);
JsonObject jObject = jElement.getAsJsonObject();
// Get the last draw object
JsonObject lastDraw = jObject.getAsJsonObject("last");
// Get the drawTime from the last draw
Long lastDrawTime = lastDraw.get("drawTime").getAsLong();
LocalDateTime lastLdt = Instant.ofEpochMilli(lastDrawTime).atZone(ZoneId.systemDefault()).toLocalDateTime();
lastDrawDate = formatter.format(lastLdt);
// Get the active draw object
JsonObject nextDraw = jObject.getAsJsonObject("active");
// Get the drawTime from the next draw
Long nextDrawTime = nextDraw.get("drawTime").getAsLong();
LocalDateTime nextLdt = Instant.ofEpochMilli(nextDrawTime).atZone(ZoneId.systemDefault()).toLocalDateTime();
nextDrawDate = formatter.format(nextLdt);
// Populate labelDrawInfo
String text = "Η τελευταία κλήρωση του " + gName + " έγινε " + lastDrawDate +
". Η επόμενη θα γίνει " + nextDrawDate + ".";
labelDrawInfo.setText(text);
}
catch (Exception ex) { /* Silently continue */ }
}
/**
* Changes the GUI accordingly, when selecting a different game and when selecting
* single draw or date range.
*/
private void changeCards()
{
CardLayout cl = (CardLayout)(viewPanelCards.getLayout());
if (comboBoxGameSelect.getSelectedItem().equals("Τζόκερ"))
{
if (radioButtonSingleDraw.isSelected())
{
cl.show(viewPanelCards, "jokerSingleDraw");
}
else
{
cl.show(viewPanelCards, "jokerDateRange");
}
}
}
/**
* Connects to the "https://api.opap.gr/draws/v3.0/5104/{drawId}" API, gets the data
* of a single draw of the game Joker and shows them in the GUI.
*/
private void getJokerSingleDrawData()
{
// Selected Joker draw
String drawStr = textFieldDrawId.getText();
// URL string
String urlStr = "https://api.opap.gr/draws/v3.0/5104/" + drawStr;
try
{
// Get json string from the API
String jsonStr = getJsonStrFromApiURL(urlStr);
// Store json string to attribute lastSearchjsonStr (for later use in DB)
lastSearchjsonStr = jsonStr;
// Parse jsonStr into json element and get an object structure
JsonElement jElement = new JsonParser().parse(jsonStr);
JsonObject jObject = jElement.getAsJsonObject();
// Create a JokerDrawData object from the json object
JokerDrawData jokerDraw = jokerJsonSingleDrawToObject(jObject);
// Populate GUI for single draw
labelDrawValue.setText(String.valueOf(jokerDraw.getDrawId()));
labelDateValue.setText(String.valueOf(jokerDraw.getDrawDate()));
labelTotalColumnsValue.setText(String.valueOf(jokerDraw.getColumns()));
labelwinNum1Value.setText(String.valueOf(jokerDraw.getWinningNum1()));
labelwinNum2Value.setText(String.valueOf(jokerDraw.getWinningNum2()));
labelwinNum3Value.setText(String.valueOf(jokerDraw.getWinningNum3()));
labelwinNum4Value.setText(String.valueOf(jokerDraw.getWinningNum4()));
labelwinNum5Value.setText(String.valueOf(jokerDraw.getWinningNum5()));
labelwinNum6Value.setText(String.valueOf(jokerDraw.getBonusNum()));
jokerSDTable.setValueAt(jokerDraw.getPrizeTier5_1winners(), 0, 1);
jokerSDTable.setValueAt(jokerDraw.getPrizeTier5_1dividend(), 0, 2);
jokerSDTable.setValueAt(jokerDraw.getPrizeTier5winners(), 1, 1);
jokerSDTable.setValueAt(jokerDraw.getPrizeTier5dividend(), 1, 2);
jokerSDTable.setValueAt(jokerDraw.getPrizeTier4_1winners(), 2, 1);
jokerSDTable.setValueAt(jokerDraw.getPrizeTier4_1dividend(), 2, 2);
jokerSDTable.setValueAt(jokerDraw.getPrizeTier4winners(), 3, 1);
jokerSDTable.setValueAt(jokerDraw.getPrizeTier4dividend(), 3, 2);
jokerSDTable.setValueAt(jokerDraw.getPrizeTier3_1winners(), 4, 1);
jokerSDTable.setValueAt(jokerDraw.getPrizeTier3_1dividend(), 4, 2);
jokerSDTable.setValueAt(jokerDraw.getPrizeTier3winners(), 5, 1);
jokerSDTable.setValueAt(jokerDraw.getPrizeTier3dividend(), 5, 2);
jokerSDTable.setValueAt(jokerDraw.getPrizeTier2_1winners(), 6, 1);
jokerSDTable.setValueAt(jokerDraw.getPrizeTier2_1dividend(), 6, 2);
jokerSDTable.setValueAt(jokerDraw.getPrizeTier1_1winners(), 7, 1);
jokerSDTable.setValueAt(jokerDraw.getPrizeTier1_1dividend(), 7, 2);
}
catch (Exception ex) { ex.printStackTrace(); }
}
/**
* Connects to the "https://api.opap.gr/draws/v3.0/5104/draw-date/{fromDate}/{toDate}"
* API, gets the data for a date range of the game Joker and shows them in the GUI.
*/
private void getJokerDateRangeData()
{
// Variables
int maxSimConnections = 50; // Max number of simultaneous calls to the API
int threadNum; // Number of threads (simultaneous calls to the API)
List<String> urlStrList; // List with all the urls we will call
List<String> jsonStrList = new ArrayList<>(); // List with the json strings
// List with the API urls
urlStrList = getUrlStrForDateRange(5104, textFieldDate1.getText(), textFieldDate2.getText());
// Set number of threads = urlStrList.size(), but not more that maxSimConnections
threadNum = urlStrList.size();
if (threadNum > maxSimConnections) {threadNum = maxSimConnections;}
// --- Create the threads to do the job ---
GetJsonStrListFromUrlStrListMT[] threadArray = new GetJsonStrListFromUrlStrListMT[threadNum];
int taskNum = urlStrList.size(); // Total number of tasks to do
for (int i=0; i<threadNum; i++)
{
int index1 = i*taskNum/threadNum; // Each thread does index2-index1
int index2 = (i+1)*taskNum/threadNum; // tasks, from index1 to index2-1
threadArray[i] = new GetJsonStrListFromUrlStrListMT(index1, index2, urlStrList);
threadArray[i].start();
}
// Wait for all threads to finish
for (int i=0; i<threadNum; i++)
{
try
{
threadArray[i].join();
}
catch (InterruptedException ex)
{
ex.printStackTrace();
}
}
// Clear attribute lastSearchjsonStrList
lastSearchjsonStrList.clear();
// Merge results from all threads
for (GetJsonStrListFromUrlStrListMT thread : threadArray)
{
// Merge jsonStrList
thread.getJsonStrList().forEach((jsonStr) ->
{
jsonStrList.add(jsonStr);
lastSearchjsonStrList.add(jsonStr); // Add here too (for later use in DB)
});
}
// Remove the old data from the jokerDRTable, before adding the new
modeljokerDRTable.setRowCount(0);
// Parce all json strings in jsonStrList
for (int i = jsonStrList.size()-1; i >= 0; i--)
{
String jsonStr = jsonStrList.get(i);
// Parse jsonStr into json element and get an object structure
JsonElement jElement = new JsonParser().parse(jsonStr);
JsonObject jObject = jElement.getAsJsonObject();
// Get the totalElements
int totalElements = jObject.get("totalElements").getAsInt();
// If there are no draw data, go to the next jsonStrList element
if (totalElements == 0) {continue;}
// Get the "content" json array
JsonArray content = jObject.getAsJsonArray("content");
for (JsonElement drawElement : content)
{
// Get the json object from this content json element
JsonObject drawObject = drawElement.getAsJsonObject();
// Create a JokerDrawData object from the json object
JokerDrawData jokerDraw = jokerJsonSingleDrawToObject(drawObject);
// Create the text for winning column
int n1 = jokerDraw.getWinningNum1();
int n2 = jokerDraw.getWinningNum2();
int n3 = jokerDraw.getWinningNum3();
int n4 = jokerDraw.getWinningNum4();
int n5 = jokerDraw.getWinningNum5();
int n6 = jokerDraw.getBonusNum();
String winCol = "<html><pre><font face=\"arial\" color=\"rgb(32,32,192)\">" +
n1 + " " + n2 + " " + n3 + " " + n4 + " " + n5 + "</font>" +
"<font face=\"arial\" color=\"rgb(210,105,0)\"> " + n6 +
"</font></pre></html>";
// Round the PrizeTier5_1dividend and make it BigDecimal
BigDecimal bd = BigDecimal.valueOf(jokerDraw.getPrizeTier5_1dividend());
BigDecimal prizeTier5_1dividendBD = bd.setScale(2, RoundingMode.HALF_UP);
// Add a row to jokerDRTable
modeljokerDRTable.addRow(new Object[] {
jokerDraw.getDrawId(), jokerDraw.getDrawDate(),
jokerDraw.getColumns(), winCol,
jokerDraw.getPrizeTier5_1winners(), prizeTier5_1dividendBD,
jokerDraw.getPrizeTier5winners(), jokerDraw.getPrizeTier5dividend(),
jokerDraw.getPrizeTier4_1winners(), jokerDraw.getPrizeTier4_1dividend(),
jokerDraw.getPrizeTier4winners(), jokerDraw.getPrizeTier4dividend(),
jokerDraw.getPrizeTier3_1winners(), jokerDraw.getPrizeTier3_1dividend(),
jokerDraw.getPrizeTier3winners(), jokerDraw.getPrizeTier3dividend(),
jokerDraw.getPrizeTier2_1winners(), jokerDraw.getPrizeTier2_1dividend(),
jokerDraw.getPrizeTier1_1winners(), jokerDraw.getPrizeTier1_1dividend()
});
}
}
}
// Button actions
/**
* Action of the comboBoxGameSelect.
* @param evt
*/
private void comboBoxGameSelectActionPerformed(java.awt.event.ActionEvent evt)
{
changeCards();
findDateOfFirstDraw();
CompletableFuture.runAsync(() -> findIdOfFirstDraw()); // Run asynchronously
CompletableFuture.runAsync(() -> findLastDrawId(false)); // Run asynchronously
CompletableFuture.runAsync(() -> showDrawInfo()); // Run asynchronously
setTextOfButtonDelAllForSelGameInDB();
}
/**
* Action of the radioButtonSingleDraw.
* @param evt
*/
private void radioButtonSingleDrawActionPerformed(java.awt.event.ActionEvent evt)
{
changeCards();
}
/**
* Action of the radioButtonDateRange.
* @param evt
*/
private void radioButtonDateRangeActionPerformed(java.awt.event.ActionEvent evt)
{
changeCards();
}
/**
* Action of the buttonFindLatestDraw.
* @param evt
*/
private void buttonFindLatestDrawActionPerformed(java.awt.event.ActionEvent evt)
{
if (lastDrawId != 0)
{
textFieldDrawId.setText(String.valueOf(lastDrawId));
}
else
{
findLastDrawId(true);
if (lastDrawId == 0)
{
String message = "Σφάλμα σύνδεσης στο API του ΟΠΑΠ.";
JOptionPane.showMessageDialog(null, message, "Σφάλμα σύνδεσης", 0);
}
}
}
/**
* Action of the comboBoxPredefinedRange.
* @param evt
*/
private void comboBoxPredefinedRangeActionPerformed(java.awt.event.ActionEvent evt)
{
// Current local date
LocalDate dateNow = LocalDate.now();
// Date format
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
// First draw date
LocalDate first;
// Change the text in textFieldDate1 and textFieldDate2
switch (comboBoxPredefinedRange.getSelectedIndex())
{
case 0: // Last week
textFieldDate1.setText(formatter.format(dateNow.minusDays(6)));
textFieldDate2.setText(formatter.format(dateNow));
break;
case 1: // Last month
textFieldDate1.setText(formatter.format(dateNow.minusMonths(1).plusDays(1)));
textFieldDate2.setText(formatter.format(dateNow));
break;
case 2: // Last 3 months
textFieldDate1.setText(formatter.format(dateNow.minusMonths(3).plusDays(1)));
textFieldDate2.setText(formatter.format(dateNow));
break;
case 3: // Last year
textFieldDate1.setText(formatter.format(dateNow.minusYears(1).plusDays(1)));
textFieldDate2.setText(formatter.format(dateNow));
break;
case 4: // Last 5 years
textFieldDate1.setText(formatter.format(dateNow.minusYears(5).plusDays(1)));
textFieldDate2.setText(formatter.format(dateNow));
break;
case 5: // First year
textFieldDate1.setText(firstDrawDate);
first = LocalDate.parse(firstDrawDate);
textFieldDate2.setText(formatter.format(first.plusYears(1).minusDays(1)));
break;
case 6: // First 5 years
textFieldDate1.setText(firstDrawDate);
first = LocalDate.parse(firstDrawDate);
textFieldDate2.setText(formatter.format(first.plusYears(5).minusDays(1)));
break;
case 7: // All
textFieldDate1.setText(firstDrawDate);
textFieldDate2.setText(formatter.format(dateNow));
break;
}
}
/**
* Action of the buttonDownload.
* @param evt
*/
private void buttonDownloadActionPerformed(java.awt.event.ActionEvent evt)
{
// If lastDrawId remains 0, there's a connection error. So, show appropriate message.
lastDrawId = 0;
findLastDrawId(false);
if (lastDrawId == 0)
{
String message = "Σφάλμα σύνδεσης στο API του ΟΠΑΠ.";
JOptionPane.showMessageDialog(null, message, "Σφάλμα σύνδεσης", 0);
return;
}
if (radioButtonSingleDraw.isSelected())
{
String dId = textFieldDrawId.getText();
if (dId.matches("\\d+") && (Integer.parseInt(dId) >= firstDrawId) && (Integer.parseInt(dId) <= lastDrawId))
{
// Get the data for the selected draw
try
{
if (comboBoxGameSelect.getSelectedItem().equals("Τζόκερ"))
{
getJokerSingleDrawData();
}
}
catch (Exception ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(null, "Σφάλμα κλήσης στο API.", "Σφάλμα", 0);
}
}
else
{
String message = "Ο αριθμός κλήρωσης πρέπει να είναι από " + firstDrawId + " έως " + lastDrawId + ".";
JOptionPane.showMessageDialog(null, message, "Λάθος είσοδος", 0);
}
}
else
{
LocalDate firstDate = LocalDate.parse(firstDrawDate);
LocalDate dateNow = LocalDate.now();
LocalDate date1;
LocalDate date2;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
// Check if given dates are valid
String errorMsgDates = "Οι ημερομηνίες πρέπει να είναι της μορφής YYYY-MM-DD.";
try
{
date1 = LocalDate.parse(textFieldDate1.getText());
date2 = LocalDate.parse(textFieldDate2.getText());
}
catch (Exception ex)
{
JOptionPane.showMessageDialog(null, errorMsgDates, "Λάθος είσοδος", 0);
return;
}
// Chech if the date range is valid
String errorMsgRange1 = "Η αρχική ημερομηνία πρέπει να είναι από " + firstDrawDate + " και η τελική έως " + formatter.format(dateNow) + ".";
if (!date1.plusDays(1).isAfter(firstDate) || !date2.minusDays(1).isBefore(dateNow))
{
JOptionPane.showMessageDialog(null, errorMsgRange1, "Λάθος είσοδος", 0);
return;
}
String errorMsgRange2 = "Η αρχική ημερομηνία πρέπει να είναι πριν την τελική.";
if (!date1.minusDays(1).isBefore(date2))
{
JOptionPane.showMessageDialog(null, errorMsgRange2, "Λάθος είσοδος", 0);
return;
}
// Get the data for the selected date range
try
{
if (comboBoxGameSelect.getSelectedItem().equals("Τζόκερ"))
{
getJokerDateRangeData();
}
}
catch (Exception ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(null, "Σφάλμα κλήσης στο API.", "Σφάλμα", 0);
}
}
}
/**
* Action of the buttonStoreInDB.
* @param evt
*/
private void buttonStoreInDBActionPerformed(java.awt.event.ActionEvent evt)
{
// Check if Java DB server is started
try
{
DriverManager.getConnection("jdbc:derby://localhost/opapGameStatistics");
}
catch (SQLException ex)
{
String errorMsg = "Ο server της βάσης δεδομένων δεν είναι ενεργοποιημένος.";
JOptionPane.showMessageDialog(null, errorMsg, "Σφάλμα σύνδεσης στη ΒΔ", 0);
return;
}
if (radioButtonSingleDraw.isSelected())
{
try {
// Check if a search has been performed
String errorMsg = "Δεν έχει γίνει αναζήτηση για συγκεκριμένη κλήρωση!";
if (lastSearchjsonStr == null)
{
JOptionPane.showMessageDialog(null, errorMsg, "Σφάλμα", 0);
return;
}
// Json string from the last single draw search
String jsonStr = lastSearchjsonStr;
// Parse jsonStr into json element and get an object structure
JsonObject jObject = new JsonParser().parse(jsonStr).getAsJsonObject();
//INSERT data to the database
AddDataController.storeDrawsDataByDrawID(jObject);
JOptionPane.showMessageDialog(null, "Επιτυχής εισαγωγή εγγραφών",
"Ενημέρωση", JOptionPane.INFORMATION_MESSAGE);
} catch (Exception ex) {
Logger.getLogger(WindowManageData.class.getName()).log(Level.SEVERE, null, ex);
}
}
else
{
// Check if a search has been performed
String errorMsg = "Δεν έχει γίνει αναζήτηση για εύρος ημερομηνιών!";
if (lastSearchjsonStrList.isEmpty())
{
JOptionPane.showMessageDialog(null, errorMsg, "Σφάλμα", 0);
return;
}
// Parce all json strings in lastSearchjsonStrList
for (int i = 0; i < lastSearchjsonStrList.size(); i++) {
try {
String jsonStr = lastSearchjsonStrList.get(i);
// Parse jsonStr into json element and get an object structure
JsonObject jObject = new JsonParser().parse(jsonStr).getAsJsonObject();
// Get the totalElements
int totalElements = jObject.get("totalElements").getAsInt();
// If there are no draw data, go to the next jsonStrList element
if (totalElements == 0) {continue;}
AddDataController.storeDrawsDataByDateRange(jObject);
} catch (Exception ex) {
Logger.getLogger(WindowManageData.class.getName()).log(Level.SEVERE, null, ex);
}
}
JOptionPane.showMessageDialog(null, "Επιτυχής εισαγωγή εγγραφών",
"Ενημέρωση", JOptionPane.INFORMATION_MESSAGE);
}
}
/**
* Dialog box to confirm deletion from DB
*/
private int deletionConfirmationDialog() {
//add an icon the the Dialog box
ImageIcon icon = new ImageIcon(getClass().getResource("/resources/exclamation4.png"));
//create a new Panel
JPanel panel = new JPanel();
//set panel preffered size
panel.setPreferredSize(new Dimension(400, 96));
// avoid setting layout so that induvidual elements can be set manually
panel.setLayout(null);
//add a new message
JLabel label1 = new JLabel("ΠΡΟΣΟΧΗ! Αυτή η ενέργεια θα διαγράψει δεδομένα από τη βάση");
label1.setVerticalAlignment(SwingConstants.BOTTOM);
label1.setBounds(32, 16, 400, 32);
label1.setFont(new Font("Arial", Font.BOLD, 12));
label1.setHorizontalAlignment(SwingConstants.LEFT);
panel.add(label1);
//second line of the message
JLabel label2 = new JLabel("Αν είστε βέβαιοι, πατήστε ΟΚ;");
label2.setVerticalAlignment(SwingConstants.TOP);
label2.setHorizontalAlignment(SwingConstants.LEFT);
label2.setFont(new Font("Arial", Font.BOLD, 12));
label2.setBounds(32, 48, 200, 96);
panel.add(label2);
UIManager.put("OptionPane.minimumSize", new Dimension(300, 120));
//select the confirmation dialog buttons, title and add the other elements
int input = JOptionPane.showConfirmDialog(null, panel, "Επιβεβαίωση διαγραφής",
JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, icon);
//return users choice (0 for OK, 2 for Cancel)
return input;
}
/**
* Action of the buttonDelDRInDB.
* Method to delete data from the database for a specific date range
* @param evt
*/
private void buttonDelDRInDBActionPerformed(java.awt.event.ActionEvent evt) {
// Check if Java DB server is started
try
{
DriverManager.getConnection("jdbc:derby://localhost/opapGameStatistics");
}
catch (SQLException ex)
{
String errorMsg = "Ο server της βάσης δεδομένων δεν είναι ενεργοποιημένος.";
JOptionPane.showMessageDialog(null, errorMsg, "Σφάλμα σύνδεσης στη ΒΔ", 0);
return;
}
//show a confirmation dialog
int choice = deletionConfirmationDialog();
//if OK is pressed, then
if(choice == 0) {
//set date variables
LocalDate date1;
LocalDate date2;
// Check if given dates are valid
String errorMsgDates = "Οι ημερομηνίες πρέπει να είναι της μορφής YYYY-MM-DD.";
//parse dates
try {
date1 = LocalDate.parse(textFieldDBDate1.getText());
date2 = LocalDate.parse(textFieldDBDate2.getText());
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, errorMsgDates, "Λάθος είσοδος", 0);
return;
}
// Check if the date range is valid
String errorMsgRange = "Η αρχική ημερομηνία πρέπει να είναι πριν την τελική.";
if (!date1.minusDays(1).isBefore(date2)) {
JOptionPane.showMessageDialog(null, errorMsgRange, "Λάθος είσοδος", 0);
return;
}
//get LocaDate as String
String fromDate = date1.toString();
String toDate = date2.toString();
try {
//execute DELETE operation
QueriesSQL.deleteDataByDateRange(fromDate, toDate);
//Notify the user that the data were deleted
JOptionPane.showMessageDialog(null, "Επιτυχής διαγραφή",
"Ενημέρωση", JOptionPane.INFORMATION_MESSAGE);
} catch (ParseException ex) {
Logger.getLogger(WindowManageData.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
/**
* Action of the buttonDelAllForSelGameInDB.
* @param evt
*/
private void buttonDelAllForSelGameInDBActionPerformed(java.awt.event.ActionEvent evt) {
// Check if Java DB server is started
try
{
DriverManager.getConnection("jdbc:derby://localhost/opapGameStatistics");
}
catch (SQLException ex)
{
String errorMsg = "Ο server της βάσης δεδομένων δεν είναι ενεργοποιημένος.";
JOptionPane.showMessageDialog(null, errorMsg, "Σφάλμα σύνδεσης στη ΒΔ", 0);
return;
}
// Get selected game id
String gId = null;
switch (comboBoxGameSelect.getSelectedItem().toString()) {
case "Κίνο": gId = "1100"; break;
case "Powerspin": gId = "1110"; break;
case "Super3": gId = "2100"; break;
case "Πρότο": gId = "2101"; break;
case "Λόττο": gId = "5103"; break;
case "Τζόκερ": gId = "5104"; break;
case "Extra5": gId = "5106"; break;
}
//convert game ID to Integer
int gameId = Integer.parseInt(gId);
//call the confirmation dialog
int choice = deletionConfirmationDialog();
//if answer is OK then
if(choice == 0) {
//calling function to delete data for selected game ID
QueriesSQL.deleteDataByGameId(gameId);
JOptionPane.showMessageDialog(null, "Επιτυχής διαγραφή",
"Ενημέρωση", JOptionPane.INFORMATION_MESSAGE);
}
}
/**
* Action of the buttonClose.
* @param evt
*/
private void buttonCloseActionPerformed(java.awt.event.ActionEvent evt)
{
dialog.dispose();
}
// Constructor
public WindowManageData()
{
// Background color
Color backColor = new java.awt.Color(244, 244, 250);
// Icons list
final List<Image> icons = new ArrayList<>();
try
{
icons.add(ImageIO.read(getClass().getResource("/resources/icon_16.png")));
icons.add(ImageIO.read(getClass().getResource("/resources/icon_20.png")));
icons.add(ImageIO.read(getClass().getResource("/resources/icon_24.png")));
icons.add(ImageIO.read(getClass().getResource("/resources/icon_28.png")));
icons.add(ImageIO.read(getClass().getResource("/resources/icon_32.png")));
icons.add(ImageIO.read(getClass().getResource("/resources/icon_40.png")));
icons.add(ImageIO.read(getClass().getResource("/resources/icon_48.png")));
icons.add(ImageIO.read(getClass().getResource("/resources/icon_56.png")));
icons.add(ImageIO.read(getClass().getResource("/resources/icon_64.png")));
}
catch (Exception ex)
{
ex.printStackTrace();
}
// Font
Font fontRobotoRegular = null;
try
{
fontRobotoRegular = Font.createFont(Font.PLAIN, getClass().getResourceAsStream("/resources/Roboto-Regular.ttf"));
}
catch (FontFormatException | IOException ex)
{
System.err.println(ex);
fontRobotoRegular = new Font("Dialog", 0, 12); // Fallback, not suppose to happen
}
/*
* Top panel with the window title
*/
JPanel topPanel = new JPanel();
topPanel.setBorder(BorderFactory.createEmptyBorder(8, 0, 18, 0));
topPanel.setLayout(new FlowLayout(1, 0, 0));
topPanel.setBackground(backColor);
JPanel titlePanel = new JPanel();
titlePanel.setLayout(new OverlayLayout(titlePanel));
titlePanel.setBackground(backColor);
// Labels with the title
JLabel labelTitle = new JLabel("Διαχείριση δεδομένων");
labelTitle.setFont(new Font(null, 3, 42));
labelTitle.setForeground(Color.ORANGE);
JLabel labelTitleShadow = new JLabel("Διαχείριση δεδομένων");
labelTitleShadow.setBorder(BorderFactory.createEmptyBorder(5, 1, 0, 0));
labelTitleShadow.setFont(new Font(null, 3, 42));
labelTitleShadow.setForeground(Color.BLUE);
titlePanel.add(labelTitle);
titlePanel.add(labelTitleShadow);
topPanel.add(titlePanel);
/*
* Middle panel with all the functionality
*/
JPanel middlePanel = new JPanel();
middlePanel.setBorder(BorderFactory.createEmptyBorder(0, 20, 0, 20));
middlePanel.setLayout(new BoxLayout(middlePanel, BoxLayout.Y_AXIS));
middlePanel.setBackground(backColor);
// Game selection & download panel
JPanel gameSelectPanel = new JPanel();
gameSelectPanel.setLayout(new FlowLayout(0, 0, 0)); // align,hgap,vgap (1,5,5)
gameSelectPanel.setLayout(new BoxLayout(gameSelectPanel, BoxLayout.X_AXIS));
gameSelectPanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, gameSelectPanel.getMinimumSize().height));
gameSelectPanel.setBackground(backColor);
// Label game select
JLabel labelGameSelect = new JLabel("Επιλέξτε τυχερό παιχνίδι");
// ComboBox game select
String opapGames[] = {"Τζόκερ"};
comboBoxGameSelect = new JComboBox(opapGames);
comboBoxGameSelect.setMaximumSize(new Dimension(comboBoxGameSelect.getMinimumSize().width, comboBoxGameSelect.getMinimumSize().height));
comboBoxGameSelect.addActionListener(this::comboBoxGameSelectActionPerformed);
comboBoxGameSelect.setBackground(backColor);
// Label with info of the last and next draw
labelDrawInfo = new JLabel();
labelDrawInfo.setFont(fontRobotoRegular.deriveFont(0, 12));
labelDrawInfo.setForeground(Color.DARK_GRAY);
gameSelectPanel.add(labelGameSelect);
gameSelectPanel.add(Box.createRigidArea(new Dimension(10,0)));
gameSelectPanel.add(comboBoxGameSelect);
gameSelectPanel.add(Box.createRigidArea(new Dimension(50,0)));
gameSelectPanel.add(Box.createHorizontalGlue());
gameSelectPanel.add(labelDrawInfo);
// Choose search method label panel
JPanel chooseMethodLabelPanel = new JPanel();
chooseMethodLabelPanel.setBorder(BorderFactory.createEmptyBorder(12, 0, 6, 0));
chooseMethodLabelPanel.setLayout(new FlowLayout(0, 0, 0));
chooseMethodLabelPanel.setBackground(backColor);
// Label choose method
JLabel labelChooseMethod = new JLabel("Επιλέξτε τρόπο αναζήτησης κληρώσεων");
chooseMethodLabelPanel.add(labelChooseMethod);
chooseMethodLabelPanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, chooseMethodLabelPanel.getMinimumSize().height));
// Choose search method and download panel
JPanel chooseMethodAndDLPanel = new JPanel();
chooseMethodAndDLPanel.setLayout(new BoxLayout(chooseMethodAndDLPanel, BoxLayout.X_AXIS));
chooseMethodAndDLPanel.setBackground(backColor);
// Choose search method panel
JPanel chooseMethodPanel = new JPanel();
chooseMethodPanel.setLayout(new BoxLayout(chooseMethodPanel, BoxLayout.Y_AXIS));
chooseMethodPanel.setBackground(backColor);
// Single draw method panel
JPanel singleDrawMethodPanel = new JPanel();
singleDrawMethodPanel.setLayout(new FlowLayout(0, 0, 0));
singleDrawMethodPanel.setBackground(backColor);
// Radio button for single draw
radioButtonSingleDraw = new JRadioButton();
radioButtonSingleDraw.setText("Συγκεκριμένη κλήρωση");
radioButtonSingleDraw.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 0));
radioButtonSingleDraw.addActionListener(this::radioButtonSingleDrawActionPerformed);
radioButtonSingleDraw.setBackground(backColor);
radioButtonSingleDraw.setSelected(false);
// Label draw id
JLabel labelDrawId = new JLabel("Αριθμός κλήρωσης");
labelDrawId.setBorder(BorderFactory.createEmptyBorder(0, 30, 0, 6));
// Text field for draw id
textFieldDrawId = new JTextField();
textFieldDrawId.setBorder(BorderFactory.createEmptyBorder(0, 4, 0, 4));
textFieldDrawId.setPreferredSize(new Dimension(58, 20));
// Button to find latest draw
JButton buttonFindLatestDraw = new JButton("Εύρεση τελευταίας κλήρωσης");
buttonFindLatestDraw.setPreferredSize(new Dimension(buttonFindLatestDraw.getMinimumSize().width, 20));
buttonFindLatestDraw.addActionListener(this::buttonFindLatestDrawActionPerformed);
singleDrawMethodPanel.add(radioButtonSingleDraw);
singleDrawMethodPanel.add(labelDrawId);
singleDrawMethodPanel.add(textFieldDrawId);
singleDrawMethodPanel.add(Box.createRigidArea(new Dimension(91,0)));
singleDrawMethodPanel.add(buttonFindLatestDraw);
singleDrawMethodPanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, singleDrawMethodPanel.getMinimumSize().height));
// Date range method panel
JPanel dateRangeMethodPanel = new JPanel();
dateRangeMethodPanel.setBorder(BorderFactory.createEmptyBorder(6, 0, 0, 0));
dateRangeMethodPanel.setLayout(new FlowLayout(0, 0, 0));
dateRangeMethodPanel.setBackground(backColor);
// Radio button for date range
JRadioButton radioButtonDateRange = new JRadioButton();
radioButtonDateRange.setText("Εύρος ημερομηνιών");
radioButtonDateRange.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 0));
radioButtonDateRange.addActionListener(this::radioButtonDateRangeActionPerformed);
radioButtonDateRange.setBackground(backColor);
radioButtonDateRange.setSelected(true);
// Group radio butttons
ButtonGroup groupChooseMethod = new ButtonGroup();
groupChooseMethod.add(radioButtonSingleDraw);
groupChooseMethod.add(radioButtonDateRange);
// Label from
JLabel labelFrom = new JLabel("Από");
labelFrom.setBorder(BorderFactory.createEmptyBorder(0, 53, 0, 6));
// Text field for date 1
textFieldDate1 = new JTextField();
textFieldDate1.setBorder(BorderFactory.createEmptyBorder(0, 4, 0, 4));
textFieldDate1.setPreferredSize(new Dimension(80, 20));
// Label up to
JLabel labelUpTo = new JLabel("Έως");
labelUpTo.setBorder(BorderFactory.createEmptyBorder(0, 8, 0, 6));
// Text field for date 2
textFieldDate2 = new JTextField();
textFieldDate2.setBorder(BorderFactory.createEmptyBorder(0, 4, 0, 4));
textFieldDate2.setPreferredSize(new Dimension(80, 20));
// Label predefined date range
JLabel labelPredefinedRange = new JLabel("Προκαθορισμένες επιλογές");
labelPredefinedRange.setBorder(BorderFactory.createEmptyBorder(0, 30, 0, 6));
// ComboBox quick select
String dateRanges[] = {"Τελευταία εβδομάδα", "Τελευταίος μήνας",
"Τελευταίο 3μηνο", "Τελευταίο έτος", "Τελευταία 5ετία",
"Πρώτο έτος", "Πρώτη 5ετία", "Όλες οι κληρώσεις"};
comboBoxPredefinedRange = new JComboBox(dateRanges);
comboBoxPredefinedRange.setPreferredSize(new Dimension(comboBoxPredefinedRange.getMinimumSize().width, 20));
comboBoxPredefinedRange.addActionListener(this::comboBoxPredefinedRangeActionPerformed);
comboBoxPredefinedRange.setSelectedIndex(0);
comboBoxPredefinedRange.setBackground(backColor);
dateRangeMethodPanel.add(radioButtonDateRange);
dateRangeMethodPanel.add(labelFrom);
dateRangeMethodPanel.add(textFieldDate1);
dateRangeMethodPanel.add(labelUpTo);
dateRangeMethodPanel.add(textFieldDate2);
dateRangeMethodPanel.add(labelPredefinedRange);
dateRangeMethodPanel.add(Box.createRigidArea(new Dimension(4,0)));
dateRangeMethodPanel.add(comboBoxPredefinedRange);
dateRangeMethodPanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, dateRangeMethodPanel.getMinimumSize().height));
chooseMethodPanel.add(singleDrawMethodPanel);
chooseMethodPanel.add(dateRangeMethodPanel);
// Button download
JButton buttonDownload = new JButton("Αναζήτηση και προβολή δεδομένων");
buttonDownload.setPreferredSize(new Dimension(buttonDownload.getMinimumSize().width, 46));
buttonDownload.setMaximumSize(new Dimension(buttonDownload.getMinimumSize().width, 46));
buttonDownload.addActionListener((evt) ->
{
CompletableFuture.runAsync(() -> this.buttonDownloadActionPerformed(evt));
});
chooseMethodAndDLPanel.add(chooseMethodPanel);
chooseMethodAndDLPanel.add(buttonDownload);
// Data base panel
JPanel dbPanelBorder = new JPanel();
dbPanelBorder.setLayout(new FlowLayout(0, 0, 0)); // align,hgap,vgap (1,5,5)
dbPanelBorder.setBorder(BorderFactory.createTitledBorder(null, "Διαχείρηση βάσης δεδομένων", 0, 0, new Font(null, 0, 12)));
dbPanelBorder.setBackground(backColor);
JPanel dbPanel = new JPanel();
dbPanel.setBorder(BorderFactory.createEmptyBorder(1, 8, 8, 8));
dbPanel.setLayout(new FlowLayout(0, 0, 0)); // align,hgap,vgap (1,5,5)
dbPanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, dbPanel.getMinimumSize().height));
dbPanel.setBackground(backColor);
// Button store in DB
JButton buttonStoreInDB = new JButton("Αποθήκευση δεδομένων");
buttonStoreInDB.addActionListener(this::buttonStoreInDBActionPerformed);
// Button delete all in date range
JButton buttonDelDRInDB = new JButton("Διαγραφή κληρώσεων στο εύρος");
buttonDelDRInDB.addActionListener(this::buttonDelDRInDBActionPerformed);
// Label from
JLabel labelDBFrom = new JLabel("Από");
labelDBFrom.setBorder(BorderFactory.createEmptyBorder(0, 8, 0, 6));
// Text field for date 1
textFieldDBDate1 = new JTextField("2000-01-01");
textFieldDBDate1.setBorder(BorderFactory.createEmptyBorder(0, 4, 0, 4));
textFieldDBDate1.setPreferredSize(new Dimension(80, 20));
// Label up to
JLabel labelDBUpTo = new JLabel("Έως");
labelDBUpTo.setBorder(BorderFactory.createEmptyBorder(0, 8, 0, 6));
// Text field for date 2
textFieldDBDate2 = new JTextField(DateTimeFormatter.ofPattern("yyyy-MM-dd").format(LocalDate.now()));
textFieldDBDate2.setBorder(BorderFactory.createEmptyBorder(0, 4, 0, 4));
textFieldDBDate2.setPreferredSize(new Dimension(80, 20));
// Button delete all for selected game
buttonDelAllForSelGameInDB = new JButton("Διαγραφή όλων για το Powerspin");
buttonDelAllForSelGameInDB.setPreferredSize(new Dimension(buttonDelAllForSelGameInDB.getMinimumSize().width, 26));
buttonDelAllForSelGameInDB.addActionListener(this::buttonDelAllForSelGameInDBActionPerformed);
dbPanel.add(buttonStoreInDB);
dbPanel.add(Box.createRigidArea(new Dimension(20,0)));
dbPanel.add(buttonDelDRInDB);
dbPanel.add(labelDBFrom);
dbPanel.add(textFieldDBDate1);
dbPanel.add(labelDBUpTo);
dbPanel.add(textFieldDBDate2);
dbPanel.add(Box.createRigidArea(new Dimension(20,0)));
dbPanel.add(buttonDelAllForSelGameInDB);
dbPanelBorder.add(dbPanel);
// Data view panel
viewPanelCards = new JPanel(); // CardLayout: Single draw / Date range
viewPanelCards.setBorder(BorderFactory.createEmptyBorder(18, 0, 0, 0));
viewPanelCards.setLayout(new CardLayout());
viewPanelCards.setBackground(backColor);
// Panel: Joker single draw
JPanel jokerSingleDrawPanel = new JPanel();
jokerSingleDrawPanel.setLayout(new BorderLayout());
jokerSingleDrawPanel.setBackground(backColor);
JPanel jokerSDNorthPanel = new JPanel();
jokerSDNorthPanel.setBackground(backColor);
JPanel jokerSDLabelsPanel = new JPanel();
jokerSDLabelsPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 10, 0));
jokerSDLabelsPanel.setLayout(new BoxLayout(jokerSDLabelsPanel, BoxLayout.Y_AXIS));
jokerSDLabelsPanel.setBackground(backColor);
JPanel drawNumPanel = new JPanel();
drawNumPanel.setLayout(new FlowLayout(0, 0, 0));
drawNumPanel.setBackground(backColor);
JLabel labelDraw = new JLabel("Κλήρωση");
labelDraw.setBorder(BorderFactory.createEmptyBorder(0, 68, 0, 0));
labelDraw.setFont(new Font("Arial", 0, 14));
labelDraw.setForeground(Color.DARK_GRAY);
labelDrawValue = new JLabel("");
labelDrawValue.setBorder(BorderFactory.createEmptyBorder(0, 4, 0, 0));
labelDrawValue.setFont(new Font("Arial", 0, 14));
labelDrawValue.setForeground(Color.DARK_GRAY);
drawNumPanel.add(labelDraw);
drawNumPanel.add(labelDrawValue);
JPanel drawDatePanel = new JPanel();
drawDatePanel.setLayout(new FlowLayout(0, 0, 0));
drawDatePanel.setBackground(backColor);
labelDateValue = new JLabel("");
labelDateValue.setBorder(BorderFactory.createEmptyBorder(4, 78, 0, 0));
labelDateValue.setPreferredSize(new Dimension(180, 16));
labelDateValue.setFont(new Font("Arial", 0, 14));
labelDateValue.setForeground(Color.DARK_GRAY);
drawDatePanel.add(labelDateValue);
JPanel winColumnPanel = new JPanel();
winColumnPanel.setLayout(new FlowLayout(0, 0, 0));
winColumnPanel.setBackground(backColor);
JLabel labelWinColumn = new JLabel("Νικήτρια στήλη");
labelWinColumn.setBorder(BorderFactory.createEmptyBorder(14, 55, 6, 0));
labelWinColumn.setFont(new Font("Arial", 0, 18));
winColumnPanel.add(labelWinColumn);
JPanel winColumnValuePanel = new JPanel();
winColumnValuePanel.setBorder(BorderFactory.createEmptyBorder(0, 7, 0, 0));
winColumnValuePanel.setLayout(new FlowLayout(0, 0, 0));
winColumnValuePanel.setBackground(backColor);
labelwinNum1Value = new JLabel("", SwingConstants.CENTER);
labelwinNum1Value.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
labelwinNum1Value.setPreferredSize(new Dimension(36, 16));
labelwinNum1Value.setFont(new Font("Arial", 0, 18));
labelwinNum1Value.setForeground(new Color(32,32,192));
labelwinNum2Value = new JLabel("", SwingConstants.CENTER);
labelwinNum2Value.setPreferredSize(new Dimension(36, 16));
labelwinNum2Value.setFont(new Font("Arial", 0, 18));
labelwinNum2Value.setForeground(new Color(32,32,192));
labelwinNum3Value = new JLabel("", SwingConstants.CENTER);
labelwinNum3Value.setPreferredSize(new Dimension(36, 16));
labelwinNum3Value.setFont(new Font("Arial", 0, 18));
labelwinNum3Value.setForeground(new Color(32,32,192));
labelwinNum4Value = new JLabel("", SwingConstants.CENTER);
labelwinNum4Value.setPreferredSize(new Dimension(36, 16));
labelwinNum4Value.setFont(new Font("Arial", 0, 18));
labelwinNum4Value.setForeground(new Color(32,32,192));
labelwinNum5Value = new JLabel("", SwingConstants.CENTER);
labelwinNum5Value.setPreferredSize(new Dimension(36, 16));
labelwinNum5Value.setFont(new Font("Arial", 0, 18));
labelwinNum5Value.setForeground(new Color(32,32,192));
labelwinNum6Value = new JLabel("", SwingConstants.CENTER);
labelwinNum6Value.setPreferredSize(new Dimension(36, 16));
labelwinNum6Value.setFont(new Font("Arial", 0, 18));
labelwinNum6Value.setForeground(new Color(210,105,0));
winColumnValuePanel.add(labelwinNum1Value);
winColumnValuePanel.add(labelwinNum2Value);
winColumnValuePanel.add(labelwinNum3Value);
winColumnValuePanel.add(labelwinNum4Value);
winColumnValuePanel.add(labelwinNum5Value);
winColumnValuePanel.add(labelwinNum6Value);
JPanel totalColumnsPanel = new JPanel();
totalColumnsPanel.setLayout(new FlowLayout(0, 0, 0));
totalColumnsPanel.setBackground(backColor);
JLabel labelTotalColumns = new JLabel("Σύνολο στηλών:");
labelTotalColumns.setBorder(BorderFactory.createEmptyBorder(14, 34, 0, 0));
labelTotalColumns.setFont(new Font("Arial", 0, 14));
labelTotalColumns.setForeground(Color.DARK_GRAY);
labelTotalColumnsValue = new JLabel("");
labelTotalColumnsValue.setBorder(BorderFactory.createEmptyBorder(14, 4, 0, 0));
labelTotalColumnsValue.setFont(new Font("Arial", 0, 14));
labelTotalColumnsValue.setForeground(Color.DARK_GRAY);
totalColumnsPanel.add(labelTotalColumns);
totalColumnsPanel.add(labelTotalColumnsValue);
jokerSDLabelsPanel.add(drawNumPanel);
jokerSDLabelsPanel.add(drawDatePanel);
jokerSDLabelsPanel.add(winColumnPanel);
jokerSDLabelsPanel.add(winColumnValuePanel);
jokerSDLabelsPanel.add(totalColumnsPanel);
jokerSDNorthPanel.add(jokerSDLabelsPanel);
JPanel jokerSDSouthPanel = new JPanel();
jokerSDSouthPanel.setLayout(new BorderLayout());
jokerSDSouthPanel.setBackground(backColor);
// Columns and initial data of the JTable for Joker single draw
String[] columnsSD = {"Κατηγορίες επιτυχιών", "Επιτυχίες",
"Κέρδη ανά επιτυχία"};
Object[][] dataSD = {
{"5+1", "", ""},
{"5", "", ""},
{"4+1", "", ""},
{"4", "", ""},
{"3+1", "", ""},
{"3", "", ""},
{"2+1", "", ""},
{"1+1", "", ""}
};
// Center renderer for table columns
DefaultTableCellRenderer centerText = new DefaultTableCellRenderer();
centerText.setHorizontalAlignment(SwingConstants.CENTER);
// JTable for Joker single draw
jokerSDTable = new JTable(dataSD, columnsSD);
jokerSDTable.setPreferredSize(new Dimension(500, 128));
jokerSDTable.getColumnModel().getColumn(0).setCellRenderer(centerText);
jokerSDTable.getColumnModel().getColumn(1).setCellRenderer(centerText);
jokerSDTable.getColumnModel().getColumn(2).setCellRenderer(centerText);
// Make table cells unselectable and uneditable
jokerSDTable.setEnabled(false);
// Disable table column re-ordering
jokerSDTable.getTableHeader().setReorderingAllowed(false);
// Make the JScrollPane take the same size as the JTable
jokerSDTable.setPreferredScrollableViewportSize(jokerSDTable.getPreferredSize());
jokerSDSouthPanel.add(new JScrollPane(jokerSDTable), BorderLayout.NORTH);
jokerSingleDrawPanel.add(jokerSDNorthPanel, BorderLayout.NORTH);
jokerSingleDrawPanel.add(jokerSDSouthPanel, BorderLayout.CENTER);
// Panel: Joker date range
JPanel jokerDateRangePanel = new JPanel();
jokerDateRangePanel.setLayout(new GridLayout(1,1));
jokerDateRangePanel.setBackground(backColor);
// Columns and initial data of the JTable for Joker date range
String[] columnsDR = {"<html><center>Αριθμός<br>κλήρωσης</center></html>",
"<html><center>Ημερομηνία</center></html>",
"<html><center>Στήλες</center></html>",
"<html><center>Νικήτρια στήλη</center></html>",
"<html><center>'5+1'<br>επιτυχίες</center></html>",
"<html><center>'5+1'<br>κέρδη</center></html>",
"<html><center>'5'<br>επιτυχίες</center></html>",
"<html><center>'5'<br>κέρδη</center></html>",
"<html><center>'4+1'<br>επιτυχίες</center></html>",
"<html><center>'4+1'<br>κέρδη</center></html>",
"<html><center>'4'<br>επιτυχίες</center></html>",
"<html><center>'4'<br>κέρδη</center></html>",
"<html><center>'3+1'<br>επιτυχίες</center></html>",
"<html><center>'3+1'<br>κέρδη</center></html>",
"<html><center>'3'<br>επιτυχίες</center></html>",
"<html><center>'3'<br>κέρδη</center></html>",
"<html><center>'2+1'<br>επιτυχίες</center></html>",
"<html><center>'2+1'<br>κέρδη</center></html>",
"<html><center>'1+1'<br>επιτυχίες</center></html>",
"<html><center>'1+1'<br>κέρδη</center></html>"};
// Table model
modeljokerDRTable = new DefaultTableModel(columnsDR, 0);
// JTable for Joker date range
jokerDRTable = new JTable(modeljokerDRTable);
jokerDRTable.getTableHeader().setFont(fontRobotoRegular.deriveFont(0, 12));
jokerDRTable.setFont(fontRobotoRegular.deriveFont(0, 12));
jokerDRTable.getColumnModel().getColumn(0).setCellRenderer(centerText); // Draw
jokerDRTable.getColumnModel().getColumn(0).setMinWidth(62);
jokerDRTable.getColumnModel().getColumn(1).setCellRenderer(centerText); // Date
jokerDRTable.getColumnModel().getColumn(1).setMinWidth(71); //71min
jokerDRTable.getColumnModel().getColumn(2).setCellRenderer(centerText); // Columns
jokerDRTable.getColumnModel().getColumn(2).setMinWidth(63);
jokerDRTable.getColumnModel().getColumn(3).setCellRenderer(centerText); // Win numbers
jokerDRTable.getColumnModel().getColumn(3).setMinWidth(139); //118min
jokerDRTable.getColumnModel().getColumn(4).setCellRenderer(centerText); // 5+1
jokerDRTable.getColumnModel().getColumn(4).setMinWidth(54); //53min
jokerDRTable.getColumnModel().getColumn(5).setCellRenderer(centerText); // 5+1
jokerDRTable.getColumnModel().getColumn(5).setMinWidth(80);
jokerDRTable.getColumnModel().getColumn(6).setCellRenderer(centerText); // 5
jokerDRTable.getColumnModel().getColumn(6).setMinWidth(54);
jokerDRTable.getColumnModel().getColumn(7).setCellRenderer(centerText); // 5
jokerDRTable.getColumnModel().getColumn(7).setMinWidth(64);
jokerDRTable.getColumnModel().getColumn(8).setCellRenderer(centerText); // 4+1
jokerDRTable.getColumnModel().getColumn(8).setMinWidth(54);
jokerDRTable.getColumnModel().getColumn(9).setCellRenderer(centerText); // 4+1
jokerDRTable.getColumnModel().getColumn(9).setMinWidth(50);
jokerDRTable.getColumnModel().getColumn(10).setCellRenderer(centerText); // 4
jokerDRTable.getColumnModel().getColumn(10).setMinWidth(54);
jokerDRTable.getColumnModel().getColumn(11).setCellRenderer(centerText); // 4
jokerDRTable.getColumnModel().getColumn(11).setMinWidth(39);
jokerDRTable.getColumnModel().getColumn(12).setCellRenderer(centerText); // 3+1
jokerDRTable.getColumnModel().getColumn(12).setMinWidth(54);
jokerDRTable.getColumnModel().getColumn(13).setCellRenderer(centerText); // 3+1
jokerDRTable.getColumnModel().getColumn(13).setMinWidth(39);
jokerDRTable.getColumnModel().getColumn(14).setCellRenderer(centerText); // 3
jokerDRTable.getColumnModel().getColumn(14).setMinWidth(54);
jokerDRTable.getColumnModel().getColumn(15).setCellRenderer(centerText); // 3
jokerDRTable.getColumnModel().getColumn(15).setMinWidth(39);
jokerDRTable.getColumnModel().getColumn(16).setCellRenderer(centerText); // 2+1
jokerDRTable.getColumnModel().getColumn(16).setMinWidth(54);
jokerDRTable.getColumnModel().getColumn(17).setCellRenderer(centerText); // 2+1
jokerDRTable.getColumnModel().getColumn(17).setMinWidth(39);
jokerDRTable.getColumnModel().getColumn(18).setCellRenderer(centerText); // 1+1
jokerDRTable.getColumnModel().getColumn(18).setMinWidth(54);
jokerDRTable.getColumnModel().getColumn(19).setCellRenderer(centerText); // 1+1
jokerDRTable.getColumnModel().getColumn(19).setMinWidth(39);
// Make table cells unselectable and uneditable
jokerDRTable.setEnabled(false);
// Disable table column re-ordering
jokerDRTable.getTableHeader().setReorderingAllowed(false);
// Make the JScrollPane take the same size as the JTable
jokerDRTable.setPreferredScrollableViewportSize(jokerDRTable.getPreferredSize());
// Make table fill the entire Viewport height
jokerDRTable.setFillsViewportHeight(true);
// Scrollpane for the jokerDRTable
JScrollPane spDR = new JScrollPane(jokerDRTable);
spDR.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
jokerDateRangePanel.add(spDR);
viewPanelCards.add(jokerDateRangePanel, "jokerDateRange");
viewPanelCards.add(jokerSingleDrawPanel, "jokerSingleDraw");
// Add elements to middle panel
middlePanel.add(gameSelectPanel);
middlePanel.add(chooseMethodLabelPanel);
middlePanel.add(chooseMethodAndDLPanel);
middlePanel.add(viewPanelCards);
middlePanel.add(Box.createRigidArea(new Dimension(0, 12)));
middlePanel.add(dbPanelBorder);
middlePanel.add(Box.createVerticalGlue());
/*
* Bottom panel with the Close button
*/
JPanel bottomPanel = new JPanel();
bottomPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 0, 20));
bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.X_AXIS));
bottomPanel.setBackground(backColor);
// Close button
JButton buttonClose = new JButton("Κλείσιμο");
buttonClose.setPreferredSize(new Dimension(116, 26));
buttonClose.addActionListener(this::buttonCloseActionPerformed);
bottomPanel.add(Box.createHorizontalGlue(), BorderLayout.CENTER);
bottomPanel.add(buttonClose);
/*
* Main panel
*/
JPanel mainPanel = new JPanel();
mainPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 30, 0));
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
mainPanel.setPreferredSize(new Dimension(1216, 650));
mainPanel.setBackground(backColor);
mainPanel.add(topPanel);
mainPanel.add(middlePanel);
mainPanel.add(bottomPanel);
/*
* Main window
*/
dialog = new JDialog();
dialog.add(mainPanel, BorderLayout.CENTER);
dialog.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
dialog.setTitle("Manage data");
dialog.setModalityType(Dialog.DEFAULT_MODALITY_TYPE);
dialog.pack();
dialog.setLocationRelativeTo(null); // Appear in the center of screen
dialog.setMinimumSize(new Dimension(1226, 680));
dialog.setIconImages(icons);
// Find firstDrawDate & lastDrawId in advance, populate textFieldDrawId
findDateOfFirstDraw();
CompletableFuture.runAsync(() -> findIdOfFirstDraw()); // Run asynchronously
CompletableFuture.runAsync(() -> findLastDrawId(true)); // Run asynchronously
CompletableFuture.runAsync(() -> showDrawInfo()); // Run asynchronously
setTextOfButtonDelAllForSelGameInDB();
dialog.setVisible(true);
}
}
| JaskJohin/JokerGame-Stats | src/view/WindowManageData.java |
2,462 | /**
* Αυτή η κλάση αναπαριστά μια ομάδα εργασίας φοιτητών που αποτελείται από δύο φοιτητές (Student κλάση).
* This class represents a team consisting of two students (Student class)
*/
public class Team {
private Student student1;
private Student student2;
// Δημιουργήστε έναν κατασκευαστή που να δέχεται ως όρισματα τους 2 φοιτητές.
// Create a constructor that has as parameters the 2 students.
public Team(Student student1,Student student2){
this.student1=student1;
this.student2=student2;
}
/**
* Μέθοδος που επιστρέφει τον 1ο φοιτητή της ομάδας.
* This method should return the 1st student of the team.
*/
public Student getStudent1() {
return this.student1;
}
/**
* Μέθοδος που επιστρέφει τον 2ο φοιτητή της ομάδας.
* This method should return the 2nd student of the team.
*/
public Student getStudent2() {
return this.student2;
}
/**
* Μέθοδος που αλλάζει τον 1ο φοιτητή της ομάδας.
* This method should change the 1st student of the team.
*/
public void setStudent1(Student student1) {
this.student1=student1;
}
/**
* Μέθοδος που αλλάζει τον 2o φοιτητή της ομάδας.
* This method should change the 2nd student of the team.
*/
public void setStudent2(Student student2) {
this.student2=student2;
}
/**
* Δοθέντος έναν αριθμό από projects αυτή η μέθοδος επιστρέφει το project (αριθμό) που πρέπει
* υλοποιήσει η ομάδα -> ("Άθροισμα των ΑΕΜ" modulo #projects) + 1
* Given a number of projects, this method returns the project number the team should take.
* The formula is -> ("sum of IDs" modulo #projects) + 1
*/
public int getProject(int projects) {
return (student1.getId()+student2.getId())%projects +1;
}
/**
* Αυτή η μέθοδος ελέγχει αν οι φοιτητές της ομάδας παρακολουθούν το ίδιο εργαστηριακό τμήμα δοθέντος
* το αριθμό των τμημάτων.
* This method checks if the team's students are in the same lab given the total number of labs.
*/
public boolean sameLab(int labs) {
return student1.getLab(labs)==student2.getLab(labs);
}
}
| asimakiskydros/University-Projects | Object Oriented Programming/Lab 2/Team.java |
2,464 | package thedreamteam.passbuy;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.ImageButton;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class MoreInfo extends PortraitActivity {
private static final String BUNDLE_NAME = "bundle";
private static final String BASKET_NAME = "basket";
private MoreInfoAdapter mAdapter;
private GsonWorker gson = new GsonWorker();
private List<Store> stores = new ArrayList<>();
private List<StoreLocation> storeLocations = new ArrayList<>();
private Coordinates userCoordinates = new Coordinates();
private LocationManager locationManager;
private Basket basket;
private String bestStore;
private double bestPrice;
private TextView bestPriceText;
private TextView bestSupermarket;
private TextView loadingText;
private final LocationListener mLocationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
updateUserLocation(location);
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
// Unneeded
}
@Override
public void onProviderEnabled(String s) {
// Unneeded
}
@Override
public void onProviderDisabled(String s) {
// Unneeded
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.more_info);
Context mContext = this.getBaseContext();
ImageButton backButton = findViewById(R.id.backButton);
ImageButton homeScreen = findViewById(R.id.homeButton);
loadingText = findViewById(R.id.empty_basket_text);
//get basket from previous activity
Bundle bundle = getIntent().getBundleExtra(BUNDLE_NAME);
basket = (Basket) bundle.getSerializable(BASKET_NAME);
bestPrice = bundle.getDouble("best_price");
bestStore = (String) bundle.getCharSequence("best_super");
stores = (List<Store>) bundle.getSerializable("stores");
List<StorePrice> totalPrices = basket.getTotalPrices();
new Thread(() -> {
if (stores == null && isNetworkAvailable(mContext)) {
stores = gson.getStores();
bestStore = stores.get(0).getName();
//Get best store name
for (Store store : stores) {
if (totalPrices.get(0).getStoreId().equals(store.getId())) {
bestStore = store.getName();
break;
}
}
}
Collections.sort(totalPrices, new IdsComparator());
bestPriceText = findViewById(R.id.best_price);
bestSupermarket = findViewById(R.id.best_supermarket);
runOnUiThread(() -> {
loadingText.setText("Λαμβάνουμε την τοποθεσία σας μέσω GPS.\nΠαρακαλώ περιμένετε..."
+ "\n\nΣημείωση: Οι ρυθμίσεις σας θα πρέπει να επιτρέπουν την ανάκτηση τοποθεσίας μέσω GPS.");
bestPriceText.setText(String.format("%.2f €", bestPrice));
bestSupermarket.setText(bestStore);
bestSupermarket.setSelected(true);
bestPriceText.setSelected(true);
initRecyclerView();
// Acquire user location
this.requestPermissions();
});
}).start();
backButton.setOnClickListener(v -> {
Intent intent = new Intent(v.getContext(), HomeScreen.class);
Bundle bundle2 = new Bundle();
bundle2.putSerializable(BASKET_NAME, basket);
intent.putExtra(BUNDLE_NAME, bundle2);
startActivity(intent);
});
homeScreen.setOnClickListener(v -> {
Intent intent = new Intent(v.getContext(), HomeScreen.class);
Bundle bundle12 = new Bundle();
bundle12.putSerializable(BASKET_NAME, basket);
intent.putExtra(BUNDLE_NAME, bundle12);
startActivity(intent);
});
}
public void requestPermissions() {
if (Build.VERSION.SDK_INT >= 23) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
else
this.requestLocation();
} else
this.requestLocation();
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
this.requestLocation();
}
}
public void requestLocation() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
long timeDelta = System.currentTimeMillis() - location.getTime();
// Refresh location if our cached one is older than 2 minutes
if (timeDelta > (1000 * 60 * 2))
locationManager.requestSingleUpdate(LocationManager.GPS_PROVIDER, mLocationListener, null);
else
this.updateUserLocation(location);
} else
locationManager.requestSingleUpdate(LocationManager.GPS_PROVIDER, mLocationListener, null);
}
private void initRecyclerView() {
RecyclerView recyclerView = findViewById(R.id.rv);
// Use an adapter to feed data into the RecyclerView
mAdapter = new MoreInfoAdapter(this, basket, stores);
// Layout size remains fixed, improve performance
recyclerView.setHasFixedSize(true);
recyclerView.setAdapter(mAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
// Draw line divider
DividerItemDecoration lineDivider = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
recyclerView.addItemDecoration(lineDivider);
}
public void updateUserLocation(Location location) {
userCoordinates.setLat(location.getLatitude());
userCoordinates.setLng(location.getLongitude());
locationManager.removeUpdates(mLocationListener);
loadingText.setText("Ψάχνουμε τα κοντινότερα καταστήματα...");
new Thread(() -> {
storeLocations = gson.getNearbyStores(stores, userCoordinates);
mAdapter.replaceUserLocation(userCoordinates);
mAdapter.replaceLocations(storeLocations);
runOnUiThread(() -> {
mAdapter.notifyDataSetChanged();
loadingText.setText("");
});
}).start();
}
public boolean isNetworkAvailable(Context context) {
final ConnectivityManager connectivityManager = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE));
return connectivityManager.getActiveNetworkInfo() != null && connectivityManager.getActiveNetworkInfo().isConnected();
}
}
//Comparator that compares prices
class IdsComparator implements Comparator {
public int compare(Object o1, Object o2) {
if (((StorePrice) o1).getStoreId() == ((StorePrice) o2).getStoreId())
return 0;
else if (((StorePrice) o1).getStoreId() > ((StorePrice) o2).getStoreId())
return 1;
else
return -1;
}
}
| TsimpDim/PassBuy | front-end/PassBuy/app/src/main/java/thedreamteam/passbuy/MoreInfo.java |
2,467 | import java.io.*;
import java.util.HashMap;
/**
* Προσθέστε στην κλάση πεδίο/πεδία και συμπληρώστε τις μεθόδους, έτσι ώστε να υπολογίζεται η συχνότητα των χαρακτήρων
* που υπάρχουν σε ένα αρχείο κειμένου καθώς και να υποστηρίζεται η αποθήκευση και φόρτωση των στατιστικών σε/από
* δυαδικά αρχεία.
* <p>
* Update the class with field(s) and fill in the methods, so as to calculate the frequency of the characters of a text
* file, as well as to save and retrieve the frequencies to/from binary files.
*/
public class CharacterFrequency {
HashMap<Character,Integer> data;
/**
* Μέθοδος που υπολογίζει τις συχνότητες των χαρακτήρων (γράμμα, αριθμός, σύμβολο, κτλ.) που υπάρχουν σε ένα αρχείο
* κειμένου, του οποίου το όνομα δίνεται ως παράμετρος. Τα κενά θα πρέπει να αγνοούνται. Όλες οι συχνότητες θα
* πρέπει να υπολογίζονται αφού γίνει μετατροπή σε πεζούς χαρακτήρες. Τα αποτελέσματα πρέπει να αποθηκεύονται σε
* κατάλληλη δομή στην κλάση, ώστε να είναι προσβάσιμη και στη μέθοδο saveToBinaryFile(String filename). Για
* παράδειγμα, για το test_file2.txt τα αποτελέσματα πρέπει να είναι: '1'=1, 'a'=10, '2'=1, 'b'=6, '3'=1, '4'=1,
* '5'=1, '6'=2, 'h'=2, 'j'=2, '.'=7
* <p>
* This method calculates the frequencies of the characters (letters, numbers, symbols, etc.) that exist in a text
* file, whose name is given as a parameter. Spaces should be skipped. All frequencies should be calculated on
* lowercase characters (i.e. you need first to convert upper case to lower case). The frequencies should be stored
* in an appropriate structure in the class, so as to be accessible by the method saveToBinaryFile(String filename).
* For example, for the test_file2.txt, the results should be: '1'=1, 'a'=10, '2'=1, 'b'=6, '3'=1, '4'=1, '5'=1,
* '6'=2, 'h'=2, 'j'=2, '.'=7
*
* @param filename Το όνομα του αρχείου / The name of the file
*/
public void countCharacters(String filename) {
this.data = new HashMap<>();
try(BufferedReader buffer = new BufferedReader(new FileReader(filename))){
String line;
while((line = buffer.readLine()) != null) {
char[] lineArray = line.toCharArray();
for (char c : lineArray) {
if (c >= 'A' && c <= 'Z')
c += 'a' - 'A';
if (c != ' ')
this.data.put(c, getFrequency(c) + 1);
}
}
}catch(IOException e){
e.printStackTrace();
}
}
/**
* Σώζει τη δομή με τις συχνότητες σε ένα δυαδικό αρχείο.
* <p>
* It saves the structure with the frequencies in an binary file.
*
* @param outputFilename Το όνομα του δυαδικού αρχείου / The name of the binary file
*/
public void saveToBinaryFile(String outputFilename) {
try(ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(outputFilename))){
oos.writeObject(data);
}catch(IOException e){
e.printStackTrace();
}
}
/**
* Φορτώνει τη δομή με τις συχνότητες από το δυαδικό αρχείο.
* <p>
* It loads the structure with the frequencies from the binary file.
*
* @param file Το όνομα του δυαδικού αρχείου / The name of the binary file.
*/
public void loadFromBinaryFile(String file) {
try(ObjectInputStream reader = new ObjectInputStream(new FileInputStream(file))){
this.data = (HashMap<Character, Integer>) reader.readObject();
}catch(IOException | ClassNotFoundException e){
e.printStackTrace();
}
}
/**
* Επιστρέφει τη συχνότητα ενός χαρακτήρα.
* <p>
* It returns the frequency of the character.
*
* @param character Ο χαρακτήρας του οποίου θέλουμε τη συχνότητα / The character whose frequency is requested
* @return Η συχνότητα του χαρακτήρα, 0 αν δεν υπάρχει / The frequency of the character, 0 if it does not exist
*/
public int getFrequency(char character) {
return this.data.getOrDefault(character,0);
}
}
| asimakiskydros/University-Projects | Object Oriented Programming/Lab 9/CharacterFrequency.java |
2,470 | package com.example.commontasker;
/**
* Created by Αρης on 18/10/2016.
*/
import android.support.v7.app.AppCompatActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class realchattime extends AppCompatActivity {
private Button add_room;
private EditText room_name;
private ListView listView;
private ArrayAdapter<String> arrayAdapter;
private ArrayList<String> list_of_rooms = new ArrayList<>();
private String name;
private DatabaseReference root = FirebaseDatabase.getInstance().getReference().getRoot();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.realchattime);
add_room = (Button) findViewById(R.id.btn_add_room);
room_name = (EditText) findViewById(R.id.room_name_edittext);
listView = (ListView) findViewById(R.id.listView);
arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,list_of_rooms);
listView.setAdapter(arrayAdapter);
request_user_name();
add_room.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Map<String,Object> map = new HashMap<String, Object>();
map.put(room_name.getText().toString(),"");
root.updateChildren(map);
}
});
root.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Set<String> set = new HashSet<String>();
Iterator i = dataSnapshot.getChildren().iterator();
while (i.hasNext()){
set.add(((DataSnapshot)i.next()).getKey());
}
list_of_rooms.clear();
list_of_rooms.addAll(set);
arrayAdapter.notifyDataSetChanged();
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getApplicationContext(),Chat_Room.class);
intent.putExtra("room_name",((TextView)view).getText().toString() );
intent.putExtra("user_name",name);
startActivity(intent);
}
});
}
private void request_user_name() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Enter name:");
final EditText input_field = new EditText(this);
builder.setView(input_field);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
name = input_field.getText().toString();
if(name.equals("")){
Toast.makeText(realchattime.this,"Το όνομα δεν πρέπει να είναι κενό" ,Toast.LENGTH_LONG).show();
request_user_name();
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
request_user_name();
}
});
builder.show();
}
}
| netCommonsEU/CommonTasker | app/src/main/java/com/example/commontasker/realchattime.java |
2,472 | /**
* Copyright 2016 SciFY
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.scify.talkandplay.gui.configuration;
import java.awt.Color;
import java.awt.Font;
import java.awt.Image;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.border.LineBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import io.sentry.Sentry;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import org.scify.talkandplay.gui.grid.tiles.TileCreator;
import org.scify.talkandplay.gui.helpers.GuiHelper;
import org.scify.talkandplay.gui.helpers.UIConstants;
import org.scify.talkandplay.models.Category;
import org.scify.talkandplay.models.User;
import org.scify.talkandplay.services.CategoryService;
import org.scify.talkandplay.services.UserService;
import org.scify.talkandplay.utils.*;
public class WordFormPanel extends javax.swing.JPanel {
private GuiHelper guiHelper;
private User user;
private Category category;
private List<Category> categories;
private ImageResource imageResource;
private SoundResource soundResource;
private CategoryService categoryService;
private UserService userService;
private ConfigurationPanel parent;
private MediaPlayer audioPlayer;
private File currentDirectory;
protected org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(WordFormPanel.class);
protected ResourceManager rm;
public WordFormPanel(User user, Category category, ConfigurationPanel parent) {
this.guiHelper = new GuiHelper();
this.user = user;
this.imageResource = null;
this.soundResource = null;
this.categoryService = new CategoryService();
this.userService = new UserService();
this.category = category;
this.parent = parent;
this.audioPlayer = null;
this.rm = ResourceManager.getInstance();
initComponents();
initCustomComponents();
}
private void initCustomComponents() {
categories = categoryService.getLinearCategories(user);
enabledCheckbox.setSelected(true);
setBorder(new LineBorder(Color.decode(UIConstants.green), 1));
setUI();
setListeners();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
backButton = new javax.swing.JButton();
titleLabel = new javax.swing.JLabel();
step1Label = new javax.swing.JLabel();
wordTextField = new javax.swing.JTextField();
step2Label = new javax.swing.JLabel();
step3Label = new javax.swing.JLabel();
step3ExplLabel = new javax.swing.JLabel();
uploadSoundLabel = new javax.swing.JLabel();
step4Label = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
step4ExplTextArea = new javax.swing.JTextArea();
uploadImageLabel = new javax.swing.JLabel();
saveButton = new javax.swing.JButton();
editStepsPanel = new javax.swing.JPanel();
rowsTextField = new javax.swing.JTextField();
xLabel = new javax.swing.JLabel();
columnsTextField = new javax.swing.JTextField();
step7Label = new javax.swing.JLabel();
imageCheckBox = new javax.swing.JCheckBox();
textCheckBox = new javax.swing.JCheckBox();
soundCheckBox = new javax.swing.JCheckBox();
step6Label = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
closeLabel = new javax.swing.JLabel();
categoriesComboBox = new javax.swing.JComboBox();
errorLabel = new javax.swing.JLabel();
enabledCheckbox = new javax.swing.JCheckBox();
backButton.setBackground(new java.awt.Color(75, 161, 69));
backButton.setFont(backButton.getFont());
backButton.setForeground(new java.awt.Color(255, 255, 255));
backButton.setText(rm.getTextOfXMLTag("backButton"));
backButton.setBorder(null);
setBackground(new java.awt.Color(255, 255, 255));
titleLabel.setText(rm.getTextOfXMLTag("addNewWord"));
step1Label.setText("1. " + rm.getTextOfXMLTag("writeWord"));
wordTextField.setBackground(new java.awt.Color(255, 255, 255));
wordTextField.setForeground(new java.awt.Color(51, 51, 51));
wordTextField.setText(rm.getTextOfXMLTag("word"));
step2Label.setText("2. " + rm.getTextOfXMLTag("uploadImage"));
step3Label.setText("3. " + rm.getTextOfXMLTag("uploadSound"));
step3ExplLabel.setText(rm.getTextOfXMLTag("uploadSoundWarning"));
uploadSoundLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
uploadSoundLabel.setText("upload");
step4Label.setText("4. " + rm.getTextOfXMLTag("wordBelongsToSelection"));
step4ExplTextArea.setEditable(false);
step4ExplTextArea.setBackground(new java.awt.Color(255, 255, 255));
step4ExplTextArea.setColumns(20);
step4ExplTextArea.setRows(5);
step4ExplTextArea.setText(rm.getTextOfXMLTag("wordBelongsToSelection2") + "\n");
step4ExplTextArea.setBorder(null);
jScrollPane1.setViewportView(step4ExplTextArea);
uploadImageLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
uploadImageLabel.setText("upload");
saveButton.setBackground(new java.awt.Color(75, 161, 69));
saveButton.setFont(saveButton.getFont());
saveButton.setForeground(new java.awt.Color(255, 255, 255));
saveButton.setText(rm.getTextOfXMLTag("saveWord"));
saveButton.setBorder(null);
saveButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
saveButtonMouseClicked(evt);
}
});
editStepsPanel.setBackground(new java.awt.Color(255, 255, 255));
xLabel.setText("x");
step7Label.setText("6. " + rm.getTextOfXMLTag("showMatrix"));
imageCheckBox.setBackground(new java.awt.Color(255, 255, 255));
imageCheckBox.setText(rm.getTextOfXMLTag("image"));
textCheckBox.setBackground(new java.awt.Color(255, 255, 255));
textCheckBox.setText(rm.getTextOfXMLTag("verbal"));
soundCheckBox.setBackground(new java.awt.Color(255, 255, 255));
soundCheckBox.setText(rm.getTextOfXMLTag("sound"));
step6Label.setText("5. " + rm.getTextOfXMLTag("configureMatrixSize"));
jLabel1.setText("(" + rm.getTextOfXMLTag("configureMatrixSize2") + ")");
javax.swing.GroupLayout editStepsPanelLayout = new javax.swing.GroupLayout(editStepsPanel);
editStepsPanel.setLayout(editStepsPanelLayout);
editStepsPanelLayout.setHorizontalGroup(
editStepsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(editStepsPanelLayout.createSequentialGroup()
.addGroup(editStepsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addGroup(editStepsPanelLayout.createSequentialGroup()
.addGap(64, 64, 64)
.addGroup(editStepsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(editStepsPanelLayout.createSequentialGroup()
.addComponent(rowsTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(xLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(columnsTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(editStepsPanelLayout.createSequentialGroup()
.addComponent(soundCheckBox)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(textCheckBox)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(imageCheckBox))
.addComponent(step6Label)
.addComponent(step7Label))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
editStepsPanelLayout.setVerticalGroup(
editStepsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(editStepsPanelLayout.createSequentialGroup()
.addComponent(step6Label)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel1)
.addGap(12, 12, 12)
.addGroup(editStepsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(rowsTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(xLabel)
.addComponent(columnsTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(step7Label)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 9, Short.MAX_VALUE)
.addGroup(editStepsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(soundCheckBox)
.addComponent(textCheckBox)
.addComponent(imageCheckBox)))
);
closeLabel.setText("closeLabel");
categoriesComboBox.setBackground(new java.awt.Color(255, 255, 255));
categoriesComboBox.setBorder(null);
errorLabel.setBackground(new java.awt.Color(255, 255, 255));
errorLabel.setForeground(new java.awt.Color(153, 0, 0));
errorLabel.setText("error");
enabledCheckbox.setBackground(new java.awt.Color(255, 255, 255));
enabledCheckbox.setText(rm.getTextOfXMLTag("activated"));
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(titleLabel)
.addGap(106, 106, 106)
.addComponent(closeLabel))
.addComponent(saveButton, javax.swing.GroupLayout.Alignment.TRAILING)))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(editStepsPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(uploadImageLabel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(uploadSoundLabel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(categoriesComboBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(step3ExplLabel)
.addComponent(errorLabel)
.addGroup(layout.createSequentialGroup()
.addGap(16, 16, 16)
.addComponent(wordTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 223, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(enabledCheckbox))
.addComponent(step1Label)
.addComponent(step2Label)
.addComponent(step3Label)
.addComponent(step4Label)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 448, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, Short.MAX_VALUE)))))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(closeLabel)
.addComponent(titleLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(step1Label)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(wordTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(enabledCheckbox))
.addGap(16, 16, 16)
.addComponent(step2Label)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(uploadImageLabel)
.addGap(11, 11, 11)
.addComponent(step3Label)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(step3ExplLabel)
.addGap(18, 18, 18)
.addComponent(uploadSoundLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(step4Label)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(categoriesComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(editStepsPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(errorLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(saveButton)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
}// </editor-fold>//GEN-END:initComponents
private void saveButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_saveButtonMouseClicked
if (validateCategory()) {
Category newCategory = new Category(wordTextField.getText());
newCategory.setEnabled(enabledCheckbox.isSelected());
newCategory.setImage(imageResource);
newCategory.setSound(soundResource);
Category selectedCat = (Category) categoriesComboBox.getSelectedItem();
if (selectedCat.getName().equals(user.getCommunicationModule().getName()))
newCategory.setParentCategory(null);
else
newCategory.setParentCategory(selectedCat);
try {
categoryService.save(category, newCategory, user);
updateCategoriesComboBox();
parent.redrawCategoriesList();
parent.displayMessage(rm.getTextOfXMLTag("wordWasSaved"));
parent.showInfoPanel();
} catch (Exception ex) {
Logger.getLogger(WordFormPanel.class.getName()).log(Level.SEVERE, null, ex);
}
}
}//GEN-LAST:event_saveButtonMouseClicked
public void updateCategoriesComboBox() {
categoriesComboBox.removeAllItems();
categoriesComboBox.addItem(rm.getTextOfXMLTag("chooseWord"));
List<Category> categories = categoryService.getLinearCategories(userService.getUser(user.getName()));
Category parent = null;
for (Category cat : categories) {
if (category == null || !category.getNameUnmodified().equals(cat.getNameUnmodified()))
categoriesComboBox.addItem(cat);
if (category != null && category.getParentCategory() != null && category.getParentCategory().getNameUnmodified().equals(cat.getNameUnmodified()))
parent = cat;
}
if (category == null || category.getParentCategory() == null)
categoriesComboBox.setSelectedIndex(1);
else
categoriesComboBox.setSelectedItem(parent);
}
private boolean validateCategory() {
String name = wordTextField.getText();
//word should not be null
if (name == null || name.isEmpty()) {
errorLabel.setText(rm.getTextOfXMLTag("wordMustNotBeEmpty"));
errorLabel.setVisible(true);
return false;
}
//word should be unique
if (category == null || (category != null && !category.getName().equals(name))) {
for (Category category : categories) {
if (category.getName().equals(name)) {
errorLabel.setText(rm.getTextOfXMLTag("wordMustBeUnique"));
errorLabel.setVisible(true);
return false;
}
}
}
//image should be uploaded
if (imageResource == null) {
//TODO this is not correct, image might not be visible due to settings
errorLabel.setText(rm.getTextOfXMLTag("wordMustHaveImage"));
errorLabel.setVisible(true);
return false;
}
if (categoriesComboBox.getSelectedIndex() == 0) {
errorLabel.setText(rm.getTextOfXMLTag("wordMustBelongToAnotherWord"));
errorLabel.setVisible(true);
return false;
}
/* if (category != null && category.getSubCategories().size() > 0 && !imageCheckBox.isSelected() && !textCheckBox.isSelected()) {
errorLabel.setText("Η λέξη θα πρέπει να έχει τουλάχιστον ένα από τα δύο: λεκτικό, εικόνα");
errorLabel.setVisible(true);
return false;
}*/
return true;
}
private void setUI() {
errorLabel.setVisible(false);
closeLabel.setIcon(new ImageIcon(rm.getImage("close-icon.png", ResourceType.JAR).getScaledInstance(15, 15, Image.SCALE_SMOOTH)));
closeLabel.setText("");
titleLabel.setText(rm.getTextOfXMLTag("addNewWord"));
titleLabel.setFont(new Font(UIConstants.mainFont, Font.BOLD, 16));
titleLabel.setForeground(Color.decode(UIConstants.green));
titleLabel.setHorizontalAlignment(JLabel.CENTER);
guiHelper.drawButton(saveButton);
guiHelper.setStepLabelFont(step1Label);
guiHelper.setStepLabelFont(step2Label);
guiHelper.setStepLabelFont(step3Label);
guiHelper.setStepLabelFont(step4Label);
guiHelper.setStepLabelFont(step6Label);
guiHelper.setStepLabelFont(step7Label);
guiHelper.setStepExplLabelFont(step3ExplLabel);
wordTextField.setBorder(BorderFactory.createMatteBorder(0, 0, 2, 0, Color.GRAY));
wordTextField.setFont(new Font(UIConstants.mainFont, Font.ITALIC, 14));
wordTextField.setHorizontalAlignment(JTextField.CENTER);
uploadImageLabel.setIcon(new ImageIcon(rm.getImage("add-icon.png", ResourceType.JAR).getScaledInstance(70, 70, Image.SCALE_SMOOTH)));
uploadSoundLabel.setIcon(new ImageIcon(rm.getImage("add-icon.png", ResourceType.JAR).getScaledInstance(70, 70, Image.SCALE_SMOOTH)));
uploadImageLabel.setText("");
uploadSoundLabel.setText("");
uploadImageLabel.setHorizontalAlignment(JLabel.CENTER);
uploadSoundLabel.setHorizontalAlignment(JLabel.CENTER);
//set up the textarea to look like a text field
step4ExplTextArea.setEditable(false);
step4ExplTextArea.setLineWrap(true);
step4ExplTextArea.setWrapStyleWord(true);
step4ExplTextArea.setBorder(javax.swing.BorderFactory.createEmptyBorder());
jScrollPane1.setBorder(null);
updateCategoriesComboBox();
categoriesComboBox.setBorder(new LineBorder(Color.decode(UIConstants.green), 1));
categoriesComboBox.setFont(new Font(UIConstants.green, Font.PLAIN, 14));
//temporarily disabling the following fields, not important to set by category
step7Label.setVisible(false);
soundCheckBox.setVisible(false);
imageCheckBox.setVisible(false);
textCheckBox.setVisible(false);
if (category == null) {
editStepsPanel.setVisible(false);
} else {
titleLabel.setText(rm.getTextOfXMLTag("editWord"));
//if the category has subcategories, fill the appropriate fields
if (category.getSubCategories().size() > 0) {
editStepsPanel.setVisible(true);
if (category.getRows() == null) {
rowsTextField.setText("");
} else {
rowsTextField.setText(String.valueOf(category.getRows()));
}
if (category.getColumns() == null) {
columnsTextField.setText("");
} else {
columnsTextField.setText(String.valueOf(category.getColumns()));
}
} else {
editStepsPanel.setVisible(false);
}
enabledCheckbox.setSelected(category.isEnabled());
wordTextField.setText(category.getName());
Image image = rm.getImage(category.getImage());
if (image == null) {
uploadImageLabel.setIcon(new ImageIcon(rm.getImage("add-icon.png", ResourceType.JAR).getScaledInstance(70, 70, Image.SCALE_SMOOTH)));
} else {
uploadImageLabel.setIcon(new ImageIcon(image.getScaledInstance(70, 70, Image.SCALE_SMOOTH)));
}
File sound = rm.getSound(category.getSound());
if (sound == null) {
uploadSoundLabel.setIcon(new ImageIcon(rm.getImage("add-icon.png", ResourceType.JAR).getScaledInstance(70, 70, Image.SCALE_SMOOTH)));
} else {
uploadSoundLabel.setIcon(new ImageIcon(rm.getImage("sound-icon.png", ResourceType.JAR).getScaledInstance(70, 70, Image.SCALE_SMOOTH)));
}
imageResource = category.getImage();
soundResource = category.getSound();
}
}
private void setListeners() {
uploadImageLabel.addMouseListener(new MouseAdapter() {
@Override
public void mouseExited(MouseEvent me) {
if (imageResource == null) {
uploadImageLabel.setIcon(new ImageIcon(rm.getImage("add-icon.png", ResourceType.JAR).getScaledInstance(70, 70, Image.SCALE_SMOOTH)));
}
}
@Override
public void mouseEntered(MouseEvent me) {
if (imageResource == null) {
uploadImageLabel.setIcon(new ImageIcon(rm.getImage("add-icon-hover.png", ResourceType.JAR).getScaledInstance(70, 70, Image.SCALE_SMOOTH)));
}
}
@Override
public void mouseClicked(MouseEvent me) {
JFileChooser chooser = new JFileChooser();
if (currentDirectory != null) {
chooser.setCurrentDirectory(currentDirectory);
}
chooser.setDialogTitle(rm.getTextOfXMLTag("selectImage"));
chooser.setAcceptAllFileFilterUsed(false);
chooser.setFileFilter(new FileNameExtensionFilter("Image Files", "png", "jpg", "jpeg", "JPG", "JPEG", "gif"));
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
imageResource = new ImageResource(chooser.getSelectedFile().getAbsolutePath(), ResourceType.LOCAL);
uploadImageLabel.setIcon(new ImageIcon(rm.getImage(imageResource).getScaledInstance(70, 70, Image.SCALE_SMOOTH)));
currentDirectory = chooser.getCurrentDirectory();
}
}
});
uploadSoundLabel.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent me) {
if (soundResource == null) {
uploadSoundLabel.setIcon(new ImageIcon(rm.getImage("add-icon-hover.png", ResourceType.JAR).getScaledInstance(70, 70, Image.SCALE_SMOOTH)));
} else {
uploadSoundLabel.setIcon(new ImageIcon(rm.getImage("sound-icon-hover.png", ResourceType.JAR).getScaledInstance(70, 70, Image.SCALE_SMOOTH)));
Media media = new Media(new File(soundResource.getSound().getAbsolutePath()).toURI().toString());
if (audioPlayer != null) {
audioPlayer.stop();
audioPlayer.dispose();
audioPlayer = null;
}
audioPlayer = AudioPlayer.getInstance().getMediaPlayer(media);
if (audioPlayer != null) {
audioPlayer.setOnEndOfMedia(new Runnable() {
@Override
public void run() {
if (audioPlayer != null) {
audioPlayer.dispose();
audioPlayer = null;
}
}
});
audioPlayer.setOnError(new Runnable() {
@Override
public void run() {
if (audioPlayer != null) {
JOptionPane.showMessageDialog(null, rm.getTextOfXMLTag("audioError"), "Error", JOptionPane.ERROR_MESSAGE);
logger.error("Media player could not play audio");
Sentry.capture("Media player could not play audio");
audioPlayer.dispose();
audioPlayer = null;
}
}
});
audioPlayer.play();
}
}
}
@Override
public void mouseExited(MouseEvent me) {
if (soundResource == null) {
uploadSoundLabel.setIcon(new ImageIcon(rm.getImage("add-icon.png", ResourceType.JAR).getScaledInstance(70, 70, Image.SCALE_SMOOTH)));
} else {
uploadSoundLabel.setIcon(new ImageIcon(rm.getImage("sound-icon.png", ResourceType.JAR).getScaledInstance(70, 70, Image.SCALE_SMOOTH)));
}
}
@Override
public void mouseClicked(MouseEvent me) {
JFileChooser chooser = new JFileChooser();
if (currentDirectory != null) {
chooser.setCurrentDirectory(currentDirectory);
}
chooser.setDialogTitle(rm.getTextOfXMLTag("selectSound"));
chooser.setAcceptAllFileFilterUsed(false);
chooser.setFileFilter(new FileNameExtensionFilter("Sound Files", "mp3", "wav", "wma", "mid"));
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
soundResource = new SoundResource(chooser.getSelectedFile().getAbsolutePath(), ResourceType.LOCAL);
uploadSoundLabel.setIcon(new ImageIcon(rm.getImage("sound-icon.png", ResourceType.JAR).getScaledInstance(70, 70, Image.SCALE_SMOOTH)));
currentDirectory = chooser.getCurrentDirectory();
}
}
});
wordTextField.addFocusListener(new FocusAdapter() {
public void focusGained(FocusEvent fe) {
if (rm.getTextOfXMLTag("word").equals(wordTextField.getText())) {
wordTextField.setText("");
}
}
public void focusLost(FocusEvent fe) {
if (wordTextField.getText().isEmpty()) {
wordTextField.setText(rm.getTextOfXMLTag("word"));
}
}
});
closeLabel.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent me) {
parent.hideInfoPanel();
parent.showInfoPanel();
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton backButton;
private javax.swing.JComboBox categoriesComboBox;
private javax.swing.JLabel closeLabel;
private javax.swing.JTextField columnsTextField;
private javax.swing.JPanel editStepsPanel;
private javax.swing.JCheckBox enabledCheckbox;
private javax.swing.JLabel errorLabel;
private javax.swing.JCheckBox imageCheckBox;
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextField rowsTextField;
private javax.swing.JButton saveButton;
private javax.swing.JCheckBox soundCheckBox;
private javax.swing.JLabel step1Label;
private javax.swing.JLabel step2Label;
private javax.swing.JLabel step3ExplLabel;
private javax.swing.JLabel step3Label;
private javax.swing.JTextArea step4ExplTextArea;
private javax.swing.JLabel step4Label;
private javax.swing.JLabel step6Label;
private javax.swing.JLabel step7Label;
private javax.swing.JCheckBox textCheckBox;
private javax.swing.JLabel titleLabel;
private javax.swing.JLabel uploadImageLabel;
private javax.swing.JLabel uploadSoundLabel;
private javax.swing.JTextField wordTextField;
private javax.swing.JLabel xLabel;
// End of variables declaration//GEN-END:variables
}
| scify/TalkAndPlay | src/main/java/org/scify/talkandplay/gui/configuration/WordFormPanel.java |
2,473 | package com.ceid.crowder;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
public class Registration extends AppCompatActivity {
private Button next;
private CheckBox terms;
private boolean accepted = false;
private EditText musername;
private EditText memail;
private EditText mpassword;
private EditText mreppassword;
ProgressBar registrationprogress;
FirebaseAuth fAuth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Hide Title Bar Coz Crashes
getSupportActionBar().hide();
setContentView(R.layout.activity_registration);
fAuth = FirebaseAuth.getInstance();
if (fAuth.getInstance().getCurrentUser() == null) {
//Go to login
}
else{
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
GoToMain();
}
registrationprogress = findViewById(R.id.registrationprogress2);
//Terms of Service Checkbox
terms = (CheckBox) findViewById(R.id.terms);
terms.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View V) {
accepted = true;
}
});
musername = findViewById(R.id.username);
memail = findViewById(R.id.regemail);
mpassword = findViewById(R.id.regpassword);
mreppassword = findViewById(R.id.password_rep);
//Just The Next Button
next = (Button) findViewById(R.id.next);
next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View V) {
//Collection and Checking of Data Inserted
String email = memail.getText().toString().trim();
String password = mpassword.getText().toString().trim();
String username = musername.getText().toString().trim();
String reppassword = mreppassword.getText().toString().trim();
if(TextUtils.isEmpty(username)){
musername.setError("Παρακαλώ Εισάγετε Ένα Όνομα Χρήστη.");
return;
}
if(TextUtils.isEmpty(email)){
memail.setError("Παρακαλώ Εισάγετε Μία Διεύθυνση eMail.");
return;
}
if(TextUtils.isEmpty(password)){
mpassword.setError("Παρακαλώ Εισάγετε Έναν Κωδικό.");
return;
}
if(TextUtils.isEmpty(reppassword)){
mreppassword.setError("Παρακαλώ Εισάγετε Ξανά Τον Κωδικό.");
return;
}
if(password.length() < 6){
mpassword.setError("Ο Κωδικός Πρέπει να Περιέχει Τουλάχιστον 6 Ψηφία");
return;
}
//Check if Terms Accepted
if(accepted) {
//Enable The Progress Bar
registrationprogress.setVisibility(View.VISIBLE);
//Register To Firebase
fAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Toast.makeText(Registration.this,"Η Εγγραφή Ήταν Επιτυχής!",Toast.LENGTH_SHORT).show();
FinishRegistration();
}
else{
Toast.makeText(Registration.this,"Η Εγγραφή Απέτυχε." + task.getException().getMessage(),Toast.LENGTH_SHORT).show();
}
}
});
}
else{
terms.setError( "Πρέπει Να Αποδεχτείτε Τους Όρους Για Να Συνεχίσετε!" );
}
}
});
}
public void GoToLogin(){
Intent intent = new Intent(this, LoginFinal.class);
startActivity(intent);
}
public void FinishRegistration(){
Intent intent = new Intent(this, FinishRegistration.class);
startActivity(intent);
}
public void GoToMain(){
Intent intent = new Intent(this, Home.class);
startActivity(intent);
}
} | Tonyzaf/Crowder | CrowderApp/app/src/main/java/com/ceid/crowder/Registration.java |
2,474 | package com.kara.bachelorpapel.entity;
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Size;
import java.util.ArrayList;
import java.util.List;
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "User_Id")
private Integer userId;
@Column(name = "username",unique = true)
@NotEmpty(message = "Το πεδίο είναι υποχρεωτικό!")
@Size(min=2,max=10,message = "Το πεδίο πρέπει να περιέχει 2-10 χαρακτήρες!")
private String username;
@Column(name = "Password",unique = true)
@NotEmpty(message = "*Το πεδίο είναι υποχρεωτικό!")
@Size(min=2,max=15,message = "Το πεδίο πρέχει να περιέχει 2-15 χαρακτήρες ")
private String password;
@Column(name = "FirstName")
@NotEmpty(message = "*Το πεδίο είναι υποχρεωτικό")
@Size(min = 2,max = 15)
private String firstname;
@Column(name = "LastName")
@NotEmpty(message = "*Το πεδίο είναι υποχρεωτικό")
@Size(min = 2,max = 15)
private String lastname;
@OneToOne(mappedBy = "user", cascade = CascadeType.REMOVE,orphanRemoval = true)
private StudentInfo studentInfo;
@OneToMany(mappedBy = "user",cascade = CascadeType.ALL)
private List<Education> educations;
@OneToMany(mappedBy = "user",cascade = CascadeType.ALL)
private List<Experience> experiences;
@OneToMany(mappedBy = "user",cascade = CascadeType.ALL)
private List<Email> emails;
@OneToMany(mappedBy = "user",cascade = CascadeType.ALL)
private List<Phone> phones;
@OneToMany(mappedBy = "user",cascade = CascadeType.ALL)
private List<Address> addresses;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(
name = "users_roles",
joinColumns = @JoinColumn(name = "user_id"),
inverseJoinColumns = @JoinColumn(name = "role_id")
)
private List<Role> roles=new ArrayList<>() ;
}
| NnKara/Bachelor | src/main/java/com/kara/bachelorpapel/entity/User.java |
2,476 | package rabbitminer.ClusterNode.Miner;
import java.security.GeneralSecurityException;
import rabbitminer.ClusterNode.ClusterNode;
import rabbitminer.ClusterNode.Miner.POW.POW;
import rabbitminer.ClusterNode.Miner.POW.*;
import rabbitminer.Core.Computer;
import rabbitminer.Crypto.CryptoAlgorithms.ECryptoAlgorithm;
import rabbitminer.Stratum.StratumJob;
/**
*
* @author Nikos Siatras
*/
public class Miner
{
private final ClusterNode fMyClusterNode;
// Miner Threads
private final int fActiveMinersCount;
private final int fMaxMinersCount;
protected final MinerThread[] fMinerThreads;
public POW fMyPOW;
// Locks
private final Object fSetPowLock = new Object(); // Αυτό το Lock είναι για το SetPow
public Miner(ClusterNode myClusterNode)
{
fMyClusterNode = myClusterNode;
fActiveMinersCount = Computer.getComputerCPUCoresCount();
fMaxMinersCount = fActiveMinersCount;
try
{
fMyPOW = new POW(ECryptoAlgorithm.SCrypt);
fMyPOW.AssignJob(null);
}
catch (Exception ex)
{
}
// Ξεκινάμε Threads
fMinerThreads = new MinerThread[fMaxMinersCount];
boolean min = true;
for (int i = 0; i < fMaxMinersCount; i++)
{
fMinerThreads[i] = new MinerThread(i, this);
fMinerThreads[i].setName("Thread #" + i);
fMinerThreads[i].setPriority(Thread.MIN_PRIORITY);
fMinerThreads[i].start();
min = !min;
}
}
public void setPOW(final POW pow)
{
synchronized (fSetPowLock)
{
fMyPOW = pow;
// Κάνουμε Set το POW σε κάθε MineThread!
for (MinerThread th : fMinerThreads)
{
th.SetMyPOW(fMyPOW);
}
}
}
public void SetJob(final StratumJob job) throws GeneralSecurityException
{
synchronized (fSetPowLock)
{
// Έλεγξε αν πρέπει να αλλαχθεί το POW
boolean changePow = fMyPOW == null || fMyPOW.fMyJob == null || (fMyPOW.fMyJob.getCryptoAlgorithm() != job.getCryptoAlgorithm());
// Αν το Job είναι Null κάνει σετ το
if (job == null)
{
fMyPOW = new POW(ECryptoAlgorithm.SCrypt);
}
// Ανάλογα με το CryptoAlgorithm σέταρε στον Miner το
// σωστό POW
switch (job.getCryptoAlgorithm())
{
case SCrypt:
if (changePow)
{
setPOW(new POW_SCrypt());
}
fMyPOW.AssignJob(job);
break;
case RandomX:
if (changePow)
{
setPOW(new POW_RandomX());
}
fMyPOW.AssignJob(job);
break;
}
final int nOnceFrom = job.getNOnceRangeFrom();
final int nOnceTo = job.getNOnceRangeTo();
final int totalNOnce = nOnceTo - nOnceFrom;
// Το κάθε thread θα ψάξει σε δικό του Range
final int nOnceRangeStep = totalNOnce / fActiveMinersCount;
for (int i = 0; i < fActiveMinersCount; i++)
{
final int start = nOnceFrom + (i * nOnceRangeStep);
int end = (start + nOnceRangeStep) - 1;
// Για το τελευταίο Thread στη σειρά
if (i == (fActiveMinersCount - 1) && end < nOnceTo)
{
end = nOnceTo;
}
// Set the NOnce range that the Miner Thread has to work on
fMinerThreads[i].SetRange(start, end);
}
fMyClusterNode.setStatus("Mining...");
}
}
public ClusterNode getMyClusterNode()
{
return fMyClusterNode;
}
public void TellThreadsToKillLoops()
{
for (MinerThread th : fMinerThreads)
{
th.KillLoop();
}
}
public void WaitForAllMinerThreadsToFinishWork()
{
ClusterNode.ACTIVE_INSTANCE.setStatus("Waiting for miner threads to finish their work");
for (MinerThread th : fMinerThreads)
{
th.WaitToFinishScanning();
}
//System.out.println("All Miner Threads finished their work!");
}
public double getHashesPerSecond()
{
double result = 0;
try
{
for (MinerThread th : fMinerThreads)
{
result += th.getHashesPerSecond();
}
}
catch (Exception ex)
{
}
return result;
}
}
| SourceRabbit/Rabbit_Miner | RabbitMiner/src/rabbitminer/ClusterNode/Miner/Miner.java |
2,479 | /**
* Copyright (c) 2010-2024 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.core.scheduler;
import java.util.Map;
import org.eclipse.jdt.annotation.NonNullByDefault;
/**
* The software utility Cron is a time-based job scheduler in Unix-like computer
* operating systems. People who set up and maintain software environments use
* cron to schedule jobs (commands or shell scripts) to run periodically at
* fixed times, dates, or intervals. It typically automates system maintenance
* or administration—though its general-purpose nature makes it useful for
* things like connecting to the Internet and downloading email at regular
* intervals.[1] The name cron comes from the Greek word for time, χρόνος
* chronos.
* <p>
* The Unix Cron defines a syntax that is used by the Cron service. A user
* should register a Cron service with the {@link CronJob#CRON} property. The
* value is according to the <a href="https://en.wikipedia.org/wiki/Cron">Cron</a>.
* <p>
*
* <pre>
* * * * * * * *
* | │ │ │ │ │ |
* | │ │ │ │ │ └ year (optional)
* | │ │ │ │ └── day of week from Monday (1) to Sunday (7).
* | │ │ │ └──── month (1 - 12) from January (1) to December (12).
* | │ │ └────── day of month (1 - 31)
* | │ └──────── hour (0 - 23)
* | └────────── min (0 - 59)
* └──────────── sec (0-59)
* </pre>
*
* <pre>
* Field name mandatory Values Special characters
* Seconds Yes 0-59 * / , -
* Minutes Yes 0-59 * / , -
* Hours Yes 0-23 * / , -
* Day of month Yes 1-31 * / , - ? L W
* Month Yes 1-12 or JAN-DEC * / , -
* Day of week Yes 1-7 or MON-SUN * / , - ? L #
* Year No 1970–2099 * / , -
* </pre>
*
* <h3>Asterisk ( * )</h3>
* <p>
* The asterisk indicates that the cron expression matches for all values of the
* field. E.g., using an asterisk in the 4th field (month) indicates every
* month.
* <h3>Slash ( / )</h3>
* <p>
* Slashes describe increments of ranges. For example 3-59/15 in the 1st field
* (minutes) indicate the third minute of the hour and every 15 minutes
* thereafter. The form "*\/..." is equivalent to the form "first-last/...",
* that is, an increment over the largest possible range of the field.
* <h3>Comma ( , )</h3>
* <p>
* Commas are used to separate items of a list. For example, using "MON,WED,FRI"
* in the 5th field (day of week) means Mondays, Wednesdays and Fridays. Hyphen
* ( - ) Hyphens define ranges. For example, 2000-2010 indicates every year
* between 2000 and 2010 AD, inclusive.
* <p>
* Additionally, you can use some fixed formats:
*
* <pre>
* @yearly (or @annually) Run once a year at midnight on the morning of January 1 0 0 1 1 *
* @monthly Run once a month at midnight on the morning of the first day of the month 0 0 1 * *
* @weekly Run once a week at midnight on Sunday morning 0 0 * * 0
* @daily Run once a day at midnight 0 0 * * *
* @hourly Run once an hour at the beginning of the hour 0 * * * *
* @reboot Run at startup @reboot
* </pre>
* <p>
* Please note that for the constants we follow the Java 8 Date and Time constants.
* Major difference is the day number. In Quartz this is 0-6 for SAT-SUN while
* here it is 1-7 for MON-SUN.
*
* @author Peter Kriens - Initial contribution
* @author Simon Kaufmann - adapted to CompletableFutures
* @author Hilbrand Bouwkamp - Moved Cron scheduling to it's own interface
*/
@NonNullByDefault
public interface CronScheduler {
/**
* Schedule a runnable to be executed for the give cron expression (See
* {@link CronJob}). Every time when the cronExpression matches the current
* time, the runnable will be run. The method returns a {@link ScheduledCompletableFuture}
* that can be used to stop scheduling. This variation does not take an
* environment object.
*
* @param runnable The runnable to run
* @param cronExpression A cron expression
* @return A {@link ScheduledCompletableFuture} to cancel the schedule
*/
ScheduledCompletableFuture<Void> schedule(SchedulerRunnable runnable, String cronExpression);
/**
* Schedule a runnable to be executed for the give cron expression (See
* {@link CronJob}). Every time when the cronExpression matches the current
* time, the runnable will be run. The method returns a {@link ScheduledCompletableFuture}
* that can be used to stop scheduling. The run method of cronJob takes
* an environment object. An environment object is a custom interface where
* the names of the methods are the keys in the properties (see {@link org.openhab.core.items.dto.ItemDTO DTOs}).
*
* @param cronJob The runnable to run
* @param cronExpression A cron expression
* @return A {@link ScheduledCompletableFuture} to cancel the schedule
*/
ScheduledCompletableFuture<Void> schedule(CronJob cronJob, Map<String, Object> config, String cronExpression);
}
| openhab/openhab-core | bundles/org.openhab.core/src/main/java/org/openhab/core/scheduler/CronScheduler.java |
2,482 | import org.xml.sax.SAXException;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Objects;
public class Main {
public static void main(String []args) throws ParserConfigurationException, IOException, SAXException {
int dementions = 2;
ArrayList<String> dedomena = new ArrayList<>();
dedomena.add("lat");
dedomena.add("lon");
///ΜΠΟΡΕΙ ΝΑ ΧΡΕΙΑΣΤΕΙ ΑΛΛΑΓΗ PATH ΓΙΑ ΝΑ ΔΙΑΒΑΣΕΙ ΤΟ ΑΡΧΕΙΟ
String osmFile = "map.osm";
AllBlocks allBlocks = new AllBlocks();
System.out.println("Διάβασμα από αρχειο:");
allBlocks.readFromOsmFile(dementions, osmFile, dedomena);
ArrayList<Block> returned = allBlocks.readFromBinaryFile();
CreateRTree r_tree = new CreateRTree(returned);
r_tree.createTree();
R_Tree actualTree = new R_Tree(r_tree.allNodes.get(0), r_tree.allNodes, r_tree.rect_id_count, r_tree.node_id_count);
actualTree.writeToFile();
Skyline skyline = new Skyline();
Delete delete = new Delete();
Insert insert = new Insert();
////////ΚΝΝ
//LeafRecords point=new LeafRecords("rec Knn",38.3744238,21.8528735);//δεδομενα ναυπακτου
LeafRecords point=new LeafRecords("rec Knn",41.4635367,26.5648868);
Knn knn=new Knn(25,actualTree,point);
ArrayList<LeafRecords> otinanai=knn.kontinotera;
System.out.println();
System.out.println();
long startTime = System.nanoTime();//////START TIME KNN WITH R_TREE
System.out.println("--------- Knn results -------------------:");
knn.isTouching(actualTree,actualTree.getRoot().allRectangles);
knn.isInCircle(actualTree.getRoot());
System.out.println();
long endTime = System.nanoTime();
long totalTime = endTime - startTime;//END TIME KNN R_TREE
Double time = (double) totalTime;
time=time/1000000000;
System.out.println("Χρόνος Κnn με χρήση δένδρου: "+time+"sec");
///Σειριακά βρίσκω τους Knn
startTime = System.nanoTime();//////START TIME KNN SEIRIAKA
otinanai=knn.knnSeiriaka(otinanai);
System.out.println();
endTime = System.nanoTime();
totalTime = endTime - startTime;//END TIME KNN SEIRIAKA
time = (double) totalTime;
time=time/1000000000;
System.out.println("Χρόνος Κnn με χρήση σειριακής αναζήτησης: "+time+"sec");
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
System.out.println();
System.out.println();
System.out.println();
System.out.println();
/////////////Code for Search.
System.out.println("<--------------------------------Επόμενο ερώτημα-------------------------------->");
//Δημιουργία ορθογωνίου για ερώτημα περιοχής
MBR anazitisi=new MBR();
anazitisi.setId("rec anazitis");
/** anazitisi.diastaseisA.add(38.3588721);//naupktos
anazitisi.diastaseisA.add(21.7987221);
anazitisi.diastaseisB.add(38.3748695);
anazitisi.diastaseisB.add(21.8534671);*/
///to diko tou arxeio
/** anazitisi.diastaseisA.add(41.5025026);
anazitisi.diastaseisA.add(26.4715030);//132
anazitisi.diastaseisB.add(41.5372766);//418
anazitisi.diastaseisB.add(26.5162474);*/
//to diko tou arxeio
anazitisi.diastaseisA.add(41.4925026);
anazitisi.diastaseisA.add(26.4615030);//6463
anazitisi.diastaseisB.add(41.5372766);//δικο μου
anazitisi.diastaseisB.add(26.5162474);
Search ser=new Search(actualTree);
ArrayList<Nodes> dummy=new ArrayList<>();
dummy.add(actualTree.getRoot());
startTime = System.nanoTime();//////START TIME Search with R_Tree
ArrayList<MBR> mbrTouching=ser.anazit(actualTree,dummy,anazitisi);
ArrayList<LeafRecords>results=ser.findMbrPeriexomeno(mbrTouching,anazitisi);
endTime = System.nanoTime();
totalTime = endTime - startTime;//END TIME Search with R_Tree
time = (double) totalTime;
time=time/1000000000;
System.out.println("Χρόνος για ερώτημα περιοχής με χρήση R_Tree: "+time+"sec");
//Αποτελέσματα σε ερώτημα περιοχής(Σειριακά)
startTime = System.nanoTime();//////START TIME Search with (Σειριακά)
ArrayList<Record> resultsSeiriaka=ser.searchSeiriaka(anazitisi);
endTime = System.nanoTime();
totalTime = endTime - startTime;//END TIME Search with R_Tree
time = (double) totalTime;
time=time/1000000000;
System.out.println("Χρόνος για ερώτημα περιοχής (Σειριακά): "+time+"sec");
int c=0;
for(LeafRecords function:results)
{
// System.out.println("C: " + c);
// function.printRecord();
c++;
}
System.out.println("Μέσα στο παράθυρο αναζήτησης υπήρχαν: "+c+" σημεία");
System.out.println("<--------------------------------Επόμενο ερώτημα-------------------------------->");
//////// 1
startTime = System.nanoTime();
System.out.println("Skyline: ");
skyline.seiriaka();
System.out.println();
endTime = System.nanoTime();
totalTime = endTime - startTime;//END TIME KNN R_TREE
time = (double) totalTime;
time=time/1000000000;
System.out.println("Χρόνος Skyline seiriaka: "+time+"sec");
System.out.println("Skyline-->Running time is: "+totalTime+" nanoseconds");
System.out.println();
System.out.println("<--------------------------------Επόμενο ερώτημα-------------------------------->");
//////// 2
startTime = System.nanoTime();
System.out.println("Skyline R* Tree: ");
skyline.createSkyline(actualTree);
System.out.println();
endTime = System.nanoTime();
totalTime = endTime - startTime;//END TIME KNN R_TREE
time = (double) totalTime;
time=time/1000000000;
System.out.println("Χρόνος Skyline r* tree: "+time+"sec");
System.out.println("Skyline-R_Tree-->Running time is: "+totalTime+" nanoseconds");
System.out.println();
System.out.println("<--------------------------------Επόμενο ερώτημα-------------------------------->");
//////// 3
startTime = System.nanoTime();
System.out.println("Delete Seiriaka: ");
LeafRecords leafRecords = new LeafRecords("delete",38.4096078, 21.9065266);
boolean dLeaf = delete.deleteLeafMR(actualTree, actualTree.root, leafRecords);
allBlocks.deleteFromDatafile(38.4096078, 21.9065266);
System.out.println();
endTime = System.nanoTime();
totalTime = endTime - startTime;//END TIME KNN R_TREE
time = (double) totalTime;
time=time/1000000000;
System.out.println("Χρόνος Delete seiriaka: "+time+"sec");
System.out.println("Delete-->Running time is: "+totalTime+" nanoseconds");
System.out.println();
System.out.println("<--------------------------------Επόμενο ερώτημα-------------------------------->");
//////// 4
startTime = System.nanoTime();
System.out.println("Delete R TREΕ: ");
leafRecords = new LeafRecords("delete",38.4096078, 21.9065266);
dLeaf = delete.deleteLeafMR(actualTree, actualTree.root, leafRecords);
// allBlocks.deleteFromDatafile(38.4096078, 21.9065266);
System.out.println();
endTime = System.nanoTime();
totalTime = endTime - startTime;//END TIME KNN R_TREE
time = (double) totalTime;
time=time/1000000000;
System.out.println("Χρόνος Delete R*-Tree: "+time+"sec");
System.out.println("Delete-R_Tree-->Running time is: "+totalTime+" nanoseconds");
System.out.println();
System.out.println("<--------------------------------Επόμενο ερώτημα-------------------------------->");
//////// 5
startTime = System.nanoTime();
System.out.println("Insert όλο το δέντρο: ");
R_Tree rTree2 = new R_Tree();
int j=0;
for(Block b: allBlocks.allBlocks){
for(Record r: b.oneBlock) {
LeafRecords leafRecords1 = new LeafRecords(r);
if (j == 0) {
Nodes n = new Nodes();
n.setId("node0");
MBR mbr = new MBR();
mbr.id = "rect0";
mbr.diastaseisA.add(r.getDiastaseis().get(0));
mbr.diastaseisB.add(r.getDiastaseis().get(0));
mbr.diastaseisA.add(r.getDiastaseis().get(1));
mbr.diastaseisB.add(r.getDiastaseis().get(1));
mbr.periexomeno.add(leafRecords1);
n.allRectangles.add(mbr);
rTree2.allNodes.add(n);
}
else{
insert.doTheInsert(rTree2, leafRecords1);
}
j++;
}
}
System.out.println();
endTime = System.nanoTime();
totalTime = endTime - startTime;//END TIME KNN R_TREE
time = (double) totalTime;
time=time/1000000000;
rTree2.printDetails();
System.out.println("Χρόνος Insert όλου του δέντρου: "+time+"sec");
System.out.println("Insert-->Running time is: "+totalTime+" nanoseconds");
System.out.println();
System.out.println("<--------------------------------Επόμενο ερώτημα-------------------------------->");
//////// 6
startTime = System.nanoTime();
System.out.println("Χρονος Bottom-up: ");
r_tree = new CreateRTree(returned);
r_tree.createTree();
actualTree = new R_Tree(r_tree.allNodes.get(0), r_tree.allNodes, r_tree.rect_id_count, r_tree.node_id_count);
System.out.println();
endTime = System.nanoTime();
totalTime = endTime - startTime;//END TIME KNN R_TREE
time = (double) totalTime;
time=time/1000000000;
System.out.println("Bottom-up: "+time+"sec");
System.out.println("Bottom-up-R_Tree-->Running time is: "+totalTime+" nanoseconds");
System.out.println();
}
} | ampatzidhs/R_tree | src/Main.java |
2,483 | import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* In this class we implement the countdown clock for the StopTheClock game (1 or 2 players)
*/
abstract class CountDown extends JPanel {
JLabel label;
Timer timer;
int second = 5;
int milliSecond = 1;
/**
* The constructor of the clock, that counts backwards until the end of the five seconds the player/players has/have available to answer the question.
*/
public CountDown() {
label = new JLabel("Υπολοιπόμενος χρόνος: "+second);
setLayout(new GridBagLayout());
add(label);
timer = new Timer(1, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
milliSecond -= 1;
if (second>-1) {
if(milliSecond==0) {
milliSecond = 999;
second--;
}
label.setText("Υπολοιπόμενος χρόνος: " + second + ": " + milliSecond);
} else {
((Timer) (e.getSource())).stop();
label.setText("Ο χρόνος τελείωσε");
onFinish();
}
}
});
timer.setInitialDelay(0);
timer.start();
}
/**
* Timer with custom time delay.
* @param sec time delay
*/
public CountDown(int sec){
this.second = sec;
timer = new Timer(1, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
milliSecond -= 1;
if (second>-1) {
if(milliSecond==0) {
milliSecond = 999;
second--;
}
} else {
((Timer) (e.getSource())).stop();
onFinish();
}
}
});
timer.setInitialDelay(0);
timer.start();
}
/**
* When a button with answer is clicked then the clock stop
*/
public void buttonClicked(){
timer.stop();
}
/**
* This is a method that return the remaining time in the clock
* @return the remaining time in the clock for count the score
*/
public int getRemainingTime() {
return second*1000+milliSecond;
}
/**
* @return the seconds in the clock
*/
public int getSecond(){
return second;
}
/**
* @return the milliseconds in the clock
*/
public int getMilliSecond() {
return milliSecond;
}
/**
* function to be called after timer goes under the zero seconds
*/
public abstract void onFinish();
} | nicktz1408/buzz | src/CountDown.java |
2,484 | package basics;
import java.io.Serializable;
/*αναπαράσταση των πληροφοριών που παρέχονται στις κριτικές της κάθε επιχείρησης*/
/*κάθε επιχείρηση περιέχει πολλά αντικείμενα τύπου Review σε ένα ArrayList*/
public class Review implements Serializable{
private String text; //κειμενο κριτικής
private String userName; //ονομα χρήστη που έγραψε την κριτική
private Long rating; //βαθμολογία
private String timeCreated; //χρόνος δημιουργίας της κριτικής
public Review() {
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Long getRating() {
return rating;
}
public void setRating(Long rating) {
this.rating = rating;
}
public String getTimeCreated() {
return timeCreated;
}
public void setTimeCreated(String timeCreated) {
this.timeCreated = timeCreated;
}
@Override
public String toString() {
return "Review{" +
"text=" + text + " " +
", userName=" + userName + " " +
", rating=" + rating + " " +
", timeCreated=" + timeCreated + " " +
'}';
}
}
| JohnChantz/JavaII-YelpAPI-Project | YelpBasics/src/basics/Review.java |
2,485 | // Genikefsi - Polymorfismos #2
// ergastirio 9
import java.text.DecimalFormat;
abstract class Tilefono {
private String arithmosTilefonou;
private float callToStatheroCostPerSecond;
private float callToKinitoCostPerSecond;
private int callsToStatheroTotalSeconds;
private int callsToKinitoTotalSeconds;
private int totalSecondsOnCall;
private float totalCallsCost;
// Default constructor
public Tilefono() {
}
// Semi constructor
public Tilefono(String new_arithmosTilefonou) {
this.arithmosTilefonou = new_arithmosTilefonou;
this.callToStatheroCostPerSecond = 0;
this.callToKinitoCostPerSecond = 0;
this.callsToStatheroTotalSeconds = 0;
this.callsToKinitoTotalSeconds = 0;
this.totalSecondsOnCall = 0;
this.totalCallsCost = 0;
}
// Full Constructor
public Tilefono(String new_arithmosTilefonou, float new_callToStatheroCostPerSecond, float new_callToKinitoCostPerSecond) {
this.arithmosTilefonou = new_arithmosTilefonou;
this.callToStatheroCostPerSecond = new_callToStatheroCostPerSecond;
this.callToKinitoCostPerSecond = new_callToKinitoCostPerSecond;
this.callsToStatheroTotalSeconds = 0;
this.callsToKinitoTotalSeconds = 0;
this.totalSecondsOnCall = 0;
this.totalCallsCost = 0;
}
abstract void dial(String numberToCall, int tmp_dialDuration); // Υλοποιείται διαφορετικά σε κάθε είδος τηλεφώνου (ΣΤΑΘΕΡΟ/ΚΙΝΗΤΟ)
public float cost(char phoneType) {
float tmp_callsCost;
switch (phoneType) {
case '2': // ΚΟΣΤΟΣ ΚΛΗΣΕΩΝ ΠΡΟΣ ΣΤΑΘΕΡΑ
tmp_callsCost = this.callsToStatheroTotalSeconds * this.callToStatheroCostPerSecond;
break;
case '6': // ΚΟΣΤΟΣ ΚΛΗΣΕΩΝ ΠΡΟΣ ΚΙΝΗΤΑ
tmp_callsCost = this.callsToKinitoTotalSeconds * this.callToKinitoCostPerSecond;
break;
default:
tmp_callsCost = 0.0f;
break;
}
this.totalCallsCost = (this.callsToStatheroTotalSeconds * this.callToStatheroCostPerSecond) + (this.callsToKinitoTotalSeconds * this.callToKinitoCostPerSecond);
return tmp_callsCost;
}
public int getTotalSecondsOnCallFromLine() {
return this.getTotalSecondsOnCalls();
}
public float getTotalCostFromLine() {
return this.getTotalCallsCost();
}
public String showCallsSecondsAndCost(char phoneType) { // Είναι ίδια για όλες τις κλάσεις
DecimalFormat df = new DecimalFormat(); // Για στρογγυλοποίηση των δεκαδικών ψηφίων του float
df.setMaximumFractionDigits(2); // Για στρογγυλοποίηση των δεκαδικών ψηφίων του float
switch (phoneType) {
case '2':
return ("Γραμμή: " + this.getPhoneNumber() + ". Συνολικός χρόνος κλήσεων προς ΣΤΑΘΕΡΑ: " + this.callsToStatheroTotalSeconds +
"sec. Συνολικό κόστος κλήσεων προς ΣΤΑΘΕΡΑ: " + df.format(this.cost(phoneType)) + "€.");
case '6':
return ("Γραμμή: " + this.getPhoneNumber() + ". Συνολικός χρόνος κλήσεων προς ΚΙΝΗΤΑ: " + this.callsToKinitoTotalSeconds +
"sec. Συνολικό κόστος κλήσεων προς ΚΙΝΗΤΑ: " + df.format(this.cost(phoneType)) + "€.");
case 'A':
return ("Γραμμή: " + this.getPhoneNumber() + ". Συνολικός χρόνος κλήσεων προς ΟΛΑ: " + this.totalSecondsOnCall +
"sec. Συνολικό κόστος κλήσεων προς ΟΛΑ: " + df.format((this.cost('2') + this.cost('6'))) + "€.");// +
default: return ("ΔΟΘΗΚΕ ΛΑΘΟΣ ΕΙΔΟΣ ΤΗΛΕΦΩΝΟΥ.");
}
}
// Set-Get phoneNumber
public void setPhoneNumber(String new_phoneNumber) {
this.arithmosTilefonou = new_phoneNumber;
}
public String getPhoneNumber() {
return this.arithmosTilefonou;
}
// Set-Get callCostPerSecond STATHERO
public void setCallToStatheroCostPerSecond(float new_callCostPerSecond) {
this.callToStatheroCostPerSecond = new_callCostPerSecond;
}
public float getCallToStatheroCostPerSecond() {
return this.callToStatheroCostPerSecond;
}
// Set-Get callCostPerSecond KINITO
public float getCallToKinitoCostPerSecond() {
return this.callToKinitoCostPerSecond;
}
public void setCallToKinitoCostPerSecond(float new_callCostPerSecond) {
this.callToKinitoCostPerSecond = new_callCostPerSecond;
}
// Set-Get callToStathroTotalSeconds STATHERO
public int getCallsToStatheroTotalSeconds() {
return this.callsToStatheroTotalSeconds;
}
public void setCallsToStatheroTotalSeconds(int new_callSeconds) {
this.callsToStatheroTotalSeconds = this.callsToStatheroTotalSeconds + new_callSeconds;
}
// Set-Get callToKinitoTotalSecond KINITO
public int getCallsToKinitoTotalSeconds() {
return this.callsToKinitoTotalSeconds;
}
public void setCallsToKinitoTotalSeconds(int new_callSeconds) {
this.callsToKinitoTotalSeconds = this.callsToKinitoTotalSeconds + new_callSeconds;
}
// Set-Get totalSecondsOnCalls
public int getTotalSecondsOnCalls() {
return this.totalSecondsOnCall;
}
public void setTotalSecondsOnCalls(int new_totalSecondsOnCall) {
this.totalSecondsOnCall = this.totalSecondsOnCall + new_totalSecondsOnCall;
}
// Set-Get totalCallsCost
public float getTotalCallsCost() {
return this.totalCallsCost;
}
public void setTotalCallsCost(float new_totalCallsCost) {
this.totalCallsCost = this.cost('2') + this.cost('6');
}
// Return all attributes in one string
public String toString() {
float dummy_totalCost = this.cost('2') + this.cost('6');
DecimalFormat df = new DecimalFormat(); // Για στρογγυλοποίηση των δεκαδικών ψηφίων του float
df.setMaximumFractionDigits(2); // Για στρογγυλοποίηση των δεκαδικών ψηφίων του float
return ("Γραμμή: " + this.arithmosTilefonou + ". Σύνολο δευτερολέπτων σε κλήση: " + this.totalSecondsOnCall + ". Συνολικό κόστος κλήσεων: " +
df.format(this.totalCallsCost) + "€.");
}
}
| panosale/DIPAE_OOP_2nd_Term-JAVA | Askisis/Ergastirio9(done)/src/Tilefono.java |
2,489 | import java.io.*;
import java.util.Random;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class MerosD
{
static long maxLineral=Long.MIN_VALUE;
static long maxBinary=Long.MIN_VALUE;
static long maxInterpolation=Long.MIN_VALUE;//μεγιστος χρονος
static long maxRBTree=Long.MIN_VALUE;
static long minLineral= Long.MAX_VALUE;
static long minBinary= Long.MAX_VALUE;
static long minInterpolation= Long.MAX_VALUE;//ελαχιστος χρονος αρχικοποιειται με το μαχ του long
static long minRBTree=Long.MAX_VALUE;
static long moLineral=0;
static long moBinary=0;
static long moInterpolation=0;//μεσος ορος χρονου
static long moRBTree=0;
static long sumLineral=0;//αθροισμα ολων των χρονων
static long sumBinary=0;
static long sumInterpolation=0;
static long sumRBTree=0;
static int number;
static int i=0;
public static void times(){
try{
PrintWriter pw = new PrintWriter(new File("Searching Time.csv"));
StringBuilder sb = new StringBuilder();
sb.append("Linear Search Time");
sb.append(';');
sb.append("Binary Search Time");
sb.append(';');
sb.append("Interpolation Search Time");
sb.append(';');
sb.append("Red-Black Tree Search Time");
sb.append(';');
sb.append("Search Number");
sb.append('\n');
try{ MerosA.readIntegers();}catch(IOException e){}
MerosA.mergeSort(MerosA.initialArray);
for(int i=0; i<=100; i++){ //100anazhthseis!
// Random rand = new Random();
//int randomNumber = rand.nextInt(100) ;
// number=randomNumber;
number=i;
long startLineral = System.nanoTime();
MerosB.lineralSearch(number);
long elapsedNanoTimeLineral = System.nanoTime()-startLineral;
System.out.println("Lineral Search Finished\n");
sumLineral=elapsedNanoTimeLineral + sumLineral;
if(elapsedNanoTimeLineral>maxLineral){maxLineral=elapsedNanoTimeLineral;}
if(elapsedNanoTimeLineral<minLineral){minLineral=elapsedNanoTimeLineral;}
long startBinary = System.nanoTime();
MerosB.binarySearch(number);
long elapsedNanoTimeBinary = System.nanoTime()-startBinary;
System.out.println("Binary Search Finished\n");
sumBinary=elapsedNanoTimeBinary + sumBinary;
if(elapsedNanoTimeBinary>maxBinary){maxBinary=elapsedNanoTimeBinary;}
if(elapsedNanoTimeBinary<minBinary){minBinary=elapsedNanoTimeBinary;}
long startInterpolation = System.nanoTime();
MerosB.interpolationSearch(number);
long elapsedNanoTimeInterpolation= System.nanoTime()-startInterpolation;
System.out.println("Interpolation Search Finished\n");
sumInterpolation=elapsedNanoTimeInterpolation + sumInterpolation;
if(elapsedNanoTimeInterpolation>maxInterpolation){maxInterpolation=elapsedNanoTimeInterpolation;}
if(elapsedNanoTimeInterpolation<minInterpolation){minInterpolation=elapsedNanoTimeInterpolation;}
/* int y;
for(int j=0; j<MerosA.count; j++){
//MerosA.initialArray.get(y)=
RBTreeInsert(MerosA.initialArray.get(y));
}
long startRBTree = System.nanoTime();
MerosC.RBTreeSearch(number);
long elapsedNanoTimeRBTree= System.nanoTime()-startRBTree;
System.out.println("Interpolation Search Finished\n");
sumInterpolation=elapsedNanoTimeRBTree + sumRBTree;
if(elapsedNanoTimeRBTree>maxRBTree){maxRBTree=elapsedNanoTimeRBTree;}
if(elapsedNanoTimeRBTree<minRBTree){minRBTree=elapsedNanoTimeRBTree;}*/
sb.append(elapsedNanoTimeLineral);
sb.append(';');
sb.append(elapsedNanoTimeBinary);
sb.append(';');
sb.append(elapsedNanoTimeInterpolation);
sb.append(';');
//sb.append(elapsedNanoTimeRBTree);
// sb.append(';');
sb.append(number);
sb.append('\n');
}
moLineral = sumLineral/10;
moBinary=sumBinary/10;
moInterpolation=sumInterpolation/10;
//moRBTree=sumRBTree/100;
sb.append(';');
sb.append(';');
sb.append(';');
sb.append('\n');
sb.append("Min Linear");
sb.append(';');
sb.append("Min Binary");
sb.append(';');
sb.append("Min Interpolation");
// sb.append(';');
// sb.append("Min RBTree");
sb.append('\n');
sb.append(minLineral/1000);
sb.append(';');
sb.append(minBinary/1000);
sb.append(';');
sb.append(minInterpolation/1000);
// sb.append(';');
// sb.append(minRBTree);
sb.append('\n');
sb.append("Max Linear");
sb.append(';');
sb.append("Max Binary");
sb.append(';');
sb.append("Max Interpolation");
// sb.append(';');
// sb.append("Max RBTree");
sb.append('\n');
sb.append(maxLineral/1000);
sb.append(';');
sb.append(maxBinary/1000);
sb.append(';');
sb.append(maxInterpolation/1000);
// sb.append(';');
// sb.append(maxRBTree);
sb.append('\n');
sb.append("Mid Linear");
sb.append(';');
sb.append("Mid Binary");
sb.append(';');
sb.append("Mid Interpolation");
sb.append(';');
sb.append("Mid RBTree");
sb.append('\n');
sb.append(moLineral/1000);
sb.append(';');
sb.append(moBinary/1000);
sb.append(';');
sb.append(moInterpolation/1000);
// sb.append(';');
// sb.append(moRBTree);
sb.append('\n');
pw.write(sb.toString());
pw.close();
}catch(FileNotFoundException e){}
//moRBTree=sumInterpolation/100;
System.out.println("Lineral Search");
System.out.println("Μέσος Χρόνος Αναζήτησης : "+moLineral+"");
System.out.println("Ελάχιστος Χρόνος Αναζήτησης : "+minLineral+"");
System.out.println("Μέγιστος Χρόνος Αναζήτησης : "+maxLineral+"");
System.out.println("-----------------------------------");
System.out.println("Binary Search");
System.out.println("Μέσος Χρόνος: "+moBinary);
System.out.println("Ελάχιστος Χρόνος Αναζήτησης : "+minBinary);
System.out.println("Μέγιστος Χρόνος Αναζήτησης : "+maxBinary);
System.out.println("-----------------------------------");
System.out.println("Interpolation Search");
System.out.println("Μέσος Χρόνος: "+moInterpolation);
System.out.println("Ελάχιστος Χρόνος Αναζήτησης : "+minInterpolation);
System.out.println("Μέγιστος Χρόνος Αναζήτησης : "+maxInterpolation);
System.out.println("-----------------------------------");
/*System.out.println("Red-Black Tree Search");
System.out.println("Μέσος Χρόνος: "+moRBTree);
System.out.println("Ελάχιστος Χρόνος Αναζήτησης : "+minRBTree);
System.out.println("Μέγιστος Χρόνος Αναζήτησης : "+maxRBTree);
System.out.println("-----------------------------------");*/
System.out.println("Δημιουργήθηκε αρχείο Excell(csv) με όλους του χρόνους για την κάθε ");
System.out.println("αναζήτηση στον φάκελο του Project!!!");
}
}
| rkapsalis/CEID-projects | Object Oriented Programming/JAVA/MerosD.java |
2,490 | package gr.cti.eslate.agent;
import java.util.ListResourceBundle;
/**
* Agent plugs bundle.
* <P>
*
* @author Giorgos Vasiliou
* @version 1.0.0, 15-May-2000
*/
public class BundlePlugs_el_GR extends ListResourceBundle {
public Object [][] getContents() {
return contents;
}
static final Object[][] contents={
{"host", "Οντότητα"},
{"vectorin", "Κατεύθυνση και ταχύτητα"},
{"vectorout", "Συνισταμένη ταχύτητα"},
{"direction", "Κατεύθυνση"},
{"distance", "Απόσταση"},
{"time", "Χρόνος"},
{"abslatlong", "Απόλυτο Γεωγραφικό Μήκος/Πλάτος"},
{"layerobjectof", "Α/Α κοντινού αντικειμένου του"},
{"nearbyrecord", "Εγγραφή κοντινού αντικειμένου"},
{"clock", "Παλμός χρονιστή"},
{"recordof", "Περιγραφικά δεδομένα κοντινού αντικειμένου του"},
};
}
| vpapakir/myeslate | widgetESlate/src/gr/cti/eslate/agent/BundlePlugs_el_GR.java |
2,491 | package buzzgame;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import static javax.swing.JOptionPane.INFORMATION_MESSAGE;
import javax.swing.Timer;
/**
*
* @author Τιμολέων Λατινόπουλος
* @author Δημήτρης Σκουλής
*/
public class Frame extends JFrame implements KeyListener {
private JFrame frame;
private FlowLayout flow;
private JButton next, button[];
private JLabel text, text2, scoreText, scoreText2, timerText, imageLabel, thermometer1Text, thermometer2Text;
private JTextArea question;
private JTextField score, score2, timerField, thermometer1Field, thermometer2Field;
private JMenuItem instructions, exit, resetHighscores, showHighscores;
private JPanel center, grid, grid2, grid3, borderGrid, top, border, languagePane, enOrGrPane, playerPane;
private ActionListener action;
private ImageIcon image;
private BufferedReader in;
private RoundMake round;
private IOClass io;
private String category;
private Player player1, player2;
private Timer timer;
private int keyID, bet1, bet2, action1, action2, count1, count2;
private int rounds, questions, count, numOfPlayers, thermometer1 = 5, thermometer2 = 5;
private boolean flagPlayer = true, questionsFlag = true, betFlag = true, thermometerFlag = false, player1Answered = false, player2Answered = false, first1 = false, first2 = false, first = true, time1 = false, time2 = false;
private String input;
/**
*
* The empty constructor of the class.
*
* Ιt creates the frame of the game and its properties. It also creates the
* menu which the game has.
*/
public Frame() {
player1 = new Player();
player2 = new Player();
io = new IOClass(player1, player2);
frame = new JFrame();
frame.setTitle("Buzz");
languagePane = new chooseLanguagePane();
//Menu Bar
JMenuBar menubar = new JMenuBar();
frame.setJMenuBar(menubar);
JMenu menu = new JMenu("File");
menubar.add(menu);
instructions = new JMenuItem("Instructions");
menu.add(instructions);
menu.addSeparator();
showHighscores = new JMenuItem("Show highscores");
menu.add(showHighscores);
resetHighscores = new JMenuItem("Reset highscores");
menu.add(resetHighscores);
menu.addSeparator();
exit = new JMenuItem("Exit");
menu.add(exit);
instructions.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
try {
in = new BufferedReader(new FileReader("instructions.txt"));
input = "";
for (String line; (line = in.readLine()) != null;) {
input += line + "\n";
}
JOptionPane.showMessageDialog(frame, input, "Instructions", INFORMATION_MESSAGE);
} catch (IOException e) {
System.out.println("Can't open file");
}
}
});
exit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
resetHighscores.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
int reply = JOptionPane.showConfirmDialog(null, "Would you like to reset the scores?", "Reset scores", JOptionPane.YES_NO_OPTION);
if (reply == JOptionPane.YES_OPTION) {
io.resetScores();
}
}
});
showHighscores.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
try {
in = new BufferedReader(new FileReader("score.txt"));
input = "";
for (String line; (line = in.readLine()) != null;) {
input += line + "\n";
}
JOptionPane.showMessageDialog(frame, input, "Scores", INFORMATION_MESSAGE);
} catch (IOException e) {
System.out.println("Can't open file");
}
}
});
//Setup frame
frame.setResizable(true);
frame.setSize(1050, 450);
frame.setLocationRelativeTo(null);
frame.add(languagePane);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setVisible(true);
//KeyListener
addKeyListener(this);
frame.setFocusable(true);
frame.addKeyListener(this);
}
@Override
public void keyTyped(KeyEvent e) {
//No fuction to this method
}
@Override
public void keyPressed(KeyEvent e) {
keyID = e.getKeyChar();
if (numOfPlayers == 2) {
if (questionsFlag == false) {
playerAction();
} else if (betFlag == false) {
betAction();
}
}
}
@Override
public void keyReleased(KeyEvent e) {
//No fuction to this method
}
/**
*
* During multiplayer game, it takes the bets of the players during the bet
* round from the keyboard.
*/
public void betAction() {
if (keyID >= 49 && keyID <= 52 && player1Answered == false) {
action1 = keyID - 48;
player1Answered = true;
} else if (keyID >= 54 && keyID <= 57 && player2Answered == false) {
action2 = keyID - 53;
player2Answered = true;
}
if (player1Answered == true && player2Answered == true) {
if (action1 == 1) {
bet1 = 250;
} else if (action1 == 2) {
bet1 = 500;
} else if (action1 == 3) {
bet1 = 750;
} else if (action1 == 4) {
bet1 = 1000;
}
if (action2 == 1) {
bet2 = 250;
} else if (action2 == 2) {
bet2 = 500;
} else if (action2 == 3) {
bet2 = 750;
} else if (action2 == 4) {
bet2 = 1000;
}
next.setVisible(true);
betFlag = false;
action1 = -1;
action2 = -1;
player1Answered = false;
player2Answered = false;
}
}
/**
*
* During multiplayer game, it takes the choices of the players and
* accordingly adds or subtracts points from each one depending on the type
* of round that is played.
*/
public void playerAction() {
if (keyID >= 49 && keyID <= 52 && player1Answered == false) {
action1 = keyID - 48;
player1Answered = true;
if (first2 == false && round.checkChoice(action1)) {
first1 = true;
}
} else if (keyID >= 54 && keyID <= 57 && player2Answered == false) {
action2 = keyID - 53;
player2Answered = true;
if (first1 == false && round.checkChoice(action2)) {
first2 = true;
}
}
switch (round.getRoundNum()) {
case 0:
if (player1Answered == true && player2Answered == true) {
if (round.checkChoice(action1) == true) {
player1.addPoints(1000);
}
if (round.checkChoice(action2) == true) {
player2.addPoints(1000);
}
}
break;
case 1:
if (player1Answered == true && player2Answered == true) {
if (round.checkChoice(action1) == true) {
player1.addPoints(bet1);
} else if (round.checkChoice(action1) == false) {
player1.subPoints(bet1);
}
if (round.checkChoice(action2) == true) {
player2.addPoints(bet2);
} else if (round.checkChoice(action2) == false) {
player2.subPoints(bet2);
}
}
break;
case 2:
if (round.checkChoice(action1) == true) {
count1 = count;
}
if (round.checkChoice(action2) == true) {
count2 = count;
}
if (round.checkChoice(action1) == true && time1 == false) {
player1.addPoints((int) (count1 * 0.2));
time1 = true;
}
if (round.checkChoice(action2) == true && time2 == false) {
player2.addPoints((int) (count2 * 0.2));
time2 = true;
}
if (player1Answered == true && player2Answered == true) {
time1 = false;
time2 = false;
timer.stop();
}
break;
case 3:
if (player1Answered == true && player2Answered == true) {
if (round.checkChoice(action1) == true) {
if (first1 == true) {
player1.addPoints(1000);
} else {
player1.addPoints(500);
}
}
if (round.checkChoice(action2) == true) {
if (first2 == true) {
player2.addPoints(1000);
} else {
player2.addPoints(500);
}
}
}
break;
case 4:
if (player1Answered == true && player2Answered == true) {
if (round.checkChoice(action1) == true) {
thermometer1--;
}
if (round.checkChoice(action2) == true) {
thermometer2--;
}
}
break;
}
if (player1Answered == true && player2Answered == true) {
endOfQuestion();
}
}
/**
*
* During multiplayer game, it changes the color of the answers and sets all
* the textFields to their updated values. It also adds points at the end of
* the thermometer round and resets some values that are used for each
* round.
*/
public void endOfQuestion() {
if (action1 != 0 && !round.checkChoice(action1)) {
button[action1 - 1].setBackground(Color.red);
}
if (action2 != 0 && !round.checkChoice(action2)) {
button[action2 - 1].setBackground(Color.red);
}
for (int i = 1; i <= 4; i++) {
if (round.checkChoice(i)) {
button[i - 1].setBackground(Color.green);
}
}
if (thermometerFlag == true) {
thermometer1Field.setText("" + thermometer1);
thermometer2Field.setText("" + thermometer2);
thermometerFlag = false;
}
next.setVisible(true);
for (int i = 0; i < 4; i++) {
button[i].setEnabled(false);
}
if (round.getRoundNum() != 4) {
if (questions == 4) {
rounds++;
questions = -1;
}
} else {
if (thermometer1 == 0 || thermometer2 == 0) {
rounds++;
questions = -1;
if (thermometer1 == thermometer2) {
if (first1 == true) {
player1.addPoints(5000);
} else {
player2.addPoints(5000);
}
} else {
if (thermometer1 == 0) {
player1.addPoints(5000);
} else if (thermometer2 == 0) {
player2.addPoints(5000);
}
}
}
}
if (rounds == 5) {
io.writeScores(numOfPlayers);
}
score.setText("" + player1.getPoints());
score2.setText("" + player2.getPoints());
time1 = false;
time2 = false;
questionsFlag = true;
action1 = 0;
action2 = 0;
player1Answered = false;
player2Answered = false;
first1 = false;
first2 = false;
}
/**
*
* Contains the part of the game in which the user selects the language.
*/
public class chooseLanguagePane extends JPanel {
public chooseLanguagePane() {
//Main Layout
flow = new FlowLayout(FlowLayout.CENTER, 10, 50);//flow layout
//Text Label
text = new JLabel("Choose language / Επέλεξε γλώσσα:");
text.setFont(new java.awt.Font("Tahoma", 0, 18));
text.setHorizontalAlignment(SwingConstants.CENTER);
//Language Panel
center = new JPanel();
center.setLayout(flow);
//Button Panel
grid = new JPanel();
grid.setLayout(new GridLayout(1, 2, 30, 0));//Grid Layout
grid2 = new JPanel();
grid2.setLayout(new GridLayout(2, 1, 30, 50));//Grid Layout
//New Buttons
button = new JButton[2];
button[0] = new JButton("English");
button[0].setActionCommand("button1Command");
button[1] = new JButton("Ελληνικά");
button[1].setActionCommand("button2Command");
//Action Listener
action = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String action = e.getActionCommand();
if (action.equals("button1Command")) {
enOrGrPane = new languagePane(true);
} else if (action.equals("button2Command")) {
enOrGrPane = new languagePane(false);
}
frame.remove(languagePane);
frame.add(enOrGrPane);
frame.revalidate();
frame.repaint();
}
};
for (int i = 0; i < 2; i++) {
button[i].addActionListener(action);
grid.add(button[i]);
}
//Add to Panel
grid2.add(text);
grid2.add(grid);
center.add(grid2);
this.add(center);
}
}
/**
*
* Contains the part of the game in which the game mode is selected.
*/
public class languagePane extends JPanel {
public languagePane(final boolean language) {
//Text Label
if (language == true) {
text.setText(" Choose the number of players: ");
} else {
text.setText("Διάλεξε τον αριθμό των παικτών:");
}
this.add(text);
center.removeAll();
grid.removeAll();
grid2.removeAll();
//New Buttons
if (language == true) {
button[0] = new JButton("1 player");
button[1] = new JButton("2 players");
} else {
button[0] = new JButton("1 παίκτης");
button[1] = new JButton("2 παίκτες");
}
button[0].setActionCommand("button1Command");
button[1].setActionCommand("button2Command");
//Action Listener
action = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String action = e.getActionCommand();
if (action.equals("button1Command")) {
playerPane = new playerPanel(language, true, 0, 0, 1);
frame.remove(enOrGrPane);
frame.add(playerPane);
frame.revalidate();
frame.repaint();
} else if (action.equals("button2Command")) {
playerPane = new playerPanel(language, true, 0, 0, 2);
frame.remove(enOrGrPane);
frame.add(playerPane);
frame.revalidate();
frame.repaint();
}
}
};
for (int i = 0; i < 2; i++) {
button[i].addActionListener(action);
grid.add(button[i]);
}
//Add to Panel
grid2.add(text);
grid2.add(grid);
center.add(grid2);
this.add(center);
}
}
/**
*
* It contains the main panel of the game, the panel that contains the
* questions and the possible answers of them.
*/
public class playerPanel extends JPanel {
private boolean lang, flag;
/**
*
* It is the main method of the whole program. It has all the
* information about the program such as the questions that have been
* used, the rounds that have been played, etc. It gets the type of
* round and calls its method to be set the properties of the panel of
* this round.
*
* @param aLang symbolizes the language that the user has selected if
* true the language is english and if false greek
* @param aFlag symbolizes if it is the first question of the game
* @param aRounds symbolizes how many rounds have been played
* @param aQuestions contains the number of questions that have been
* played in this round
* @param aNumOfPlayers symbolizes the number of players
*/
public playerPanel(boolean aLang, boolean aFlag, int aRounds, int aQuestions, int aNumOfPlayers) {
//local variables
lang = aLang;
flag = aFlag;
rounds = aRounds;
questions = aQuestions;
numOfPlayers = aNumOfPlayers;
border = new JPanel();
borderGrid = new JPanel();
borderGrid.setLayout(new GridLayout(2, 1, 10, 10));
grid2 = new JPanel();
grid2.setLayout(new GridLayout(numOfPlayers, 2, 10, 10));//Grid Layout
score = new JTextField("" + player1.getPoints());
score.setEnabled(false);
score.setFont(new java.awt.Font("Tahoma", 0, 16));
if (lang == true) {
scoreText = new JLabel("Score 1:");
} else {
scoreText = new JLabel("Σκορ 1:");
}
scoreText.setFont(new java.awt.Font("Tahoma", 0, 16));
if (numOfPlayers == 2) {
score2 = new JTextField("" + player2.getPoints());
score2.setEnabled(false);
score2.setFont(new java.awt.Font("Tahoma", 0, 16));
if (lang == true) {
scoreText2 = new JLabel("Score 2:");
} else {
scoreText2 = new JLabel("Σκορ 2:");
}
scoreText2.setFont(new java.awt.Font("Tahoma", 0, 16));
}
grid2.add(scoreText);
grid2.add(score);
if (numOfPlayers == 2) {
grid2.add(scoreText2);
grid2.add(score2);
}
if (flag) {
if (numOfPlayers == 1) {
round = new RoundMake(lang, 3);
} else if (numOfPlayers == 2) {
round = new RoundMake(lang, 5);
}
flag = false;
}
round.startRound(questions);
//Main Panel
top = new JPanel();
top.setLayout(new GridLayout(4, 1, 30, 20));
//Round Type
switch (round.getRoundNum()) {
case 0:
makeCorrectChoicePanel();
break;
case 1:
makeBetPanel();
break;
case 2:
makeTimerPanel();
break;
case 3:
makeQuickAnswer();
break;
case 4:
makeΤhermometer();
break;
}
}
/**
*
* Creates the correct choice round.
*/
public void makeCorrectChoicePanel() {
if (lang == true) {
text.setText("Round " + (rounds + 1) + ": Correct Answer");
} else {
text.setText("Γύρος " + (rounds + 1) + ": Σωστή Απάντηση");
}
top.add(text);
border.add(top, BorderLayout.CENTER);
makeQuestionsAndAnswersPanel();
}
/**
*
* Creates the bet panel and the bet round.
*/
public void makeBetPanel() {
betFlag = false;
if (lang == true) {
text.setText("Round " + (rounds + 1) + ": Bet");
} else {
text.setText("Γύρος " + (rounds + 1) + ": Ποντάρισμα");
}
top.add(text);
//Button Panel
grid = new JPanel();
grid.setLayout(new GridLayout(2, 2, 30, 20));//Grid Layout
switch (round.getCategory()) {
case 0:
if (lang == true) {
category = "Sports";
} else {
category = "Αθλητισμός";
}
break;
case 1:
if (lang == true) {
category = "Geography";
} else {
category = "Γεωγραφία";
}
break;
case 2:
if (lang == true) {
category = "Science";
} else {
category = "Επιστήμη";
}
break;
case 3:
if (lang == true) {
category = "Movies";
} else {
category = "Ταινίες";
}
break;
case 4:
if (lang == true) {
category = "Arts";
} else {
category = "Τέχνη";
}
break;
}
if (lang == true) {
text2 = new JLabel("The Category is " + category + ". How much do you bet?");
} else {
text2 = new JLabel("Η κατηγορία είναι " + category + ". Πόσους πόντους θες να ποντάρεις;");
}
text2.setFont(new java.awt.Font("Tahoma", 0, 16));
text2.setHorizontalAlignment(SwingConstants.CENTER);
top.add(text2);
button = new JButton[4];
button[0] = new JButton("250");
button[1] = new JButton("500");
button[2] = new JButton("750");
button[3] = new JButton("1000");
for (int i = 0; i < 4; i++) {
button[i].setActionCommand("" + (i + 1));
}
action = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int action = Integer.parseInt(e.getActionCommand());
if (action == 1) {
bet1 = 250;
} else if (action == 2) {
bet1 = 500;
} else if (action == 3) {
bet1 = 750;
} else if (action == 4) {
bet1 = 1000;
}
if (numOfPlayers == 1) {
grid.removeAll();
grid.revalidate();
grid.repaint();
top.remove(text2);
top.remove(grid);
top.remove(next);
top.revalidate();
top.repaint();
makeQuestionsAndAnswersPanel();
} else {
next.setVisible(true);
}
}
};
for (int i = 0; i < 4; i++) {
if (numOfPlayers == 1) {
button[i].addActionListener(action);
}
grid.add(button[i]);
}
if (lang == true) {
next = new JButton("Go to question");
} else {
next = new JButton("Πήγαινε στην Ερώτηση");
}
next.setVisible(false);
next.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
grid.removeAll();
grid.revalidate();
grid.repaint();
top.remove(text2);
top.remove(grid);
top.remove(next);
top.revalidate();
top.repaint();
makeQuestionsAndAnswersPanel();
}
});
//Add to panel
top.add(grid);
top.add(next);
border.add(top, BorderLayout.CENTER);
this.add(border);
}
/**
*
* Creates the timer that is going to be used in the timer round and
* sets the properties for the panel.
*/
public void makeTimerPanel() {
timerField = new JTextField();
timerField.setText("5000");
count = 5000;
timer = new Timer(100, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (count <= 0) {
((Timer) e.getSource()).stop();
next.setVisible(true);
for (int i = 0; i < 4; i++) {
button[i].setEnabled(false);
}
if (numOfPlayers == 2) {
endOfQuestion();
} else {
if (questions == 4) {
rounds++;
questions = -1;
}
if (rounds == 5) {
io.writeScores(numOfPlayers);
}
}
} else {
timerField.setText(Integer.toString(count));
count -= 100;
}
timerField.setText(Integer.toString(count));
}
});
timer.start();
if (lang == true) {
text.setText("Round " + (rounds + 1) + ": Timer");
} else {
text.setText("Γύρος " + (rounds + 1) + ": Χρονόμετρο");
}
top.add(text);
grid3 = new JPanel();
grid3.setLayout(new GridLayout(1, 2, 10, 10));
timerField.setEnabled(false);
timerField.setFont(new java.awt.Font("Tahoma", 0, 16));
if (lang == true) {
timerText = new JLabel("Time:");
} else {
timerText = new JLabel("Χρόνος:");
}
timerText.setFont(new java.awt.Font("Tahoma", 0, 16));
grid3.add(timerText);
grid3.add(timerField);
borderGrid.add(grid3);
border.add(borderGrid, BorderLayout.EAST);
makeQuestionsAndAnswersPanel();
}
/**
*
* Creates the quick answer round.
*/
public void makeQuickAnswer() {
if (lang == true) {
text.setText("Round " + (rounds + 1) + ": Quick answer");
} else {
text.setText("Γύρος " + (rounds + 1) + ": Γρήγορη απάντηση");
}
top.add(text);
makeQuestionsAndAnswersPanel();
}
/**
*
* Creates the thermometer round.
*/
public void makeΤhermometer() {
thermometerFlag = true;
if (lang == true) {
text.setText("Round " + (rounds + 1) + ": Thermometer");
} else {
text.setText("Γύρος " + (rounds + 1) + ": Θερμόμετρο");
}
top.add(text);
grid3 = new JPanel();
grid3.setLayout(new GridLayout(2, 2, 10, 10));
if (first == true) {
thermometer1Field = new JTextField();
thermometer1Field.setText("5");
thermometer2Field = new JTextField();
thermometer2Field.setText("5");
first = false;
}
thermometer1Field.setEnabled(false);
thermometer1Field.setFont(new java.awt.Font("Tahoma", 0, 16));
if (lang == true) {
thermometer1Text = new JLabel("Thermometer 1:");
} else {
thermometer1Text = new JLabel("Θερμόμετρο 1:");
}
thermometer1Text.setFont(new java.awt.Font("Tahoma", 0, 16));
grid3.add(thermometer1Text);
grid3.add(thermometer1Field);
thermometer2Field.setEnabled(false);
thermometer2Field.setFont(new java.awt.Font("Tahoma", 0, 16));
if (lang == true) {
thermometer2Text = new JLabel("Thermometer 2:");
} else {
thermometer2Text = new JLabel("Θερμόμετρο 2:");
}
thermometer2Text.setFont(new java.awt.Font("Tahoma", 0, 16));
grid3.add(thermometer2Text);
grid3.add(thermometer2Field);
borderGrid.add(grid3);
border.add(borderGrid, BorderLayout.EAST);
makeQuestionsAndAnswersPanel();
}
/**
*
* This method is called during each round during single player game. It
* sets the panel with the question and the answers, gets the choice of
* the player and then it decides if the player wins or loses any
* points. When it is done, it calls the constructor for a new question
* or a new round be made.
*/
public void makeQuestionsAndAnswersPanel() {
//Button Panel
grid = new JPanel();
grid.setLayout(new GridLayout(2, 2, 30, 10));//Grid Layout
questionsFlag = false;
//Question TextArea
question = new JTextArea(round.getQuestionsAndAnswers(0));
question.setFont(new java.awt.Font("Tahoma", 0, 14));
question.setEditable(false);
question.setEnabled(false);
question.setLineWrap(true);
question.setWrapStyleWord(true);
question.setBackground(Color.black);
question.setAutoscrolls(true);
top.add(question);
button = new JButton[4];
//New buttons
for (int i = 0; i < 4; i++) {
button[i] = new JButton(round.getQuestionsAndAnswers(i + 1));
button[i].setActionCommand("" + (i + 1));
}
if ((rounds >= 4 && questions == 4 && thermometerFlag == false) || (rounds >= 5 && questions == -1 && thermometerFlag == false)) {
if (lang == true) {
next = new JButton("End quiz");
} else {
next = new JButton("Τέλος παιχνιδιού");
}
} else {
if (lang == true) {
next = new JButton("Next Question");
} else {
next = new JButton("Επόμενη Ερώτηση");
}
}
next.setVisible(false);
next.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (rounds != 5) {
frame.remove(playerPane);
playerPane = new playerPanel(lang, flag, rounds, ++questions, numOfPlayers);
frame.add(playerPane);
frame.revalidate();
frame.repaint();
} else {
System.exit(0);
}
}
});
//Action Listener
action = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int action = Integer.parseInt(e.getActionCommand());
if (!round.checkChoice(action)) {
button[action - 1].setBackground(Color.red);
}
for (int i = 1; i <= 4; i++) {
if (round.checkChoice(i)) {
button[i - 1].setBackground(Color.green);
}
}
switch (round.getRoundNum()) {
case 0:
if (round.checkChoice(action) == true) {
player1.addPoints(1000);
}
break;
case 1:
if (round.checkChoice(action) == true) {
player1.addPoints(bet1);
} else {
player1.subPoints(bet1);
}
break;
case 2:
timer.stop();
if (round.checkChoice(action) == true) {
player1.addPoints((int) (count * 0.2));
}
break;
}
score.setText("" + player1.getPoints());
next.setVisible(true);
for (int i = 0; i < 4; i++) {
button[i].setEnabled(false);
}
if (questions == 4) {
rounds++;
questions = -1;
}
if (rounds == 5) {
io.writeScores(numOfPlayers);
}
}
};
for (int i = 0; i < 4; i++) {
if (numOfPlayers == 1) {
button[i].addActionListener(action);
}
grid.add(button[i]);
}
//Add to panel
top.add(grid);
top.add(next);
border.add(top, BorderLayout.CENTER);
borderGrid.add(grid2);
border.add(borderGrid, BorderLayout.EAST);
if (round.getQuestionsAndAnswers(5) != null) {
image = new ImageIcon(round.getQuestionsAndAnswers(5));
imageLabel = new JLabel("", image, JLabel.CENTER);
border.add(imageLabel, BorderLayout.EAST);
}
this.add(border);
}
}
}
| TimoleonLatinopoulos/BuzzGame | src/buzzgame/Frame.java |
2,493 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package telikh;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.FileOutputStream;
import java.nio.charset.StandardCharsets;
/**
*
* @author sun
*/
public class GUI extends Frame implements ActionListener, WindowListener{
private Label fNameLb;
private Label lNameLb;
private Label salaryLb;
private Label spLb;
private Label yrLb;
private Label minHLb;
private Button pBtn;
private Button nBtn;
private TextField overtimeTF;
private ArrayList<Employee> employees;
private String fileName;
private int empIndex;
public void firstEmployee () {
Employee employee = employees.get(empIndex);
fNameLb = new Label("Όνομα: " + employee.fName);
lNameLb = new Label("Επίθετο: " + employee.lName);
salaryLb = new Label("Βασικός μισθός: " + employee.salary);
spLb = new Label("Ειδικότητα: " + employee.specialty);
yrLb = new Label("Χρόνος πρόσληψης: " + employee.year);
minHLb = new Label("Μηνιαίο ωράριο: " + employee.minMonthH);
nBtn = new Button("Επόμενος");
pBtn = new Button("Προηγούμενος");
overtimeTF = new TextField("Υπερωρίες");
add(fNameLb);
add(lNameLb);
add(salaryLb);
add(spLb);
add(yrLb);
add(minHLb);
add(nBtn);
add(pBtn);
add(overtimeTF);
}
public void showEmployee(){
Employee employee = employees.get(empIndex);
this.fNameLb.setText("Όνομα: " + employee.fName);
this.lNameLb.setText("Επίθετο: " + employee.lName);
this.salaryLb.setText("Βασικός μισθός: " + employee.salary);
this.spLb.setText("Ειδικότητα: " + employee.specialty);
this.yrLb.setText("Έτος πρόσληψης: " + employee.year);
this.minHLb.setText("Μηνιαίο ωράριο: " + employee.minMonthH);
if (employee.exHours == 0)
this.overtimeTF.setText("Υπερωρίες");
else
this.overtimeTF.setText("" + employee.exHours);
}
public GUI(ArrayList<Employee> employees, String fileName) {
this.fileName = fileName;
this.employees = employees;
setLayout(new FlowLayout());
setTitle("Εξέταση Java");
setSize(350,160);
addWindowListener(this);
firstEmployee();
nBtn.addActionListener(this);
pBtn.addActionListener(this);
setVisible(true);
}
public void windowClosing(WindowEvent e) {
try {
FileOutputStream fos = new FileOutputStream("C:\\Users\\sun\\Desktop\\exetashJavaOut.txt");
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos, StandardCharsets.UTF_8));
for (int i = 0; i < employees.size(); i++) {
bw.write(employees.get(i).toString());
bw.newLine();
}
bw.close();
}
catch (java.io.FileNotFoundException exc) {
System.out.println("Δεν βρέθηκε το αρχείο που ζητήθηκε.");
}
catch (java.io.IOException exc) {
System.out.println("Δεν μπόρεσε να διαβαστεί το αρχείο.");
}
System.exit(0);
}
public void windowOpened(WindowEvent e){}
public void windowClosed(WindowEvent e){}
public void windowDeactivated(WindowEvent e){}
public void windowActivated(WindowEvent e){}
public void windowIconified(WindowEvent e){}
public void windowDeiconified(WindowEvent e){}
@Override
public void actionPerformed(ActionEvent evt) {
if (evt.getActionCommand().equals("Επόμενος")) {
Employee employee = employees.get(empIndex);
try {
employee.exHours = Integer.parseInt(overtimeTF.getText());
employee.getSalary();
}
catch (Exception ex) {
System.out.println("Λάθος!");
}
this.empIndex++;
if (this.empIndex == employees.size()) this.empIndex = 0;
showEmployee();
}
else {
Employee employee = employees.get(empIndex);
try {
employee.getSalary();
employee.exHours = Integer.parseInt(overtimeTF.getText());
}
catch (Exception ex) {
System.out.println("Λάθος!");
}
this.empIndex--;
if (this.empIndex == -1) this.empIndex = this.employees.size() -1;
showEmployee();
}
}
}
| DimosthenisK/Java_Excercise_1 | GUI.java |
2,494 | package game;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
/**
* <p>Παράθυρο όπου τρέχει ο λαβύρινθος.</p>
*
* @author Team Hack-You
* @version 1.0
*/
public final class LabyrinthFrame implements ActionListener {
private JFrame frame;
private JProgressBar bar;
private final GamePanel gamePanel = new GamePanel(this);
private final JButton start = new JButton("start");
//Μεταβλητές χρήσιμες για τη λειτουργία του progressBar
private boolean go = true; // Αν συνεχίζει το progressBar ή βρίσκεται σε pause
private boolean hasStarted = false; // Αν έχει αρχίσει το παιχνίδι
//Μεταβλητές για πόσο χρόνο ο παίκτης θα κερδίζει χάνει ανάλογα με την απάντησή του στις ερωτήσεις
static int for_correct;
static int for_wrong;
//Πόσο χρόνο σε seconds θα έχει ο παίκτης
private static int time;
// Αν ο παίκτης έχει χάσει ή όχι
private boolean hasLost = false;
//Δευτερόλεπτα που απομένουν στον παίκτη για να δραπετεύσει από τον λαβύρινθο
private int counter;
//Εάν έχει προηγηθεί restart
private static boolean restartStatus = false;
/**
* <p>Getter for the field <code>restartStatus</code>.</p>
*
* @return a boolean
*/
public static boolean getRestartStatus() {
return restartStatus;
}
/**
* <p>Setter for the field <code>restartStatus</code>.</p>
*
* @param restartStatus a boolean
*/
public static void setRestartStatus(boolean restartStatus) {
LabyrinthFrame.restartStatus = restartStatus;
}
/**
* <p>Getter for the field <code>hasLost</code>.</p>
*
* @return a boolean
*/
public boolean getHasLost() {
return hasLost;
}
/**
* <p>Getter for the field <code>hasStarted</code>.</p>
*
* @return a boolean
*/
public boolean getHasStarted() {
return hasStarted;
}
/**
* <p>Αρχικοποίηση μεταβλητών για χρόνο παιχνιδιού <br>
* και win/loss χρόνου ανάλογα με την απάντηση στις ερωτήσεις</p>
*/
static void setLabyrinth() {
switch (Levels.getDifficulty()) {
case "Easy":
time = 50;
for_correct = 3;
for_wrong = -5;
break;
case "Medium":
time = 65;
for_correct = 5;
for_wrong = -5;
break;
default:
time = 75;
for_correct = 5;
for_wrong = -5;
break;
}
}
/**
* <p>Δημιουργία frame</p>
*/
private void createFrame() {
frame = new JFrame();
FrameSetter.setFrame(frame, "Labyrinth", 780, 660);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
}
/**
* <p>Δημιουργία progressBar</p>
*/
private void createBar() {
bar = new JProgressBar(0, time);
bar.setValue(time);
bar.setStringPainted(true);
//Θέτω το μέγεθος της progressBar
bar.setPreferredSize(new Dimension(600, 50));
bar.setFont(new Font("Arial", Font.BOLD, 25));
bar.setForeground(Color.red);
bar.setBackground(Color.black);
bar.setVisible(false);
}
/**
* <p>Constructor for LabyrinthFrame.</p>
*/
public LabyrinthFrame() {
restartStatus = false;
if (Menu.checkMusic()) {
Menu.playMusic();
}
createFrame();
createBar();
/*Για να μην υπάρχει καμία περίπτωση να κολλήσει
η κίνηση του παίκτη σε περίπτωση μετακίνησης του παραθύρου*/
frame.addComponentListener(new ComponentAdapter() {
@Override
public void componentMoved(ComponentEvent e) {
super.componentMoved(e);
gamePanel.playerStabilize();
}
});
setButton(start);
start.setBackground(Color.green);
start.setFont(new Font("Calibri", Font.ITALIC, 25));
frame.add(bar, BorderLayout.NORTH);
frame.add(start, BorderLayout.SOUTH);
frame.getRootPane().setDefaultButton(start);
frame.add(gamePanel, BorderLayout.CENTER);
gamePanel.setupGame();
}
/**
* <p>Λειτουργία του progressBar.</p>
*
* @param flg : ο χρόνος που θα έχει ο παίκτης
*/
private void fill(int flg) {
counter = flg;
// counter >= 0 : Για να γίνεται το activation του quiz και με 1 second left
while (counter >= 0) {
if (!go) {
go = true;
return;
}
if (counter == 0) {
break;
}
bar.setString(String.format("%d seconds left", counter));
bar.setValue(counter);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
counter--;
}
bar.setValue(0);
hasLost = true;
bar.setString("Game Over");
}
private void setButton(JButton button) {
ButtonSetter.setButton(button, 250, 500, 100, 50, new Font("Calibri", Font.ITALIC, 20), this);
button.setIcon(null);
}
/**
* <p>Ανανέωσης progressBar</p>
*
* @param flg : ο χρόνος που προσθαφαιρείται από το χρόνο που απομένει
*/
void updateBar(int flg) {
int new_time = Math.min(bar.getValue() + flg, time);
//Thread το οποίο τρέχει τη "φόρτωση" του εναπομένοντος χρόνου του παίκτη
Thread fill_bar = new Thread(() -> fill(new_time));
fill_bar.start();
}
/**
* <p>Κλείσιμο παραθύρου παιχνιδιού (διακοπή παιχνιδιού)</p>
*/
void closeFrame() {
//SOS! CRUCIAL for thread safety
gamePanel.terminate();
frame.dispose();
}
/**
* <p>Τερματισμός παιχνιδιού</p>
*
* @param hasWon : true σε περίπτωση νίκης, false σε περίπτωση αποτυχίας
*/
void closeFrame(boolean hasWon) {
hasStarted = false;
if (hasWon) {
stopBar();
SwingUtilities.invokeLater(() -> new WinFrame(counter));
} else {
SwingUtilities.invokeLater(DeathFrame::new);
}
gamePanel.terminate();
frame.dispose();
}
/**
* <p>Παύση progressBar</p>
*/
void stopBar() {
go = false;
}
/**
* {@inheritDoc}
*/
@Override
public void actionPerformed(ActionEvent e) {
ButtonSetter.playSE();
if (e.getSource() == start) {
//Εμφάνιση progressBar και έναρξη countdown
bar.setVisible(true);
Thread fill_bar = new Thread(() -> fill(time));
fill_bar.start();
start.setEnabled(false);
hasStarted = true;
start.setVisible(false);
//Για να μπορεί ο παίκτης να αρχίσει να κινείται
gamePanel.setGameState(GamePanel.playState);
}
}
}
| geoartop/Hack-You | Maven/src/main/java/game/LabyrinthFrame.java |
2,496 | /*
Ergasia Diktya 2
Java DatagramSocket Programming
Onoma Foithth: Mpekiaris Theofanis AEM:8200
Etos: 2018
*/
package userApplication;
import java.io.*;
import java.net.*;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import java.lang.System;
public class userApplication {
public static void main(String[] args) throws IOException{
//Ports και κωδικοί απο την ιθάκη
int clientPort = 48021;
int serverPort = 38021;
int ithakiCopterServerPort = 38048;
int OBDserverPort = 29078 ;
String echoRequestCode = "E1825";
String imageRequestCode = "M9578";
String soundRequestCode = "A6372";
//----- Echo----//
echoFunction(echoRequestCode,serverPort,clientPort); //Πακέτα που έρχονται με κάποια καθυστέρηση
echoFunction("E0000T00",serverPort,clientPort); //Πακέτα χωρίς καθυστέρηση
//-----Image----//
String iRCode_PTZ = imageRequestCode + "CAM=PTZUDP=1024";
String iRCode_FIX = imageRequestCode + "CAM=FIXUDP=1024";
imageFunction(8200,iRCode_FIX,serverPort,clientPort); //Default camera CAM=FIX
imageFunction(8200,iRCode_PTZ+"DIR=C",serverPort,clientPort); //Camera CAM=PTZ center
imageFunction(8200,iRCode_PTZ+"DIR=U",serverPort,clientPort); //Camera CAM=PTZ up
imageFunction(8200,iRCode_PTZ+"DIR=C",serverPort,clientPort); //Camera CAM=PTZ center
imageFunction(8200,iRCode_PTZ+"DIR=D",serverPort,clientPort); //Camera CAM=PTZ down
imageFunction(8200,iRCode_PTZ+"DIR=C",serverPort,clientPort); //Camera CAM=PTZ center
imageFunction(8200,iRCode_PTZ+"DIR=L",serverPort,clientPort); //Camera CAM=PTZ left
imageFunction(8200,iRCode_PTZ+"DIR=C",serverPort,clientPort); //Camera CAM=PTZ center
imageFunction(8200,iRCode_PTZ+"DIR=R",serverPort,clientPort); //Camera CAM=PTZ right
//----Sound----//
int numOfSoundPackets = 100; //Αριθμός μουσικών πακέτων
boolean AQ_DPCM = true; //Επιλογή κωδικοποίησης AQ_DPCM ή DPCM
int Qbits = 8; //Αριθμός bit κβαντιστή για DPCM
String sRCodeΤ_DPCM = soundRequestCode + "T"+Integer.toString(numOfSoundPackets); //Γεννήτρια Συχνοτήτων
String sRCodeΤ_AQ_DPCM = soundRequestCode +"AQ" + "T"+Integer.toString(numOfSoundPackets); //Γεννήτρια Συχνοτήτων
String sRCodeF1_AQ_DPCM = soundRequestCode +"AQ" +"L30"+ "F"+Integer.toString(numOfSoundPackets); //Mουσικό κομμάτι1(audio clip1)
String sRCodeF2_AQ_DPCM = soundRequestCode +"AQ" +"L36"+"F"+Integer.toString(numOfSoundPackets); //Mουσικό κομμάτι2(audio clip2)
soundDPCM_OR_AQDPCM(sRCodeΤ_DPCM,serverPort,clientPort,numOfSoundPackets,!AQ_DPCM,Qbits ); //DPCM κωδικοποίηση,από γεννήτρια συχν.
soundDPCM_OR_AQDPCM(sRCodeΤ_AQ_DPCM,serverPort,clientPort,numOfSoundPackets,AQ_DPCM,Qbits ); //AQ_DPCM κωδικοποίηση,από γεννήτρια συχν.
soundDPCM_OR_AQDPCM(sRCodeF1_AQ_DPCM,serverPort,clientPort,numOfSoundPackets,AQ_DPCM,Qbits ); //AQ_DPCM κωδικοποίηση,μουσικό κομμάτι1(audio clip1)
soundDPCM_OR_AQDPCM(sRCodeF2_AQ_DPCM,serverPort,clientPort,numOfSoundPackets,AQ_DPCM,Qbits ); //AQ_DPCM κωδικοποίηση,μουσικό κομμάτι2(audio clip2)
//----IthakiCopter----//
int flightLevel_1 = 170; //Επιθυμητό ύψος πτήσης του IthakiCopter
int flightLevel_2 = 200; //Επιθυμητό ύψος πτήσης του IthakiCopter
ithakicopter(ithakiCopterServerPort,flightLevel_1);
try{TimeUnit.SECONDS.sleep(20);}catch(Exception x) { System.out.println(x);}
ithakicopter(ithakiCopterServerPort,flightLevel_2);
//----OBD-----//
OBDfunction(OBDserverPort);
//
}//telos main
static public void clientRequestDatagram(String requestCode,int serverPort) throws IOException{
//Request προς τον server
byte[] txbuffer = requestCode.getBytes();
//Δημιουργία socket για την αποστολή πακέτων προς τον server
DatagramSocket s = new DatagramSocket();
byte[] hostIP = { (byte)155,(byte)207,(byte)18,(byte)208 };
InetAddress hostAddress = InetAddress.getByAddress(hostIP);
DatagramPacket p = new DatagramPacket(txbuffer,txbuffer.length, hostAddress,serverPort);
try {
s.send(p);
s.close();
} catch (IOException x) {System.out.println(x);}
}
static public DatagramPacket serverResponseDatagramPacket(int clientPort) throws IOException{
//Δημιουργεία socket για την παραλαβή των πακέτων απο τον εικονικό server της ιθάκης
DatagramSocket r = new DatagramSocket(clientPort);
r.setSoTimeout(10000);
byte[] rxbuffer = new byte[2048];
DatagramPacket packet = new DatagramPacket(rxbuffer,rxbuffer.length);
try {
r.receive(packet);
} catch (Exception x) {
System.out.println(x);
}
r.close();
return packet;
}
static public void echoFunction(String requestCode,int serverPort,int clientPort) throws IOException{
File echoFileName = new File("echoFile_" + requestCode + ".txt");
FileOutputStream echoFile = new FileOutputStream(echoFileName);
File echoThroughput8FileName = new File("echoThroughput8File_" + requestCode + ".txt");
FileOutputStream echoThroughput8File = new FileOutputStream(echoThroughput8FileName);
File echoThroughput16FileName = new File("echoThroughput16File_" + requestCode + ".txt");
FileOutputStream echoThroughput16File = new FileOutputStream(echoThroughput16FileName);
File echoThroughput32FileName = new File("echoThroughput32File_" + requestCode + ".txt");
FileOutputStream echoThroughput32File = new FileOutputStream(echoThroughput32FileName);
try { //Perigrafh periexomenou arxeiwn
echoFile.write(("Mhnuma kai xronos ka8usterhshs se millis").getBytes());
echoFile.write((char) 13); //newline
echoThroughput8File.write(("Ari8mos paketwn ana 8sec kai h ru8mapososh pou prokuptei").getBytes());
echoThroughput8File.write((char) 13); //newline
echoThroughput16File.write(("Ari8mos paketwn ana 16sec kai h ru8mapososh pou prokuptei").getBytes());
echoThroughput16File.write((char) 13); //newline
echoThroughput32File.write(("Ari8mos paketwn ana 32sec kai h ru8mapososh pou prokuptei").getBytes());
echoThroughput32File.write((char) 13); //newline
}
catch (Exception x) {
System.out.println(x);
}
DatagramPacket packet = null;
String message = null;
long time4min = 4*60*1000; //4 λεπτα
long time8sec = 8*1000; //8 sec
long time16sec = 16*1000; //16 sec
long time32sec = 32*1000; //32 sec
long timeTotalStart = 0, timeTotalEnd = 0, timePacketStart = 0, timePacketEnd = 0; //Συνολικός χρόνος,χρόνος λείψης πακέτου
long time8secStart = 0 , time16secStart = 0 , time32secStart = 0; //Χρόνοι για τον υπολογισμό της ρυθμαπόδοσης
int numOfPackets8sec = 0; //Αριθμός πακέτων που λαμβάνονται ανά 8,16,32 seconds
int numOfPackets16sec = 0;
int numOfPackets32sec = 0;
timeTotalStart = System.currentTimeMillis();
time8secStart = timeTotalStart;
time16secStart = timeTotalStart;
time32secStart = timeTotalStart;
while(timeTotalEnd - timeTotalStart < time4min)
{
//Request
clientRequestDatagram(requestCode,serverPort);
//Response
timePacketStart = System.currentTimeMillis();
packet = serverResponseDatagramPacket(clientPort);
timePacketEnd = System.currentTimeMillis();
message = new String(Arrays.copyOfRange(packet.getData(),0,packet.getLength()));
System.out.println(message + " " );
System.out.println(timePacketEnd-timePacketStart);
//Γράψε τα δεδομένα και τον χρόνο απόκρισης στο αρχείο για διαγραμμα G1
try {
echoFile.write(Arrays.copyOfRange(packet.getData(),0,packet.getLength()));
echoFile.write((" " + String.valueOf(timePacketEnd-timePacketStart)).getBytes());
echoFile.write((char) 13); //newline
}
catch (Exception x) {
System.out.println(x);
break;
}
//Ρυθμαπόδοση για 8sec
if(timeTotalEnd-time8secStart < time8sec){
numOfPackets8sec++;
}else{
//Γράψε τον αριθμό των πακέτων στο αρχείο και την ρυθμαπόδοση που προκύπτει
try {
echoThroughput8File.write(String.valueOf(numOfPackets8sec).getBytes());
//Throughput = 32byte*8bit*numOfPackets8sec*1000/time_se_millis
long Throughput = (32*8*numOfPackets8sec*1000)/(timeTotalEnd-time8secStart);
echoThroughput8File.write((" " + String.valueOf(Throughput) + " bps").getBytes());
echoThroughput8File.write((char) 13); //newline
}
catch (Exception x) {
System.out.println(x);
break;
}
//Αρχικοποίηση μεταβλητών για την επόμενη μέτρηση των 8sec
time8secStart = System.currentTimeMillis();
numOfPackets8sec = 0;
}//telos gia 8sec
//Ρυθμαπόδοση για 16sec
if(timeTotalEnd-time16secStart < time16sec){
numOfPackets16sec++;
}else{
//Γράψε τον αριθμό των πακέτων στο αρχείο και την ρυθμαπόδοση που προκύπτει
try {
echoThroughput16File.write(String.valueOf(numOfPackets16sec).getBytes());
//Throughput = 32byte*8bit*numOfPackets8sec*1000/time_se_millis
long Throughput = (32*8*numOfPackets16sec*1000)/(timeTotalEnd-time16secStart);
echoThroughput16File.write((" " + String.valueOf(Throughput) + " bps").getBytes());
echoThroughput16File.write((char) 13); //newline
}
catch (Exception x) {
System.out.println(x);
break;
}
//Αρχικοποίηση μεταβλητών για την επόμενη μέτρηση των 8sec
time16secStart = System.currentTimeMillis();
numOfPackets16sec = 0;
}//telos gia 16sec
//Ρυθμαπόδοση για 32sec
if(timeTotalEnd-time32secStart < time32sec){
numOfPackets32sec++;
}else{
//Γράψε τον αριθμό των πακέτων στο αρχείο και την ρυθμαπόδοση που προκύπτει
try {
echoThroughput32File.write(String.valueOf(numOfPackets32sec).getBytes());
//Throughput = 32byte*8bit*numOfPackets8sec*1000/time_se_millis
long Throughput = (32*8*numOfPackets32sec*1000)/(timeTotalEnd-time32secStart);
echoThroughput32File.write((" " + String.valueOf(Throughput) + " bps").getBytes());
echoThroughput32File.write((char) 13); //newline
}
catch (Exception x) {
System.out.println(x);
break;
}
//Αρχικοποίηση μεταβλητών για την επόμενη μέτρηση των 8sec
time32secStart = System.currentTimeMillis();
numOfPackets32sec = 0;
}//telos gia 32sec
timeTotalEnd = System.currentTimeMillis();
}//telos while
//Κλείνουμε τα stream
echoFile.close();
echoThroughput8File.close();
echoThroughput16File.close();
echoThroughput32File.close();
}
static public void imageFunction(int imageId,String requestCode,int serverPort,int clientPort) throws IOException{
File imageFileName = new File("imageFile"+imageId+"_" + requestCode + ".jpg");
FileOutputStream imageFile = new FileOutputStream(imageFileName);
requestCode += "FLOW=ON";
DatagramPacket packet = null;
boolean startFind = false;
boolean endFind = false;
byte[] beginning = { (byte)0xFF , (byte)0xD8 }; //Χαρακτήρες αρχής εικόνας
byte[] termination = { (byte)0xFF , (byte)0xD9 }; //Χαρακτήρες τέλους εικόνας
//Request
clientRequestDatagram(requestCode,serverPort);
System.out.println("Wait Servo to move");
while(!startFind){ //Αναζήτηση των χαρακτήρων αρχής στα packets μέχρι να βρούμε την αρχή της εικόνας
packet = serverResponseDatagramPacket(clientPort); //Response
byte[] messegeBytes = Arrays.copyOfRange(packet.getData(),0,packet.getLength());
for(int i = 0;i<messegeBytes.length-1;i++){ //Εύρεση χαρακτήρων αρχής
if(messegeBytes[i] == beginning[0] && messegeBytes[i+1] == beginning[1]){
System.out.println("The image beggining was found");
//Αποθήκευση πακέτων εικόνας απο τους χαρακτήρες αρχής και μετά
try{
imageFile.write(Arrays.copyOfRange(messegeBytes, i, messegeBytes.length));
}
catch (Exception x) {System.out.println(x); }
startFind = true;
break;
}
}
clientRequestDatagram("NEXT",serverPort);
}
System.out.println("The image transfer was started");
while(!endFind){
//Response
packet = serverResponseDatagramPacket(clientPort); //Response
byte[] messegeBytes = Arrays.copyOfRange(packet.getData(),0,packet.getLength());
for(int i = 0; i<messegeBytes.length-1;i++){ //Ψαξε τους χαρακτήρες τέλους
if(messegeBytes[i] == termination[0] && messegeBytes[i+1] == termination[1]){
System.out.println("The end of the image was found");
//Αποθήκευση πακέτου μέχρι και τους χαρακτήρες τέλους
try {
imageFile.write(Arrays.copyOfRange(messegeBytes,0,i+2));
}
catch (Exception x) {
System.out.println(x);
}
endFind = true;
break;
}
}
// }
//Αποθήκευση ενδιάμεσων πακέτων εικόνας
if(!endFind)
try {
imageFile.write(Arrays.copyOfRange(packet.getData(),0,packet.getLength()));
}
catch (Exception x) {
System.out.println(x);
}
clientRequestDatagram("NEXT",serverPort);
}
imageFile.close();
}
static public void soundDPCM_OR_AQDPCM(String requestCode,int serverPort,int clientPort,int size1,boolean AQ_DPCM,int Qbits ) throws IOException{
//Αρχικοποιούμε για την περίπτωση της DPCM κωδικοποίησης
AudioFormat formatDPCM = new AudioFormat(8000, Qbits, 1, true, false);;
int size2 = 128;
int numofPackets = 0;
float b = (float) 1.6;
if(AQ_DPCM){ //Αν έχουμε AQ_DPCM κωδικοποίηση αρχικοποιούμε κατάλληλα τις μεταβλητές μας
Qbits = 16;
size2 = 132;
formatDPCM = new AudioFormat(8000, Qbits, 1, true, false);
System.out.println("AQ_DPCM");
}else{
System.out.println("DPCM");
}
byte[][] packetBuffer = new byte[size1][size2];
SourceDataLine dataLine = null;
try {
dataLine = AudioSystem.getSourceDataLine(formatDPCM);
} catch (LineUnavailableException ex) {}
try {
dataLine.open(formatDPCM, 32000); //32000 audio buffer
} catch (LineUnavailableException ex1) {}
dataLine.start();
//Request
clientRequestDatagram(requestCode,serverPort);
//Αρχικοποίηση μεταβλητών για τα πακέτα που έρχονται απο τον server
DatagramSocket r = new DatagramSocket(clientPort);
r.setSoTimeout(300);
byte[] rxbuffer = new byte[2048];
DatagramPacket packet = new DatagramPacket(rxbuffer,rxbuffer.length);
//Αποθήκευση δεδομένων σε έναν buffer size1(X)size2 = ari8mosPaketwn(X)mege8osPaketou
for (int i = 0; i < size1; i++) {
System.out.println("Size1 = "+ i);
try {
r.receive(packet); //Παραλαβή πακέτου
numofPackets++;
} catch (Exception x) {i--; size1--; System.out.println(x); continue;}
for (int j = 0; j < size2; j++) packetBuffer[i][j] = packet.getData()[j];
}
r.close(); //Κλείνουμε το Socket
System.out.println("numofPackets = "+ numofPackets);
byte[] bufferOut;
if (AQ_DPCM) {
bufferOut = aq_dpcm(packetBuffer,requestCode,numofPackets);
}
else{
bufferOut = dpcm(packetBuffer,requestCode,numofPackets, b);
}
dataLine.write(bufferOut , 0, bufferOut.length);
dataLine.stop();
dataLine.close();
}
static public byte[] dpcm(byte[][] packetBuffer,String requestCode,int size1, float b) throws IOException{
File diafFileName = new File("soundFilediaf_" + requestCode + ".txt");
FileOutputStream diafFile = new FileOutputStream(diafFileName); //Τα δεδομενα διαφορών οπως λαμβάνονται απο τον server
File deigFileName = new File("soundFiledeig_" + requestCode + ".txt");
FileOutputStream deigFile = new FileOutputStream(deigFileName); //Τα δεδομενα του τραγουδιού μετά την αποκωδικοποίηση
byte[] bufferOut = new byte[128 * 2 * size1];
int tempData;
int nibbleLS;
int nibbleMS;
String string;
int size2 = packetBuffer[0].length;
int index = -1;
for (int i = 0; i < size1; i++) {
for (int j = 0; j < size2; j++) {
tempData = (int) packetBuffer[i][j] ;
nibbleLS = (tempData ) & 0b00001111; //Απομονώνουμε τα 2 δειγματα ηχου για καθε byte δεδομένων
nibbleMS = (tempData >>> 4) & 0b00001111;
//Gia to MSB
index++;
tempData = Math.round((nibbleMS - 8) * b);
try {
string = Integer.toString(tempData);
diafFile.write(string.getBytes());
diafFile.write((char) 13);
} catch (IOException ex) {}
if (j > 0)
tempData = tempData + bufferOut[index - 1];
try {
string = Integer.toString(tempData);
deigFile.write(string.getBytes());
deigFile.write(13);
deigFile.write(10);
bufferOut[index] = (byte) tempData;
} catch (IOException ex1) {}
//Gia to LSB
index++;
tempData = Math.round((nibbleLS - 8) * b);
try {
string = Integer.toString(tempData);
diafFile.write(string.getBytes());
diafFile.write(13);
diafFile.write(10);
} catch (IOException ex2) {}
tempData = tempData + bufferOut[index - 1];
try {
string = Integer.toString(tempData);
deigFile.write(string.getBytes());
deigFile.write(13);
deigFile.write(10);
bufferOut[index] = (byte) tempData;
} catch (IOException ex3) {
}
}
}
diafFile.close();
deigFile.close();
return bufferOut;
}
static public byte[] aq_dpcm(byte[][] packetBuffer,String requestCode,int size1) throws IOException{
File diafFileName = new File("soundFilediaf_" + requestCode + ".txt");
FileOutputStream diafFile = new FileOutputStream(diafFileName); //Τα δεδομενα διαφορών οπως λαμβάνονται απο τον server
File deigFileName = new File("soundFiledeig_" + requestCode + ".txt");
FileOutputStream deigFile = new FileOutputStream(deigFileName); //Τα δεδομενα του τραγουδιού μετά την αποκωδικοποίηση
File meanFileName = new File("soundMeanFile_" + requestCode + ".txt");
FileOutputStream meanFile = new FileOutputStream(meanFileName); //Η τιμή του μέσου όρου που διαβάζεται από κάθε πακέτο
File stepFileName = new File("soundStepFile_" + requestCode + ".txt");
FileOutputStream stepFile = new FileOutputStream(stepFileName); //Η τιμή του βήματος που διαβάζεται από κάθε πακέτο
String string;
byte[] bufferOut = new byte[2* (128 * 2) * size1];
int[][] samples = new int[size1][128 * 2];
int[] mean = new int[size1];
int[] step = new int[size1];
int tempData;
int nibbleLS;
int nibbleMS;
int index = -1;
int bb;
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
//Για κάθε πακέτο που λάβαμε
for (int i = 0; i < size1; i++) {
//Παίρνουμε τον μέσω όρο και το βήμα
mean[i] = 256 * packetBuffer[i][1] + packetBuffer[i][0]; //msb+lsb
step[i] = 256 * packetBuffer[i][3] + packetBuffer[i][2]; //msb+lsb;
try { //Εγγραφη της μεσης τιμής και του βήματος σε αρχεία
string = Integer.toString(mean[i]);
meanFile.write(string.getBytes());
meanFile.write(13);
meanFile.write(10);
string = Integer.toString(step[i]);
stepFile.write(string.getBytes());
stepFile.write(13);
stepFile.write(10);
} catch (IOException ex1) {}
index = -1;
//Αποκωδικοποίηση και αποθήκευση των δεδομένων ήχου(διαφορές xi-x(i-1))κάθε πακέτου στον πίνακα sample
for (int j = 4; j < packetBuffer[0].length; j++) {
bb = step[i];
tempData = (int) packetBuffer[i][j];
nibbleLS = ( ( tempData & 0x0F )-8 )*bb;
nibbleMS = ( (( tempData >>> 4) & 0x0F )-8 )*bb;
samples[i][++index] = nibbleMS;
samples[i][++index] = nibbleLS;
}
}
//Aποθήκευση των δεδομένων σε αρχεία
//----------------------------------------------//
for (int m=0; m<samples.length; m++){
for (int n = 0; n < samples[0].length; n++)
{
try {
string = Integer.toString(samples[m][n]);
diafFile.write(string.getBytes());
diafFile.write(13);
diafFile.write(10);
} catch (IOException ex) { }
if (n>0) samples[m][n] += samples[m][n - 1]; //Προηγούμενο δειγμα τρεχοντος πακέτου
}
}
index = -1;
for (int m=0; m<samples.length; m++)
for (int n = 0; n < samples[0].length; n++)
{
samples[m][n] += mean[m];
try
{
string = Integer.toString(samples[m][n]);
deigFile.write(string.getBytes());
deigFile.write(13);
deigFile.write(10);
}catch (IOException ex){ }
bufferOut[++index] = (byte) samples[m][n];
bufferOut[++index] = (byte) (samples[m][n] >>> 8);
if (samples[m][n]>max){
max = samples[m][n];
}else if (samples[m][n]<min){
min = samples[m][n];
}
}
System.out.println("max --> " + max);
System.out.println("min -->" + min);
System.out.println("aq-dpcm");
//----------------------------------------------//
//Κλείνουμε τα αρχεία
diafFile.close();
deigFile.close();
meanFile.close();
stepFile.close();
return bufferOut;
}
static public void ithakicopter(int serverPort,int fLevel) throws IOException{
File copterFileName = new File("ithakiCopter_" + fLevel + ".txt");
FileOutputStream copterFile = new FileOutputStream(copterFileName);
File errorsPIDFileName = new File("PIDCopterController_" + fLevel + ".txt");
FileOutputStream errorsPIDFile = new FileOutputStream(errorsPIDFileName);
//Δημιουργία TCP socket για την επικοινωνία με τον Server
String hostIP ="155.207.18.208";
InetAddress hostAddress = InetAddress.getByName(hostIP);
Socket sock = new Socket(hostAddress,serverPort);
DataOutputStream copterStreamTCP_OUT = new DataOutputStream(sock.getOutputStream());
BufferedReader copterStreamTCP_IN = new BufferedReader(new InputStreamReader(sock.getInputStream()));
StringBuilder buffer = new StringBuilder();
String fileLabel = "Epi8umhtes times fLevel,lMotor,rMotor, Times pou lambanoume gia fLevel,lMotor,rMotor\n";
buffer.append(fileLabel);
StringBuilder errorsBuffer = new StringBuilder();
fileLabel = "PID controller errors\nProportial Integral Derivative\n";
errorsBuffer.append(fileLabel);
long startTime = System.currentTimeMillis();
long time3min = 3*60*1000; //3 λεπτα
int index=-1;
int MaxdDelay = 20; //Ορίζουμε καθυστέριση για το control των κινητήρων,
int delay = MaxdDelay; //δηλαδή καθυστέριση μεταξύ των αλλαγών της ταχύτητας των κινητήρων
int error =0;
int du_DIV_dt = 0;
int sumError = 0;
int prevAltitude = 74;
int lMotor = 178; //Αρχικές τιμές κινητήρων
int rMotor = 178;
while((System.currentTimeMillis()-startTime)< time3min-100){ //Λίγο λιγότερο απο 3λεπτά
String strfLevel = String.valueOf(fLevel);
String strlMotor = String.valueOf(lMotor);
String strrMotor = String.valueOf(rMotor);
//Οι μεταβλητές LLL RRR και AAA πρέπει να είναι τριψήφιοι αριθμοί
if(fLevel <100) strfLevel="0"+fLevel;
if(lMotor <100) strlMotor="0"+lMotor;
if(rMotor <100) strrMotor="0"+rMotor;
if(fLevel <10) strfLevel="00"+fLevel;
if(lMotor <10) strlMotor="00"+lMotor;
if(rMotor <10) strrMotor="00"+rMotor;
String requestCode = "AUTO FLIGHTLEVEL="+strfLevel+" LMOTOR="+strlMotor+" RMOTOR="+strrMotor+" PILOT \r\n";
//Request
copterStreamTCP_OUT.writeBytes(requestCode);
//Response
String message = copterStreamTCP_IN.readLine();
System.out.println(message);
//Πρεπει να βρουμε το ITHAKICOPTER και μετα να αποθηκέυσουμε τα απολεσματα
try{
if(message.indexOf("ITHAKICOPTER")!=0)
continue;
else{
index++;
if(index==0) continue;
}
}catch(Exception x) { System.out.println(x); break;}
String delimeter = " |=";
String[] data = message.split(delimeter); //Διαχωρίζουμε τα δεδομένα και παίρνουμε τις τιμές τους
buffer.append(index+" ");
buffer.append(fLevel+" "); //FLIGHT LEVEL
buffer.append(lMotor+" "); //LMOTOR
buffer.append(rMotor+" "); //RMOTOR
buffer.append(" ");
int altitude = Integer.parseInt(data[6]);
buffer.append(altitude+" "); //ALTITUDE
int lmotor = Integer.parseInt(data[2]);
buffer.append(lmotor+" "); //LMOTOR
int rmotor = Integer.parseInt(data[4]);
buffer.append(rmotor+" "); //RMOTOR
float temperature = Float.parseFloat(data[8]);
buffer.append(temperature+" "); //TEMPERATURE
float pressure = Float.parseFloat(data[10]);
buffer.append(pressure+"\n"); //PRESSURE
//---------------------PID Controller------------------//
//PID controller for motor speed
//Κατασκευάζουμε έναν controller που ελέγχει το επιθυμητό ύψος προσαρμόζοντας τις στροφές των κινητήρων.
//Λόγο της καθυστέρησης που υπάρχει μεταξύ στην επικοινωνία εισάγουμε μέσω της μεταβλητής delay καθυστέρηση
//στον βρόχο ανάδρασης. Με απλά λόγια,στέλνουμε το έτοιμα για τις στροφές των κινητήρων και περιμένουμε κάποιο
//χρονικό διάστημα(μέσω της Delay) μέρχι να σταλεί το έτοιμα και να κινηθεί κατάλληλα το copter και μέτα υπολογίζουμε το σφάλμα
//και προσαρμόζουμε την νέα ταχύτητα των κινητήρων
delay++;
if(delay>MaxdDelay){
error = fLevel - altitude; //P
sumError += error; //I
du_DIV_dt = prevAltitude - altitude; //D
if(sumError>15 || sumError <-15) sumError = 0; //Διότι το σφάλμα error είναι ικανό να διορθώση την θέση
error = Math.round((float) 0.1*(float)error); //P
int tempSumError = Math.round((float) 0.05*(float)sumError); //I
du_DIV_dt = Math.round((float) 0.1*(float)du_DIV_dt); //D
int total_error = error + du_DIV_dt + tempSumError;
System.out.println(error);
System.out.println(du_DIV_dt);
System.out.println(tempSumError);
System.out.println(total_error);
errorsBuffer.append(error+" ");
errorsBuffer.append(du_DIV_dt+" ");
errorsBuffer.append(tempSumError+"\n");
if((lMotor + total_error)<200 && (rMotor + total_error)<200 ){
lMotor = lMotor + total_error;
rMotor = rMotor + total_error;
}else if(total_error>0){
lMotor = 200;
rMotor = 200;
}
delay = 0;
prevAltitude = altitude;
}
//---------------------PID End of code------------------//
}//Telos while()
//Εγγραφή στα αρχεία
try
{
copterFile.write(buffer.toString().getBytes());
errorsPIDFile.write(errorsBuffer.toString().getBytes());
} catch (Exception x) {System.out.println(x);}
copterFile.close();
errorsPIDFile.close();
sock.close();
}
static public void OBDfunction(int serverPort) throws IOException{
File OBDFileName = new File("OBDData_" + ".txt");
FileOutputStream OBDFile = new FileOutputStream(OBDFileName);
//Δημιουργία TCP socket για την επικοινωνία με τον Server
String hostIP ="155.207.18.208";
InetAddress hostAddress = InetAddress.getByName(hostIP);
Socket sock = new Socket(hostAddress,serverPort);
DataOutputStream OBDStreamTCP_OUT = new DataOutputStream(sock.getOutputStream());
BufferedReader OBDStreamTCP_IN = new BufferedReader(new InputStreamReader(sock.getInputStream()));
StringBuilder buffer = new StringBuilder();
String fileLabel = "EngineRunTime IntakeAirTemperature ThrottlePosition EngineRPM VehicleSpeed CoolantTemperature\n";
buffer.append(fileLabel);
String delimeter = " ";
long startTime = System.currentTimeMillis();
long time4min = 4*60*1000; //4 λεπτα
String mode = "01";
String[] PID = {"1F","0F","11","0C","0D","05"};
String message = "";
int x = 0;
int y = 0;
while (System.currentTimeMillis()-startTime < time4min){ //Για 4 λεπτά
for(int i = 0;i<6;i++){
OBDStreamTCP_OUT.writeBytes(mode+" "+PID[i] + "\r");
message = OBDStreamTCP_IN.readLine();
String[] received_data = message.split(delimeter);
switch(i){
case 0:
x = Integer.parseInt(received_data[2], 16);
y = Integer.parseInt(received_data[3], 16);
int engineRunTime=255*x + y;
buffer.append(engineRunTime+" ");
System.out.print(engineRunTime+" ");
break;
case 1:
x = Integer.parseInt(received_data[2], 16);
int intakeAirTemperature=x-40;
buffer.append(intakeAirTemperature+" ");
System.out.print(intakeAirTemperature+" ");
break;
case 2:
x=Integer.parseInt(received_data[2], 16);
int throttlePosition=x*100/255;
buffer.append(throttlePosition+" ");
System.out.print(throttlePosition+" ");
break;
case 3:
x = Integer.parseInt(received_data[2], 16);
y = Integer.parseInt(received_data[3], 16);
int engineRpm=(256*x + y)/4;
buffer.append(engineRpm+" ");
System.out.print(engineRpm+" ");
break;
case 4:
x = Integer.parseInt(received_data[2], 16);
int vehicleSpeed=x;
buffer.append(vehicleSpeed+" ");
System.out.print(vehicleSpeed+" ");
break;
case 5:
x = Integer.parseInt(received_data[2], 16);
int coolantTemperature=x-40;
buffer.append(coolantTemperature+" \n");
System.out.println(coolantTemperature+" \n");
break;
}
}
}//Telos while()
OBDFile.write(buffer.toString().getBytes());
OBDFile.close();
sock.close();
}
}//telos class Main
| theompek/Java_Network_Application_UDP_TCP_Communication_Protocols | src/userApplication.java |
2,499 | package Games;
import GetData.*;
import java.util.*;
import javax.swing.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import java.net.*;
import java.awt.event.*;
import javax.swing.Timer;
import java.text.*;
public class Game extends javax.swing.JApplet implements ActionListener{
String word, wordold, wordnew, word2, word3, word4, word6, word8, word9,
quest,answ,dbpedia,wiki,quest2,dbpedia2,wiki2,quest3,dbpedia3,wiki3,quest4,dbpedia4,wiki4,quest5,dbpedia5,wiki5,
answ1,answ2,answ3,answ4,answ5,answw,correctanswers,duplicatequestion="";
String [] question, answer, usersanswer; String[] [] data;
int frameNumber,indeximages,indexnoimages,mouseoverbutton=0;
int [] frameNumber1;
Timer timer;
boolean frozen = false; boolean [] correct;
char [] wordarray, word5, word7;
int count, len, exist, total, game,score,num,comboindex=0,checkindex=0,numofcorrect;
String name; String [] GamePlayed,Category;
int TimesPlayed=1000,GameOver=0; int [] indexarray;
String URI1="http://wiki.el.dbpedia.org/apps/ssg/files/";
@Override
public void init() {
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Game.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Game.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Game.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Game.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
try {
java.awt.EventQueue.invokeAndWait(new Runnable() {
@Override
public void run() {
initComponents();
}
});
} catch (Exception ex) { }
score=0; total=0;
jButton25.setVisible(false);jButton27.setVisible(false);
frameNumber1=new int[TimesPlayed];
correct=new boolean[TimesPlayed];
num=0;
name="Άτομο χωρίς όνομα";
name=JOptionPane.showInputDialog(null,"Πώς σε λένε;");
if (name==null | "".equals(name)) {name="άτομο χωρίς όνομα";}
jLabel9.setText("Γεια σου "+name);
for (int i=0;i<TimesPlayed;i++) {frameNumber1[i]=-1;}
frameNumber = -1;
jLabel10.setVisible(false);
GamePlayed=new String[TimesPlayed];
Category=new String[TimesPlayed];
question=new String[TimesPlayed];
answer=new String[TimesPlayed];
jScrollPane1.setVisible(false);
jLabel2.setText(null);
try {
URL url = new URL(URI1+"logos/el-dbpedia.png");
BufferedImage img = ImageIO.read(url);
Icon icon=new ImageIcon(img);
jLabel11.setIcon(icon);
} catch (IOException e) {System.out.println("1");}
try {
URL url = new URL(URI1+"logos/el-wikipedia.png");
BufferedImage img = ImageIO.read(url);
Icon icon=new ImageIcon(img);
jLabel12.setIcon(icon);
} catch (IOException e) {System.out.println("2");}
try {
URL url = new URL(URI1+"logos/auth-math.png");
BufferedImage img = ImageIO.read(url);
Icon icon=new ImageIcon(img);
jLabel13.setIcon(icon);
} catch (IOException e) {System.out.println("3");}
try {
URL url = new URL(URI1+"logos/eldbpedia.png");
BufferedImage img = ImageIO.read(url);
Icon icon=new ImageIcon(img);
jLabel16.setIcon(icon);
jLabel19.setIcon(icon);
jLabel22.setIcon(icon);
jLabel25.setIcon(icon);
jLabel30.setIcon(icon);
} catch (IOException e) {System.out.println("4");}
try {
URL url = new URL(URI1+"logos/wikipedia.png");
BufferedImage img = ImageIO.read(url);
Icon icon=new ImageIcon(img);
jLabel17.setIcon(icon);
jLabel20.setIcon(icon);
jLabel23.setIcon(icon);
jLabel26.setIcon(icon);
jLabel31.setIcon(icon);
} catch (IOException e) {System.out.println("5");}
try {
URL url = new URL(URI1+"smileys/thinking.png");
BufferedImage smiley = ImageIO.read(url);
java.awt.Image smiley2=smiley.getScaledInstance(150,150,BufferedImage.SCALE_SMOOTH);
Icon icon=new ImageIcon(smiley2);
jLabel32.setIcon(icon);
} catch (IOException e) {System.out.println("6");}
jLabel1.setText("Ερώτηση: 1η");
ReadFromFile GetData = new ReadFromFile(); indexarray=GetData.index1(); data=GetData.data(indexarray);
//indeximages=GetData.indeximages();
//indexnoimages=GetData.indexnoimages();
//System.out.println("to images= "+indeximages+"kai to no images="+indexnoimages);
DeActivateAll();
//if (indexnoimages==1) {GamePlayed[0]="Πολλαπλή Επιλογή (Multiple Choice)"; MultipleChoice();}
//else if (indeximages==1 && indexnoimages==0) {GamePlayed[num]="Πολλαπλή Επιλογή (1 Εικόνα, 4 Επιλογές)"; Flag();}
//else if (indexnoimages==0 && indeximages==0) {GamePlayed[num]="Κρεμάλα (Hangman)";Hangman();}
GamePlayed[0]="Πολλαπλή Επιλογή (Multiple Choice)"; MultipleChoice();
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
buttonGroup1 = new javax.swing.ButtonGroup();
jTextField1 = new javax.swing.JTextField();
jTextField5 = new javax.swing.JTextField();
jRadioButton1 = new javax.swing.JRadioButton();
jRadioButton2 = new javax.swing.JRadioButton();
jRadioButton3 = new javax.swing.JRadioButton();
jRadioButton4 = new javax.swing.JRadioButton();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jComboBox1 = new javax.swing.JComboBox();
jComboBox2 = new javax.swing.JComboBox();
jComboBox3 = new javax.swing.JComboBox();
jComboBox4 = new javax.swing.JComboBox();
jTextField2 = new javax.swing.JTextField();
jTextField6 = new javax.swing.JTextField();
jButton19 = new javax.swing.JButton();
jButton17 = new javax.swing.JButton();
jButton18 = new javax.swing.JButton();
jButton15 = new javax.swing.JButton();
jButton16 = new javax.swing.JButton();
jButton22 = new javax.swing.JButton();
jButton13 = new javax.swing.JButton();
jButton23 = new javax.swing.JButton();
jButton14 = new javax.swing.JButton();
jButton24 = new javax.swing.JButton();
jButton11 = new javax.swing.JButton();
jButton12 = new javax.swing.JButton();
jButton10 = new javax.swing.JButton();
jButton20 = new javax.swing.JButton();
jButton21 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton1 = new javax.swing.JButton();
jButton7 = new javax.swing.JButton();
jButton6 = new javax.swing.JButton();
jButton5 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
jButton9 = new javax.swing.JButton();
jButton8 = new javax.swing.JButton();
jLabel10 = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel11 = new javax.swing.JLabel();
jLabel12 = new javax.swing.JLabel();
jLabel13 = new javax.swing.JLabel();
jLabel14 = new javax.swing.JLabel();
jButton25 = new javax.swing.JButton();
jLabel15 = new javax.swing.JLabel();
jLabel16 = new javax.swing.JLabel();
jLabel17 = new javax.swing.JLabel();
jLabel18 = new javax.swing.JLabel();
jLabel19 = new javax.swing.JLabel();
jLabel21 = new javax.swing.JLabel();
jLabel22 = new javax.swing.JLabel();
jLabel23 = new javax.swing.JLabel();
jLabel24 = new javax.swing.JLabel();
jLabel25 = new javax.swing.JLabel();
jLabel26 = new javax.swing.JLabel();
jButton26 = new javax.swing.JButton();
jLabel20 = new javax.swing.JLabel();
jLabel27 = new javax.swing.JLabel();
jLabel28 = new javax.swing.JLabel();
jCheckBox1 = new javax.swing.JCheckBox();
jCheckBox2 = new javax.swing.JCheckBox();
jCheckBox3 = new javax.swing.JCheckBox();
jCheckBox4 = new javax.swing.JCheckBox();
jCheckBox5 = new javax.swing.JCheckBox();
jRadioButton5 = new javax.swing.JRadioButton();
jLabel29 = new javax.swing.JLabel();
jLabel30 = new javax.swing.JLabel();
jLabel31 = new javax.swing.JLabel();
jButton27 = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jLabel32 = new javax.swing.JLabel();
setBackground(new java.awt.Color(240, 240, 240));
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jTextField1.setBackground(new java.awt.Color(255, 204, 204));
jTextField1.setEditable(false);
jTextField1.setFont(new java.awt.Font("Tahoma", 0, 16));
jTextField1.setAlignmentX(3.0F);
jTextField1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
jTextField5.setBackground(new java.awt.Color(255, 204, 102));
jTextField5.setEditable(false);
jTextField5.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jTextField5.setAlignmentX(3.0F);
jTextField5.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
jTextField5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField5ActionPerformed(evt);
}
});
buttonGroup1.add(jRadioButton1);
jRadioButton1.setFont(new java.awt.Font("Tahoma", 0, 16)); // NOI18N
jRadioButton1.setText("1η Απάντηση");
jRadioButton1.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jRadioButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButton1ActionPerformed(evt);
}
});
buttonGroup1.add(jRadioButton2);
jRadioButton2.setFont(new java.awt.Font("Tahoma", 0, 16));
jRadioButton2.setText("2η Απάντηση");
jRadioButton2.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jRadioButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButton2ActionPerformed(evt);
}
});
buttonGroup1.add(jRadioButton3);
jRadioButton3.setFont(new java.awt.Font("Tahoma", 0, 16));
jRadioButton3.setText("3η Απάντηση");
jRadioButton3.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jRadioButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButton3ActionPerformed(evt);
}
});
buttonGroup1.add(jRadioButton4);
jRadioButton4.setFont(new java.awt.Font("Tahoma", 0, 16));
jRadioButton4.setText("4η Απάντηση");
jRadioButton4.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jRadioButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButton4ActionPerformed(evt);
}
});
jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel2.setText("Εικόνα");
jLabel3.setFont(new java.awt.Font("Tahoma", 0, 16)); // NOI18N
jLabel3.setText("Κείμενο 1");
jLabel4.setFont(new java.awt.Font("Tahoma", 0, 16)); // NOI18N
jLabel4.setText("Κείμενο 2");
jLabel5.setFont(new java.awt.Font("Tahoma", 0, 16)); // NOI18N
jLabel5.setText("Κείμενο 3");
jLabel6.setFont(new java.awt.Font("Tahoma", 0, 16)); // NOI18N
jLabel6.setText("Κείμενο 4");
jComboBox1.setFont(new java.awt.Font("Tahoma", 0, 16)); // NOI18N
jComboBox1.setMaximumRowCount(4);
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox1.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jComboBox1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox1ActionPerformed(evt);
}
});
jComboBox2.setFont(new java.awt.Font("Tahoma", 0, 16)); // NOI18N
jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox2.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jComboBox2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox2ActionPerformed(evt);
}
});
jComboBox3.setFont(new java.awt.Font("Tahoma", 0, 16)); // NOI18N
jComboBox3.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox3.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jComboBox4.setFont(new java.awt.Font("Tahoma", 0, 16)); // NOI18N
jComboBox4.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox4.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jTextField2.setBackground(new java.awt.Color(204, 204, 255));
jTextField2.setEditable(false);
jTextField2.setFont(new java.awt.Font("Tahoma", 0, 16));
jTextField2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField2ActionPerformed(evt);
}
});
jTextField6.setBackground(new java.awt.Color(204, 204, 255));
jTextField6.setEditable(false);
jTextField6.setFont(new java.awt.Font("Tahoma", 0, 16));
jTextField6.setHorizontalAlignment(javax.swing.JTextField.CENTER);
jButton19.setFont(new java.awt.Font("Tahoma", 0, 18));
jButton19.setText("Τ");
jButton19.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jButton19.setDefaultCapable(false);
jButton19.setPreferredSize(new java.awt.Dimension(41, 23));
jButton19.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton19ActionPerformed(evt);
}
});
jButton17.setFont(new java.awt.Font("Tahoma", 0, 18));
jButton17.setText("Ρ");
jButton17.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jButton17.setDefaultCapable(false);
jButton17.setPreferredSize(new java.awt.Dimension(41, 23));
jButton17.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton17ActionPerformed(evt);
}
});
jButton18.setFont(new java.awt.Font("Tahoma", 0, 18));
jButton18.setText("Σ");
jButton18.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jButton18.setDefaultCapable(false);
jButton18.setPreferredSize(new java.awt.Dimension(41, 23));
jButton18.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton18ActionPerformed(evt);
}
});
jButton15.setFont(new java.awt.Font("Tahoma", 0, 18));
jButton15.setText("Ο");
jButton15.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jButton15.setDefaultCapable(false);
jButton15.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton15ActionPerformed(evt);
}
});
jButton16.setFont(new java.awt.Font("Tahoma", 0, 18));
jButton16.setText("Π");
jButton16.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jButton16.setDefaultCapable(false);
jButton16.setPreferredSize(new java.awt.Dimension(41, 23));
jButton16.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton16ActionPerformed(evt);
}
});
jButton22.setFont(new java.awt.Font("Tahoma", 0, 18));
jButton22.setText("Χ");
jButton22.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jButton22.setDefaultCapable(false);
jButton22.setPreferredSize(new java.awt.Dimension(41, 23));
jButton22.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton22ActionPerformed(evt);
}
});
jButton13.setFont(new java.awt.Font("Tahoma", 0, 18));
jButton13.setText("Ν");
jButton13.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jButton13.setDefaultCapable(false);
jButton13.setPreferredSize(new java.awt.Dimension(41, 23));
jButton13.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton13ActionPerformed(evt);
}
});
jButton23.setFont(new java.awt.Font("Tahoma", 0, 18));
jButton23.setText("Ψ");
jButton23.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jButton23.setDefaultCapable(false);
jButton23.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton23ActionPerformed(evt);
}
});
jButton14.setFont(new java.awt.Font("Tahoma", 0, 18));
jButton14.setText("Ξ");
jButton14.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jButton14.setDefaultCapable(false);
jButton14.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton14ActionPerformed(evt);
}
});
jButton24.setFont(new java.awt.Font("Tahoma", 0, 18));
jButton24.setText("Ω");
jButton24.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jButton24.setDefaultCapable(false);
jButton24.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton24ActionPerformed(evt);
}
});
jButton11.setFont(new java.awt.Font("Tahoma", 0, 18));
jButton11.setText("Λ");
jButton11.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jButton11.setDefaultCapable(false);
jButton11.setPreferredSize(new java.awt.Dimension(41, 23));
jButton11.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton11ActionPerformed(evt);
}
});
jButton12.setFont(new java.awt.Font("Tahoma", 0, 18));
jButton12.setText("Μ");
jButton12.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jButton12.setDefaultCapable(false);
jButton12.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton12ActionPerformed(evt);
}
});
jButton10.setFont(new java.awt.Font("Tahoma", 0, 18));
jButton10.setText("Κ");
jButton10.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jButton10.setDefaultCapable(false);
jButton10.setPreferredSize(new java.awt.Dimension(41, 23));
jButton10.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton10ActionPerformed(evt);
}
});
jButton20.setFont(new java.awt.Font("Tahoma", 0, 18));
jButton20.setText("Υ");
jButton20.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jButton20.setDefaultCapable(false);
jButton20.setPreferredSize(new java.awt.Dimension(41, 23));
jButton20.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton20ActionPerformed(evt);
}
});
jButton21.setFont(new java.awt.Font("Tahoma", 0, 18));
jButton21.setText("Φ");
jButton21.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jButton21.setDefaultCapable(false);
jButton21.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton21ActionPerformed(evt);
}
});
jButton3.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jButton3.setText("Γ");
jButton3.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jButton3.setDefaultCapable(false);
jButton3.setPreferredSize(new java.awt.Dimension(41, 23));
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jButton2.setFont(new java.awt.Font("Tahoma", 0, 18));
jButton2.setText("Β");
jButton2.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jButton2.setDefaultCapable(false);
jButton2.setPreferredSize(new java.awt.Dimension(41, 23));
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jButton1.setFont(new java.awt.Font("Tahoma", 0, 18));
jButton1.setText("Α");
jButton1.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jButton1.setDefaultCapable(false);
jButton1.setPreferredSize(new java.awt.Dimension(41, 23));
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton7.setFont(new java.awt.Font("Tahoma", 0, 18));
jButton7.setText("Η");
jButton7.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jButton7.setDefaultCapable(false);
jButton7.setPreferredSize(new java.awt.Dimension(41, 23));
jButton7.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton7ActionPerformed(evt);
}
});
jButton6.setFont(new java.awt.Font("Tahoma", 0, 18));
jButton6.setText("Ζ");
jButton6.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jButton6.setDefaultCapable(false);
jButton6.setPreferredSize(new java.awt.Dimension(41, 23));
jButton6.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton6ActionPerformed(evt);
}
});
jButton5.setFont(new java.awt.Font("Tahoma", 0, 18));
jButton5.setText("Ε");
jButton5.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jButton5.setDefaultCapable(false);
jButton5.setPreferredSize(new java.awt.Dimension(41, 23));
jButton5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton5ActionPerformed(evt);
}
});
jButton4.setFont(new java.awt.Font("Tahoma", 0, 18));
jButton4.setText("Δ");
jButton4.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jButton4.setDefaultCapable(false);
jButton4.setPreferredSize(new java.awt.Dimension(41, 23));
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
jButton9.setFont(new java.awt.Font("Tahoma", 0, 18));
jButton9.setText("Ι");
jButton9.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jButton9.setDefaultCapable(false);
jButton9.setPreferredSize(new java.awt.Dimension(41, 23));
jButton9.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton9ActionPerformed(evt);
}
});
jButton8.setFont(new java.awt.Font("Tahoma", 0, 18));
jButton8.setText("Θ");
jButton8.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jButton8.setDefaultCapable(false);
jButton8.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton8ActionPerformed(evt);
}
});
jLabel10.setIcon(new javax.swing.ImageIcon("C:\\Users\\Ιωάννης\\Desktop\\ΤΡΕΧΟΝΤΑ\\hangman\\hanged0.jpg")); // NOI18N
jLabel1.setText("Ερώτηση:");
jLabel8.setText("Χρόνος");
jLabel9.setText("Όνομα");
jLabel7.setText("Συνολικός Χρόνος");
jLabel14.setText("Βαθμολογία: 0 / 0");
jButton25.setFont(new java.awt.Font("Tahoma", 0, 13));
jButton25.setText("Επόμενη Ερώτηση");
jButton25.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jButton25.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton25ActionPerformed(evt);
}
});
jLabel15.setFont(new java.awt.Font("Tahoma", 0, 14));
jLabel15.setForeground(new java.awt.Color(51, 51, 255));
jLabel15.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
jLabel15.setText("Για περισσότερες πληροφορίες σχετικά με: ");
jLabel16.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jLabel16.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel16MouseClicked(evt);
}
});
jLabel17.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jLabel17.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel17MouseClicked(evt);
}
});
jLabel18.setFont(new java.awt.Font("Tahoma", 0, 14));
jLabel18.setForeground(new java.awt.Color(51, 51, 255));
jLabel18.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
jLabel18.setText("Για περισσότερες πληροφορίες σχετικά με: ");
jLabel19.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jLabel19.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel19MouseClicked(evt);
}
});
jLabel21.setFont(new java.awt.Font("Tahoma", 0, 14));
jLabel21.setForeground(new java.awt.Color(51, 51, 255));
jLabel21.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
jLabel21.setText("Για περισσότερες πληροφορίες σχετικά με: ");
jLabel22.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jLabel22.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel22MouseClicked(evt);
}
});
jLabel23.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jLabel23.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel23MouseClicked(evt);
}
});
jLabel24.setFont(new java.awt.Font("Tahoma", 0, 14));
jLabel24.setForeground(new java.awt.Color(51, 51, 255));
jLabel24.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
jLabel24.setText("Για περισσότερες πληροφορίες σχετικά με: ");
jLabel25.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jLabel25.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel25MouseClicked(evt);
}
});
jLabel26.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jLabel26.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel26MouseClicked(evt);
}
});
jButton26.setFont(new java.awt.Font("Tahoma", 0, 13));
jButton26.setText("Υποβολή");
jButton26.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jButton26.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton26ActionPerformed(evt);
}
});
jLabel20.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jLabel20.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel20MouseClicked(evt);
}
});
jLabel27.setFont(new java.awt.Font("Tahoma", 0, 16));
jLabel27.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel27.setText("Ερώτημα");
jLabel28.setText("Κατηγορία: Γενικές Γνώσεις");
jCheckBox1.setFont(new java.awt.Font("Tahoma", 0, 16)); // NOI18N
jCheckBox1.setText("1η Απάντηση");
jCheckBox1.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jCheckBox2.setFont(new java.awt.Font("Tahoma", 0, 16)); // NOI18N
jCheckBox2.setText("2η Απάντηση");
jCheckBox2.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jCheckBox2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jCheckBox2ActionPerformed(evt);
}
});
jCheckBox3.setFont(new java.awt.Font("Tahoma", 0, 16));
jCheckBox3.setText("3η Απάντηση");
jCheckBox3.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jCheckBox4.setFont(new java.awt.Font("Tahoma", 0, 16));
jCheckBox4.setText("4η Απάντηση");
jCheckBox4.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jCheckBox5.setFont(new java.awt.Font("Tahoma", 0, 16));
jCheckBox5.setText("5η Απάντηση");
jCheckBox5.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
buttonGroup1.add(jRadioButton5);
jRadioButton5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButton5ActionPerformed(evt);
}
});
jLabel29.setFont(new java.awt.Font("Tahoma", 0, 14));
jLabel29.setForeground(new java.awt.Color(51, 51, 255));
jLabel29.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
jLabel29.setText("Για περισσότερες πληροφορίες σχετικά με: ");
jLabel30.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jLabel30.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel30MouseClicked(evt);
}
});
jLabel31.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jLabel31.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel31MouseClicked(evt);
}
});
jButton27.setFont(new java.awt.Font("Tahoma", 1, 36));
jButton27.setForeground(new java.awt.Color(255, 0, 0));
jButton27.setText("X");
jButton27.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jButton27.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jButton27MouseClicked(evt);
}
public void mouseEntered(java.awt.event.MouseEvent evt) {
jButton27MouseEntered(evt);
}
});
jButton27.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton27ActionPerformed(evt);
}
});
jTextArea1.setColumns(20);
jTextArea1.setFont(new java.awt.Font("Monospaced", 2, 12)); // NOI18N
jTextArea1.setLineWrap(true);
jTextArea1.setRows(5000);
jTextArea1.setWrapStyleWord(true);
jScrollPane1.setViewportView(jTextArea1);
jLabel32.setText("Smiley");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(10, 10, 10)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 147, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel14, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel28, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton26, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton25, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 187, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(260, 260, 260)
.addComponent(jLabel12, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(194, 194, 194)
.addComponent(jLabel13, javax.swing.GroupLayout.PREFERRED_SIZE, 250, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(jButton27, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(669, 669, 669))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 989, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel29, javax.swing.GroupLayout.PREFERRED_SIZE, 559, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jLabel21, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel18, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel24, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 576, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jLabel15, javax.swing.GroupLayout.PREFERRED_SIZE, 576, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel30, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel25, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel22, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel19, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel16, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel31, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel26, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel23, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel20, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel17, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(321, 321, 321))
.addComponent(jTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, 989, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(804, 804, 804))
.addGroup(layout.createSequentialGroup()
.addGap(382, 382, 382)
.addComponent(jRadioButton5)
.addContainerGap(870, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 989, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(389, 389, 389)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 253, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel27)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel32, javax.swing.GroupLayout.PREFERRED_SIZE, 178, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(86, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGap(284, 284, 284)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 452, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 432, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 440, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 427, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox3, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox2, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox1, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox4, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(985, 985, 985))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 989, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(274, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, 989, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGap(118, 118, 118)
.addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 212, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(85, 85, 85)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(6, 6, 6)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(6, 6, 6)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(6, 6, 6)
.addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(6, 6, 6)
.addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(6, 6, 6)
.addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(6, 6, 6)
.addComponent(jButton7, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(6, 6, 6)
.addComponent(jButton8, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jButton17, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(6, 6, 6)
.addComponent(jButton18, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(6, 6, 6)
.addComponent(jButton19, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(6, 6, 6)
.addComponent(jButton20, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(6, 6, 6)
.addComponent(jButton21, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(6, 6, 6)
.addComponent(jButton22, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(6, 6, 6)
.addComponent(jButton23, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(6, 6, 6)
.addComponent(jButton24, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jButton9, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(6, 6, 6)
.addComponent(jButton10, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(6, 6, 6)
.addComponent(jButton11, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(6, 6, 6)
.addComponent(jButton12, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(6, 6, 6)
.addComponent(jButton13, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(6, 6, 6)
.addComponent(jButton14, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(6, 6, 6)
.addComponent(jButton15, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(6, 6, 6)
.addComponent(jButton16, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(52, 52, 52)))
.addGap(804, 804, 804))
.addGroup(layout.createSequentialGroup()
.addGap(404, 404, 404)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jCheckBox5)
.addComponent(jCheckBox4)
.addComponent(jCheckBox2)
.addComponent(jCheckBox3)
.addComponent(jCheckBox1)
.addComponent(jRadioButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 564, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jRadioButton2, javax.swing.GroupLayout.DEFAULT_SIZE, 564, Short.MAX_VALUE)
.addComponent(jRadioButton3, javax.swing.GroupLayout.DEFAULT_SIZE, 564, Short.MAX_VALUE)
.addComponent(jRadioButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 541, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(835, 835, 835))
);
layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jCheckBox1, jCheckBox2, jCheckBox3, jCheckBox4, jCheckBox5, jRadioButton1, jRadioButton2, jRadioButton3, jRadioButton4});
layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jLabel27, jTextField1, jTextField2, jTextField5, jTextField6});
layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jLabel16, jLabel19, jLabel22, jLabel25});
layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jLabel17, jLabel20, jLabel23, jLabel26});
layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jButton25, jButton26});
layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jButton1, jButton10, jButton11, jButton12, jButton13, jButton14, jButton15, jButton16, jButton17, jButton18, jButton19, jButton2, jButton20, jButton21, jButton22, jButton23, jButton24, jButton3, jButton4, jButton5, jButton6, jButton7, jButton8, jButton9});
layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jLabel24, jLabel29});
layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jLabel3, jLabel4, jLabel5, jLabel6});
layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jComboBox1, jComboBox2, jComboBox3, jComboBox4});
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel12, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel13, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton27, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel9, javax.swing.GroupLayout.DEFAULT_SIZE, 36, Short.MAX_VALUE)
.addComponent(jLabel7, javax.swing.GroupLayout.DEFAULT_SIZE, 36, Short.MAX_VALUE)
.addComponent(jLabel8, javax.swing.GroupLayout.DEFAULT_SIZE, 36, Short.MAX_VALUE)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 36, Short.MAX_VALUE)
.addComponent(jLabel14, javax.swing.GroupLayout.DEFAULT_SIZE, 36, Short.MAX_VALUE)
.addComponent(jLabel28, javax.swing.GroupLayout.DEFAULT_SIZE, 36, Short.MAX_VALUE)
.addComponent(jButton26, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton25, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel27, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 600, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jRadioButton1)
.addGap(9, 9, 9)
.addComponent(jRadioButton2)
.addGap(9, 9, 9)
.addComponent(jRadioButton3)
.addGap(9, 9, 9)
.addComponent(jRadioButton4)
.addGap(0, 0, 0)
.addComponent(jCheckBox1)
.addGap(9, 9, 9)
.addComponent(jCheckBox2, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(9, 9, 9)
.addComponent(jCheckBox3)
.addGap(9, 9, 9)
.addComponent(jCheckBox4)
.addGap(9, 9, 9)
.addComponent(jCheckBox5)
.addGap(0, 0, 0)
.addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(0, 0, 0)
.addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 294, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(51, 51, 51)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton7, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton8, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton9, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton10, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton11, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton12, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton13, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton14, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton15, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton16, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton17, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton18, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton19, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton20, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton21, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton22, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton23, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton24, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(3, 3, 3)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel15, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel16, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel17, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, 0)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel18, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel19, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel20, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, 0)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel21, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel22, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel23, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, 0)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel24, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel25, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel26, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, 0)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel29, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel30, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel31, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jRadioButton5))
.addGroup(layout.createSequentialGroup()
.addGap(30, 30, 30)
.addComponent(jLabel32, javax.swing.GroupLayout.PREFERRED_SIZE, 178, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {jLabel1, jLabel14, jLabel28, jLabel7, jLabel8, jLabel9});
layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {jLabel11, jLabel12});
layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {jLabel15, jLabel16, jLabel17, jLabel18, jLabel19, jLabel20, jLabel21, jLabel22, jLabel23, jLabel24, jLabel25, jLabel26, jLabel29, jLabel30, jLabel31});
layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {jButton25, jButton26});
layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {jButton1, jButton10, jButton11, jButton12, jButton13, jButton14, jButton15, jButton16, jButton17, jButton18, jButton19, jButton2, jButton20, jButton21, jButton22, jButton23, jButton24, jButton3, jButton4, jButton5, jButton6, jButton7, jButton8, jButton9});
layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {jComboBox1, jComboBox2, jComboBox3, jComboBox4, jLabel3, jLabel4, jLabel5, jLabel6});
}// </editor-fold>//GEN-END:initComponents
public int count1 () {
if (word.equals(word9)) {count=11; }
if (count==0) jTextField2.setText("Απομένουν 6 λάθος επιλογές");
if (count==1) {
jTextField2.setText("Απομένουν 5 λάθος επιλογές");
try {
URL url = new URL(URI1+"hangman/hanged1.jpg");
BufferedImage img = ImageIO.read(url);
Icon icon=new ImageIcon(img);
jLabel10.setIcon(icon);
} catch (IOException e) {}
}
if (count==2) {
jTextField2.setText("Απομένουν 4 λάθος επιλογές");
try {
URL url = new URL(URI1+"hangman/hanged2.jpg");
BufferedImage img = ImageIO.read(url);
Icon icon=new ImageIcon(img);
jLabel10.setIcon(icon);
} catch (IOException e) {}
}
if (count==3) {
jTextField2.setText("Απομένουν 3 λάθος επιλογές");
try {
URL url = new URL(URI1+"hangman/hanged3.jpg");
BufferedImage img = ImageIO.read(url);
Icon icon=new ImageIcon(img);
jLabel10.setIcon(icon);
} catch (IOException e) {}
}
if (count==4) {
jTextField2.setText("Απομένουν 2 λάθος επιλογές");
try {
URL url = new URL(URI1+"hangman/hanged4.jpg");
BufferedImage img = ImageIO.read(url);
Icon icon=new ImageIcon(img);
jLabel10.setIcon(icon);
} catch (IOException e) {}
}
if (count==5) {
jTextField2.setText("Απομένει 1 λάθος επιλογή");
try {
URL url = new URL(URI1+"hangman/hanged5.jpg");
BufferedImage img = ImageIO.read(url);
Icon icon=new ImageIcon(img);
jLabel10.setIcon(icon);
} catch (IOException e) {}
}
if (count==6) {
jButton1.setEnabled(false); jButton2.setEnabled(false); jButton3.setEnabled(false);
jButton4.setEnabled(false); jButton5.setEnabled(false); jButton6.setEnabled(false);
jButton7.setEnabled(false); jButton8.setEnabled(false); jButton9.setEnabled(false);
jButton10.setEnabled(false); jButton11.setEnabled(false); jButton12.setEnabled(false);
jButton13.setEnabled(false); jButton14.setEnabled(false); jButton15.setEnabled(false);
jButton16.setEnabled(false); jButton17.setEnabled(false); jButton18.setEnabled(false);
jButton19.setEnabled(false); jButton20.setEnabled(false); jButton21.setEnabled(false);
jButton22.setEnabled(false); jButton23.setEnabled(false); jButton24.setEnabled(false);
jTextField2.setText("Λυπάμαι δεν το βρήκες! Η σωστή απάντηση ήταν: "+word);
total++;
frozen = true;stopAnimation();
jButton25.setVisible(true);
correct[num]=false;
try {
URL url = new URL(URI1+"hangman/hanged6.jpg");
BufferedImage img = ImageIO.read(url);
Icon icon=new ImageIcon(img);
jLabel10.setIcon(icon);
} catch (IOException e) {}
jLabel15.setVisible(true);jLabel16.setVisible(true);jLabel17.setVisible(true);
jLabel15.setText("Για περισσότερες πληροφορίες σχετικά με: "+quest);
try {
URL url = new URL(URI1+"smileys/sad.png");
BufferedImage smiley = ImageIO.read(url);
java.awt.Image smiley2=smiley.getScaledInstance(150,150,BufferedImage.SCALE_SMOOTH);
Icon icon=new ImageIcon(smiley2);
jLabel32.setIcon(icon);
} catch (IOException e) {}
if (num==TimesPlayed-1) EndGame();
}
if (count==11) {
jButton1.setEnabled(false); jButton2.setEnabled(false); jButton3.setEnabled(false);
jButton4.setEnabled(false); jButton5.setEnabled(false); jButton6.setEnabled(false);
jButton7.setEnabled(false); jButton8.setEnabled(false); jButton9.setEnabled(false);
jButton10.setEnabled(false); jButton11.setEnabled(false); jButton12.setEnabled(false);
jButton13.setEnabled(false); jButton14.setEnabled(false); jButton15.setEnabled(false);
jButton16.setEnabled(false); jButton17.setEnabled(false); jButton18.setEnabled(false);
jButton19.setEnabled(false); jButton20.setEnabled(false); jButton21.setEnabled(false);
jButton22.setEnabled(false); jButton23.setEnabled(false); jButton24.setEnabled(false);
jTextField2.setText("Μπράβο, το βρήκες!"); score++; total++;
frozen = true;stopAnimation();
try {
URL url = new URL(URI1+"smileys/smile.png");
BufferedImage smiley = ImageIO.read(url);
java.awt.Image smiley2=smiley.getScaledInstance(150,150,BufferedImage.SCALE_SMOOTH);
Icon icon=new ImageIcon(smiley2);
jLabel32.setIcon(icon);
} catch (IOException e) {}
jButton25.setVisible(true);
correct[num]=true;
jLabel15.setVisible(true);jLabel16.setVisible(true);jLabel17.setVisible(true);
jLabel15.setText("Για περισσότερες πληροφορίες σχετικά με: "+quest);
if (num==TimesPlayed-1) EndGame();
}
jLabel14.setText("Βαθμολογία: "+score+" / "+total);
return count;
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
word3=word3.replace('Α', '*');
exist=0;
for (int i = 0; i < len; i++) {
if (word5[i]=='Α') {
word7[i]='Α';
exist=1;
}
}
if (exist==0) count=count+1;
word8="";
word9="";
for (int i = 0; i < len; i++) {
word8 = word8+word7[i]+' ';
word9 = word9+word7[i];
}
jTextField5.setText(word8);
jButton1.setEnabled(false);
count1();
}//GEN-LAST:event_jButton1ActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
word3=word3.replace('Β', '*');
exist=0;
for (int i = 0; i < len; i++) {
if (word5[i]=='Β') {
word7[i]='Β';
exist=1;
}
}
if (exist==0) count=count+1;
word8="";
word9="";
for (int i = 0; i < len; i++) {
word8 = word8+word7[i]+' ';
word9=word9+word7[i];
}
jTextField5.setText(word8);
jButton2.setEnabled(false);
count1();
}//GEN-LAST:event_jButton2ActionPerformed
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
word3=word3.replace('Γ', '*');
exist=0;
for (int i = 0; i < len; i++) {
if (word5[i]=='Γ') {
word7[i]='Γ';
exist=1;
}
}
if (exist==0) count=count+1;
word8="";
word9="";
for (int i = 0; i < len; i++) {
word8 = word8+word7[i]+' ';
word9=word9+word7[i];
}
jTextField5.setText(word8);
jButton3.setEnabled(false);
count1();
}//GEN-LAST:event_jButton3ActionPerformed
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
word3=word3.replace('Δ', '*');
exist=0;
for (int i = 0; i < len; i++) {
if (word5[i]=='Δ') {
word7[i]='Δ';
exist=1;
}
}
if (exist==0) count=count+1;
word8="";
word9="";
for (int i = 0; i < len; i++) {
word8 = word8+word7[i]+' ';
word9 = word9+word7[i];
}
jTextField5.setText(word8);
jButton4.setEnabled(false);
count1();
}//GEN-LAST:event_jButton4ActionPerformed
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
word3=word3.replace('Ε', '*');
exist=0;
for (int i = 0; i < len; i++) {
if (word5[i]=='Ε') {
word7[i]='Ε';
exist=1;
}
}
if (exist==0) count=count+1;
word8="";
word9="";
for (int i = 0; i < len; i++) {
word8 = word8+word7[i]+' ';
word9 = word9+word7[i];
}
jTextField5.setText(word8);
jButton5.setEnabled(false);
count1();
}//GEN-LAST:event_jButton5ActionPerformed
private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
word3=word3.replace('Ζ', '*');
exist=0;
for (int i = 0; i < len; i++) {
if (word5[i]=='Ζ') {
word7[i]='Ζ';
exist=1;
}
}
if (exist==0) count=count+1;
word8="";
word9="";
for (int i = 0; i < len; i++) {
word8 = word8+word7[i]+' ';
word9=word9+word7[i];
}
jTextField5.setText(word8);
jButton6.setEnabled(false);
count1();
}//GEN-LAST:event_jButton6ActionPerformed
private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed
word3=word3.replace('Η', '*');
exist=0;
for (int i = 0; i < len; i++) {
if (word5[i]=='Η') {
word7[i]='Η';
exist=1;
}
}
if (exist==0) count=count+1;
word8="";
word9="";
for (int i = 0; i < len; i++) {
word8 = word8+word7[i]+' ';
word9=word9+word7[i];
}
jTextField5.setText(word8);
jButton7.setEnabled(false);
count1();
}//GEN-LAST:event_jButton7ActionPerformed
private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton8ActionPerformed
word3=word3.replace('Θ', '*');
exist=0;
for (int i = 0; i < len; i++) {
if (word5[i]=='Θ') {
word7[i]='Θ';
exist=1;
}
}
if (exist==0) count=count+1;
word8="";
word9="";
for (int i = 0; i < len; i++) {
word8 = word8+word7[i]+' ';
word9=word9+word7[i];
}
jTextField5.setText(word8);
jButton8.setEnabled(false);
count1();
}//GEN-LAST:event_jButton8ActionPerformed
private void jButton9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton9ActionPerformed
word3=word3.replace('Ι', '*');
exist=0;
for (int i = 0; i < len; i++) {
if (word5[i]=='Ι') {
word7[i]='Ι';
exist=1;
}
}
if (exist==0) count=count+1;
word8="";
word9="";
for (int i = 0; i < len; i++) {
word8 = word8+word7[i]+' ';
word9=word9+word7[i];
}
jTextField5.setText(word8);
jButton9.setEnabled(false);
count1();
}//GEN-LAST:event_jButton9ActionPerformed
private void jButton10ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton10ActionPerformed
word3=word3.replace('Κ', '*');
exist=0;
for (int i = 0; i < len; i++) {
if (word5[i]=='Κ') {
word7[i]='Κ';
exist=1;
}
}
if (exist==0) count=count+1;
word8="";
word9="";
for (int i = 0; i < len; i++) {
word8 = word8+word7[i]+' ';
word9=word9+word7[i];
}
jTextField5.setText(word8);
jButton10.setEnabled(false);
count1();
}//GEN-LAST:event_jButton10ActionPerformed
private void jButton11ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton11ActionPerformed
word3=word3.replace('Λ', '*');
exist=0;
for (int i = 0; i < len; i++) {
if (word5[i]=='Λ') {
word7[i]='Λ';
exist=1;
}
}
if (exist==0) count=count+1;
word8="";
word9="";
for (int i = 0; i < len; i++) {
word8 = word8+word7[i]+' ';
word9=word9+word7[i];
}
jTextField5.setText(word8);
jButton11.setEnabled(false);
count1();
}//GEN-LAST:event_jButton11ActionPerformed
private void jButton12ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton12ActionPerformed
word3=word3.replace('Μ', '*');
exist=0;
for (int i = 0; i < len; i++) {
if (word5[i]=='Μ') {
word7[i]='Μ';
exist=1;
}
}
if (exist==0) count=count+1;
word8="";
word9="";
for (int i = 0; i < len; i++) {
word8 = word8+word7[i]+' ';
word9=word9+word7[i];
}
jTextField5.setText(word8);
jButton12.setEnabled(false);
count1();
}//GEN-LAST:event_jButton12ActionPerformed
private void jButton13ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton13ActionPerformed
word3=word3.replace('Ν', '*');
exist=0;
for (int i = 0; i < len; i++) {
if (word5[i]=='Ν') {
word7[i]='Ν';
exist=1;
}
}
if (exist==0) count=count+1;
word8="";
word9="";
for (int i = 0; i < len; i++) {
word8 = word8+word7[i]+' ';
word9=word9+word7[i];
}
jTextField5.setText(word8);
jButton13.setEnabled(false);
count1();
}//GEN-LAST:event_jButton13ActionPerformed
private void jButton14ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton14ActionPerformed
word3=word3.replace('Ξ', '*');
exist=0;
for (int i = 0; i < len; i++) {
if (word5[i]=='Ξ') {
word7[i]='Ξ';
exist=1;
}
}
if (exist==0) count=count+1;
word8="";
word9="";
for (int i = 0; i < len; i++) {
word8 = word8+word7[i]+' ';
word9=word9+word7[i];
}
jTextField5.setText(word8);
jButton14.setEnabled(false);
count1();
}//GEN-LAST:event_jButton14ActionPerformed
private void jButton15ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton15ActionPerformed
word3=word3.replace('Ο', '*');
exist=0;
for (int i = 0; i < len; i++) {
if (word5[i]=='Ο') {
word7[i]='Ο';
exist=1;
}
}
if (exist==0) count=count+1;
word8="";
word9="";
for (int i = 0; i < len; i++) {
word8 = word8+word7[i]+' ';
word9=word9+word7[i];
}
jTextField5.setText(word8);
jButton15.setEnabled(false);
count1();
}//GEN-LAST:event_jButton15ActionPerformed
private void jButton16ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton16ActionPerformed
word3=word3.replace('Π', '*');
exist=0;
for (int i = 0; i < len; i++) {
if (word5[i]=='Π') {
word7[i]='Π';
exist=1;
}
}
if (exist==0) count=count+1;
word8="";
word9="";
for (int i = 0; i < len; i++) {
word8 = word8+word7[i]+' ';
word9=word9+word7[i];
}
jTextField5.setText(word8);
jButton16.setEnabled(false);
count1();
}//GEN-LAST:event_jButton16ActionPerformed
private void jButton17ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton17ActionPerformed
word3=word3.replace('Ρ', '*');
exist=0;
for (int i = 0; i < len; i++) {
if (word5[i]=='Ρ') {
word7[i]='Ρ';
exist=1;
}
}
if (exist==0) count=count+1;
word8="";
word9="";
for (int i = 0; i < len; i++) {
word8 = word8+word7[i]+' ';
word9=word9+word7[i];
}
jTextField5.setText(word8);
jButton17.setEnabled(false);
count1();
}//GEN-LAST:event_jButton17ActionPerformed
private void jButton18ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton18ActionPerformed
word3=word3.replace('Σ', '*');
exist=0;
for (int i = 0; i < len; i++) {
if (word5[i]=='Σ') {
word7[i]='Σ';
exist=1;
}
}
if (exist==0) count=count+1;
word8="";
word9="";
for (int i = 0; i < len; i++) {
word8 = word8+word7[i]+' ';
word9=word9+word7[i];
}
jTextField5.setText(word8);
jButton18.setEnabled(false);
count1();
}//GEN-LAST:event_jButton18ActionPerformed
private void jButton19ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton19ActionPerformed
word3=word3.replace('Τ', '*');
exist=0;
for (int i = 0; i < len; i++) {
if (word5[i]=='Τ') {
word7[i]='Τ';
exist=1;
}
}
if (exist==0) count=count+1;
word8="";
word9="";
for (int i = 0; i < len; i++) {
word8 = word8+word7[i]+' ';
word9=word9+word7[i];
}
jTextField5.setText(word8);
jButton19.setEnabled(false);
count1();
}//GEN-LAST:event_jButton19ActionPerformed
private void jButton20ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton20ActionPerformed
word3=word3.replace('Υ', '*');
exist=0;
for (int i = 0; i < len; i++) {
if (word5[i]=='Υ') {
word7[i]='Υ';
exist=1;
}
}
if (exist==0) count=count+1;
word8="";
word9="";
for (int i = 0; i < len; i++) {
word8 = word8+word7[i]+' ';
word9=word9+word7[i];
}
jTextField5.setText(word8);
jButton20.setEnabled(false);
count1();
}//GEN-LAST:event_jButton20ActionPerformed
private void jButton21ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton21ActionPerformed
word3=word3.replace('Φ', '*');
exist=0;
for (int i = 0; i < len; i++) {
if (word5[i]=='Φ') {
word7[i]='Φ';
exist=1;
}
}
if (exist==0) count=count+1;
word8="";
word9="";
for (int i = 0; i < len; i++) {
word8 = word8+word7[i]+' ';
word9=word9+word7[i];
}
jTextField5.setText(word8);
jButton21.setEnabled(false);
count1();
}//GEN-LAST:event_jButton21ActionPerformed
private void jButton22ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton22ActionPerformed
word3=word3.replace('Χ', '*');
exist=0;
for (int i = 0; i < len; i++) {
if (word5[i]=='Χ') {
word7[i]='Χ';
exist=1;
}
}
if (exist==0) count=count+1;
word8="";
word9="";
for (int i = 0; i < len; i++) {
word8 = word8+word7[i]+' ';
word9=word9+word7[i];
}
jTextField5.setText(word8);
jButton22.setEnabled(false);
count1();
}//GEN-LAST:event_jButton22ActionPerformed
private void jButton23ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton23ActionPerformed
word3=word3.replace('Ψ', '*');
exist=0;
for (int i = 0; i < len; i++) {
if (word5[i]=='Ψ') {
word7[i]='Ψ';
exist=1;
}
}
if (exist==0) count=count+1;
word8="";
word9="";
for (int i = 0; i < len; i++) {
word8 = word8+word7[i]+' ';
word9=word9+word7[i];
}
jTextField5.setText(word8);
jButton23.setEnabled(false);
count1();
}//GEN-LAST:event_jButton23ActionPerformed
private void jButton24ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton24ActionPerformed
word3=word3.replace('Ω', '*');
exist=0;
for (int i = 0; i < len; i++) {
if (word5[i]=='Ω') {
word7[i]='Ω';
exist=1;
}
}
if (exist==0) count=count+1;
word8="";
word9="";
for (int i = 0; i < len; i++) {
word8 = word8+word7[i]+' ';
word9=word9+word7[i];
}
jTextField5.setText(word8);
jButton24.setEnabled(false);
count1();
}//GEN-LAST:event_jButton24ActionPerformed
private void jTextField5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField5ActionPerformed
}//GEN-LAST:event_jTextField5ActionPerformed
private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton1ActionPerformed
frozen = true;
stopAnimation();
String b= answ1;
jRadioButton1.setEnabled(false);
jRadioButton2.setEnabled(false);
jRadioButton3.setEnabled(false);
jRadioButton4.setEnabled(false);
if (b.equals(answ)) {
jTextField2.setText("Μπράβο, το βρήκες!");
score++;correct[num]=true;
try {
URL url = new URL(URI1+"smileys/smile.png");
BufferedImage smiley = ImageIO.read(url);
java.awt.Image smiley2=smiley.getScaledInstance(150,150,BufferedImage.SCALE_SMOOTH);
Icon icon=new ImageIcon(smiley2);
jLabel32.setIcon(icon);
} catch (IOException e) {}
}
else {
if (game==5 ) jTextField2.setText("Λυπάμαι, λάθος! Η σωστή απάντηση είναι: "+answw);
else if (game!=5) jTextField2.setText("Λυπάμαι, λάθος! Η σωστή απάντηση είναι: "+answ);
correct[num]=false;
try {
URL url = new URL(URI1+"smileys/sad.png");
BufferedImage smiley = ImageIO.read(url);
java.awt.Image smiley2=smiley.getScaledInstance(150,150,BufferedImage.SCALE_SMOOTH);
Icon icon=new ImageIcon(smiley2);
jLabel32.setIcon(icon);
} catch (IOException e) {}
}
total++;
if (game==1){
jRadioButton1.setText(answ1);
jRadioButton2.setText(answ2);
jRadioButton3.setText(answ3);
jRadioButton4.setText(answ4);
}
jLabel14.setText("Βαθμολογία: "+score+" / "+total);
jButton25.setVisible(true);
jLabel15.setVisible(true);jLabel16.setVisible(true);jLabel17.setVisible(true);
jLabel15.setText("Για περισσότερες πληροφορίες σχετικά με: "+quest);
if (num==TimesPlayed-1) EndGame();
}//GEN-LAST:event_jRadioButton1ActionPerformed
private void jRadioButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton2ActionPerformed
frozen = true;
stopAnimation();
String b= answ2;
jRadioButton1.setEnabled(false);
jRadioButton2.setEnabled(false);
jRadioButton3.setEnabled(false);
jRadioButton4.setEnabled(false);
if (b.equals(answ)) {
jTextField2.setText("Μπράβο, το βρήκες!");
score++;correct[num]=true;
try {
URL url = new URL(URI1+"smileys/smile.png");
BufferedImage smiley = ImageIO.read(url);
java.awt.Image smiley2=smiley.getScaledInstance(150,150,BufferedImage.SCALE_SMOOTH);
Icon icon=new ImageIcon(smiley2);
jLabel32.setIcon(icon);
} catch (IOException e) {}
}
else {
if (game==5 ) jTextField2.setText("Λυπάμαι, λάθος! Η σωστή απάντηση είναι: "+answw);
else if (game!=5) jTextField2.setText("Λυπάμαι, λάθος! Η σωστή απάντηση είναι: "+answ);
correct[num]=false;
try {
URL url = new URL(URI1+"smileys/sad.png");
BufferedImage smiley = ImageIO.read(url);
java.awt.Image smiley2=smiley.getScaledInstance(150,150,BufferedImage.SCALE_SMOOTH);
Icon icon=new ImageIcon(smiley2);
jLabel32.setIcon(icon);
} catch (IOException e) {}
}
total++;
if (game==1){
jRadioButton1.setText(answ1);
jRadioButton2.setText(answ2);
jRadioButton3.setText(answ3);
jRadioButton4.setText(answ4);
}
jLabel14.setText("Βαθμολογία: "+score+" / "+total);
jButton25.setVisible(true);
jLabel15.setVisible(true);jLabel16.setVisible(true);jLabel17.setVisible(true);
jLabel15.setText("Για περισσότερες πληροφορίες σχετικά με: "+quest);
if (num==TimesPlayed-1) EndGame();
}//GEN-LAST:event_jRadioButton2ActionPerformed
private void jRadioButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton3ActionPerformed
frozen = true;
stopAnimation();
String b= answ3;
jRadioButton1.setEnabled(false);
jRadioButton2.setEnabled(false);
jRadioButton3.setEnabled(false);
jRadioButton4.setEnabled(false);
if (b.equals(answ)) {
jTextField2.setText("Μπράβο, το βρήκες!");
score++;correct[num]=true;
try {
URL url = new URL(URI1+"smileys/smile.png");
BufferedImage smiley = ImageIO.read(url);
java.awt.Image smiley2=smiley.getScaledInstance(150,150,BufferedImage.SCALE_SMOOTH);
Icon icon=new ImageIcon(smiley2);
jLabel32.setIcon(icon);
} catch (IOException e) {}
}
else {
if (game==5 ) jTextField2.setText("Λυπάμαι, λάθος! Η σωστή απάντηση είναι: "+answw);
else if (game!=5) jTextField2.setText("Λυπάμαι, λάθος! Η σωστή απάντηση είναι: "+answ);
correct[num]=false;
try {
URL url = new URL(URI1+"smileys/sad.png");
BufferedImage smiley = ImageIO.read(url);
java.awt.Image smiley2=smiley.getScaledInstance(150,150,BufferedImage.SCALE_SMOOTH);
Icon icon=new ImageIcon(smiley2);
jLabel32.setIcon(icon);
} catch (IOException e) {}
}
total++;
if (game==1){
jRadioButton1.setText(answ1);
jRadioButton2.setText(answ2);
jRadioButton3.setText(answ3);
jRadioButton4.setText(answ4);
}
jLabel14.setText("Βαθμολογία: "+score+" / "+total);
jButton25.setVisible(true);
jLabel15.setVisible(true);jLabel16.setVisible(true);jLabel17.setVisible(true);
jLabel15.setText("Για περισσότερες πληροφορίες σχετικά με: "+quest);
if (num==TimesPlayed-1) EndGame();
}//GEN-LAST:event_jRadioButton3ActionPerformed
private void jRadioButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton4ActionPerformed
frozen = true;
stopAnimation();
String b= answ4;
jRadioButton1.setEnabled(false);
jRadioButton2.setEnabled(false);
jRadioButton3.setEnabled(false);
jRadioButton4.setEnabled(false);
if (b.equals(answ)) {
jTextField2.setText("Μπράβο, το βρήκες!");
score++;correct[num]=true;
try {
URL url = new URL(URI1+"smileys/smile.png");
BufferedImage smiley = ImageIO.read(url);
java.awt.Image smiley2=smiley.getScaledInstance(150,150,BufferedImage.SCALE_SMOOTH);
Icon icon=new ImageIcon(smiley2);
jLabel32.setIcon(icon);
} catch (IOException e) {}
}
else {
if (game==5 ) jTextField2.setText("Λυπάμαι, λάθος! Η σωστή απάντηση είναι: "+answw);
else if (game!=5) jTextField2.setText("Λυπάμαι, λάθος! Η σωστή απάντηση είναι: "+answ);
correct[num]=false;
try {
URL url = new URL(URI1+"smileys/sad.png");
BufferedImage smiley = ImageIO.read(url);
java.awt.Image smiley2=smiley.getScaledInstance(150,150,BufferedImage.SCALE_SMOOTH);
Icon icon=new ImageIcon(smiley2);
jLabel32.setIcon(icon);
} catch (IOException e) {}
}
total++;
if (game==1){
jRadioButton1.setText(answ1);
jRadioButton2.setText(answ2);
jRadioButton3.setText(answ3);
jRadioButton4.setText(answ4);
}
jLabel14.setText("Βαθμολογία: "+score+" / "+total);
jButton25.setVisible(true);
jLabel15.setVisible(true);jLabel16.setVisible(true);jLabel17.setVisible(true);
jLabel15.setText("Για περισσότερες πληροφορίες σχετικά με: "+quest);
if (num==TimesPlayed-1) EndGame();
}//GEN-LAST:event_jRadioButton4ActionPerformed
private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed
}//GEN-LAST:event_jComboBox1ActionPerformed
private void jComboBox2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox2ActionPerformed
}//GEN-LAST:event_jComboBox2ActionPerformed
private void jButton25ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton25ActionPerformed
DeActivateAll();
ChooseGame();
}//GEN-LAST:event_jButton25ActionPerformed
private void jLabel16MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel16MouseClicked
String command="cmd.exe /c start ";
String site=command+dbpedia;
try {
Process pc = Runtime.getRuntime().exec(site);
} catch (IOException ex) {JOptionPane.showMessageDialog(this, "Ο σύνδεσμος δε λειτουργεί!");}
}//GEN-LAST:event_jLabel16MouseClicked
private void jLabel17MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel17MouseClicked
String command="cmd.exe /c start ";
String site=command+wiki;
try {
Process pc = Runtime.getRuntime().exec(site);
} catch (IOException ex) {JOptionPane.showMessageDialog(this, "Ο σύνδεσμος δε λειτουργεί!");}
}//GEN-LAST:event_jLabel17MouseClicked
private void jButton26ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton26ActionPerformed
frozen = true;
stopAnimation();
double sc = 0.0;
jLabel15.setVisible(true); jLabel16.setVisible(true); jLabel17.setVisible(true);
jLabel18.setVisible(true);jLabel19.setVisible(true);jLabel20.setVisible(true);
jComboBox1.setEnabled(false);jComboBox2.setEnabled(false);
jComboBox3.setEnabled(false);jComboBox4.setEnabled(false);
jButton26.setEnabled(false);
jCheckBox1.setEnabled(false);jCheckBox2.setEnabled(false);jCheckBox3.setEnabled(false);
jCheckBox4.setEnabled(false);jCheckBox5.setEnabled(false);
if (game==6) {
jLabel15.setText("Για περισσότερες πληροφορίες σχετικά με: " + quest);
jLabel18.setText("Για περισσότερες πληροφορίες σχετικά με: "+quest2);
if (jComboBox1.getSelectedItem() == answ1) {
//System.out.println("Βρήκες το 1ο");
if (comboindex > 4) sc = sc + 0.25;
else if (comboindex == 4) sc = sc + 1.0 / 3.0;
else if (comboindex == 3) sc = sc + 0.5;
}
if (jComboBox2.getSelectedItem() == answ2) {
//System.out.println("Βρήκες το 2ο");
if (comboindex > 4) sc = sc + 0.25;
else if (comboindex == 4) sc = sc + 1.0 / 3.0;
else if (comboindex == 3) sc = sc + 0.5;
}
if (comboindex > 3) {
if (jComboBox3.getSelectedItem() == answ3) {
//System.out.println("Βρήκες το 3ο");
if (comboindex > 4) sc = sc + 0.25;
else if (comboindex == 4) sc = sc + 1.0 / 3.0;
}
}
if (comboindex > 4) {
if (jComboBox4.getSelectedItem() == answ4) {
//System.out.println("Βρήκες το 4ο");
sc = sc + 0.25;
}
}
if (sc == 1) {
score++;
jTextField2.setText("Μπράβο, το βρήκες! ");
jTextField6.setText("Πήρες 1 βαθμό! ");
correct[num] = true;
try {
URL url = new URL(URI1+"smileys/smile.png");
BufferedImage smiley = ImageIO.read(url);
java.awt.Image smiley2=smiley.getScaledInstance(150,150,BufferedImage.SCALE_SMOOTH);
Icon icon=new ImageIcon(smiley2);
jLabel32.setIcon(icon);
} catch (IOException e) {}
}
else {
jTextField2.setText("Λυπάμαι, λάθος! Η σωστή απάντηση είναι:");
jTextField6.setVisible(true);
String text = "";
if (comboindex > 4) text = "1 - " + answ1 + ", 2 - " + answ2 + ", 3 - " + answ3 + ", 4 - " + answ4;
else if (comboindex == 4) text = "1 - " + answ1 + ", 2 - " + answ2 + ", 3 - " + answ3;
else if (comboindex == 3) text = "1 - " + answ1 + ", 2 - " + answ2;
jTextField6.setText(text);
correct[num] = false;
try {
URL url = new URL(URI1+"smileys/sad.png");
BufferedImage smiley = ImageIO.read(url);
java.awt.Image smiley2=smiley.getScaledInstance(150,150,BufferedImage.SCALE_SMOOTH);
Icon icon=new ImageIcon(smiley2);
jLabel32.setIcon(icon);
} catch (IOException e) {}
}
if (comboindex>3) {
jLabel21.setVisible(true);jLabel22.setVisible(true);jLabel23.setVisible(true);
jLabel21.setText("Για περισσότερες πληροφορίες σχετικά με: "+quest3);
}
if (comboindex>4) {
jLabel24.setVisible(true);jLabel25.setVisible(true);jLabel26.setVisible(true);
jLabel24.setText("Για περισσότερες πληροφορίες σχετικά με: "+quest4);
}
}
else if (game==7) {
sc=0;
int selectedanswers=0;
if (jCheckBox1.isSelected()) selectedanswers=selectedanswers+1;
if (jCheckBox2.isSelected()) selectedanswers=selectedanswers+1;
if (jCheckBox3.isSelected()) selectedanswers=selectedanswers+1;
if (jCheckBox4.isSelected()) selectedanswers=selectedanswers+1;
if (jCheckBox5.isSelected()) selectedanswers=selectedanswers+1;
if (jCheckBox1.isSelected() && quest.equals(duplicatequestion)) sc=sc+1.0/numofcorrect;
if (jCheckBox2.isSelected() && quest2.equals(duplicatequestion)) sc=sc+1.0/numofcorrect;
if (jCheckBox3.isSelected() && quest3.equals(duplicatequestion)) sc=sc+1.0/numofcorrect;
if (jCheckBox4.isSelected() && quest4.equals(duplicatequestion)) sc=sc+1.0/numofcorrect;
if (jCheckBox5.isSelected() && quest5.equals(duplicatequestion)) sc=sc+1.0/numofcorrect;
if (jCheckBox1.isSelected() && !quest.equals(duplicatequestion)) sc=sc-1.0/numofcorrect;
if (jCheckBox2.isSelected() && !quest2.equals(duplicatequestion)) sc=sc-1.0/numofcorrect;
if (jCheckBox3.isSelected() && !quest3.equals(duplicatequestion)) sc=sc-1.0/numofcorrect;
if (jCheckBox4.isSelected() && !quest4.equals(duplicatequestion)) sc=sc-1.0/numofcorrect;
if (jCheckBox5.isSelected() && !quest5.equals(duplicatequestion)) sc=sc-1.0/numofcorrect;
if (sc==1 && selectedanswers==numofcorrect) {
score++;
jTextField2.setText("Μπράβο, το βρήκες! ");
jTextField6.setText("Πήρες 1 βαθμό! ");
correct[num] = true;
try {
URL url = new URL(URI1+"smileys/smile.png");
BufferedImage smiley = ImageIO.read(url);
java.awt.Image smiley2=smiley.getScaledInstance(150,150,BufferedImage.SCALE_SMOOTH);
Icon icon=new ImageIcon(smiley2);
jLabel32.setIcon(icon);
} catch (IOException e) {}
}
else {
jTextField2.setText("Λυπάμαι, λάθος! Οι σωστές απαντήσεις είναι:");
if (numofcorrect == 3) {jTextField2.setText("Λυπάμαι, λάθος!"); correctanswers = "Οι σωστές απαντήσεις είναι: " + correctanswers;}
else if (numofcorrect== 2) {jTextField2.setText("Λυπάμαι, λάθος!"); correctanswers = "Οι σωστές απαντήσεις είναι: " + correctanswers;}
else if (numofcorrect== 1) {jTextField2.setText("Λυπάμαι, λάθος!"); correctanswers = "Η σωστή απάντηση είναι: "+ correctanswers; }
jTextField6.setText(correctanswers);
correct[num] = false;
try {
URL url = new URL(URI1+"smileys/sad.png");
BufferedImage smiley = ImageIO.read(url);
java.awt.Image smiley2=smiley.getScaledInstance(150,150,BufferedImage.SCALE_SMOOTH);
Icon icon=new ImageIcon(smiley2);
jLabel32.setIcon(icon);
} catch (IOException e) {}
}
jLabel15.setText("Για περισσότερες πληροφορίες σχετικά με: " + answ);
jLabel18.setText("Για περισσότερες πληροφορίες σχετικά με: "+answ2);
if (checkindex>3) {
jLabel21.setVisible(true);jLabel22.setVisible(true);jLabel23.setVisible(true);
jLabel21.setText("Για περισσότερες πληροφορίες σχετικά με: "+answ3);
}
if (checkindex>4) {
jLabel24.setVisible(true);jLabel25.setVisible(true);jLabel26.setVisible(true);
jLabel24.setText("Για περισσότερες πληροφορίες σχετικά με: "+answ4);
}
if (checkindex>5) {
jLabel29.setVisible(true);jLabel30.setVisible(true);jLabel31.setVisible(true);
jLabel29.setText("Για περισσότερες πληροφορίες σχετικά με: "+answ5);
}
}
total++;
// System.out.println("Score=" + sc);
jLabel14.setText("Βαθμολογία: " + score + " / " + total);
jButton25.setVisible(true);jButton26.setVisible(false);
if (num == TimesPlayed - 1) EndGame();
}//GEN-LAST:event_jButton26ActionPerformed
private void jLabel19MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel19MouseClicked
String command="cmd.exe /c start ";
String site=command+dbpedia2;
try {
Process pc = Runtime.getRuntime().exec(site);
} catch (IOException ex) {JOptionPane.showMessageDialog(this, "Ο σύνδεσμος δε λειτουργεί!");}
}//GEN-LAST:event_jLabel19MouseClicked
private void jLabel22MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel22MouseClicked
String command="cmd.exe /c start ";
String site=command+dbpedia3;
try {
Process pc = Runtime.getRuntime().exec(site);
} catch (IOException ex) {JOptionPane.showMessageDialog(this, "Ο σύνδεσμος δε λειτουργεί!");}
}//GEN-LAST:event_jLabel22MouseClicked
private void jLabel23MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel23MouseClicked
String command="cmd.exe /c start ";
String site=command+wiki3;
try {
Process pc = Runtime.getRuntime().exec(site);
} catch (IOException ex) {JOptionPane.showMessageDialog(this, "Ο σύνδεσμος δε λειτουργεί!");}
}//GEN-LAST:event_jLabel23MouseClicked
private void jLabel25MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel25MouseClicked
String command="cmd.exe /c start ";
String site=command+dbpedia4;
try {
Process pc = Runtime.getRuntime().exec(site);
} catch (IOException ex) {JOptionPane.showMessageDialog(this, "Ο σύνδεσμος δε λειτουργεί!");}
}//GEN-LAST:event_jLabel25MouseClicked
private void jLabel26MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel26MouseClicked
String command="cmd.exe /c start ";
String site=command+wiki4;
try {
Process pc = Runtime.getRuntime().exec(site);
} catch (IOException ex) {JOptionPane.showMessageDialog(this, "Ο σύνδεσμος δε λειτουργεί!");}
}//GEN-LAST:event_jLabel26MouseClicked
private void jLabel20MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel20MouseClicked
String command="cmd.exe /c start ";
String site=command+wiki2;
try {
Process pc = Runtime.getRuntime().exec(site);
} catch (IOException ex) {JOptionPane.showMessageDialog(this, "Ο σύνδεσμος δε λειτουργεί!");}
}//GEN-LAST:event_jLabel20MouseClicked
private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField2ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jTextField2ActionPerformed
private void jCheckBox2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBox2ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jCheckBox2ActionPerformed
private void jLabel30MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel30MouseClicked
String command="cmd.exe /c start ";
String site=command+dbpedia5;
try {
Process pc = Runtime.getRuntime().exec(site);
} catch (IOException ex) {JOptionPane.showMessageDialog(this, "Ο σύνδεσμος δε λειτουργεί!");}
}//GEN-LAST:event_jLabel30MouseClicked
private void jLabel31MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel31MouseClicked
String command="cmd.exe /c start ";
String site=command+wiki5;
try {
Process pc = Runtime.getRuntime().exec(site);
} catch (IOException ex) {JOptionPane.showMessageDialog(this, "Ο σύνδεσμος δε λειτουργεί!");}
}//GEN-LAST:event_jLabel31MouseClicked
private void jRadioButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton5ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jRadioButton5ActionPerformed
private void jButton27MouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton27MouseEntered
//if (mouseoverbutton==0) {JOptionPane.showMessageDialog(this, "Αν πατήσεις το X θα τερματιστεί το πρόγραμμα!"); mouseoverbutton=1;}
jButton27.setToolTipText("Αν πατήσεις το X, το παιχνίδι θα τερματιστεί!");
}//GEN-LAST:event_jButton27MouseEntered
private void jButton27MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton27MouseClicked
Object[] options = {"Ναι","Όχι"};
int more = JOptionPane.showOptionDialog(this,"Θέλεις να τερματίσεις το παιχνίδι;","'Εφτασε το τέλος!",
JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE,null,options,options[1]);
System.out.println("more = " + more);
if (more==0) {GameOver=1; EndGame();}
else if (more==1 && !jButton25.isVisible()){frozen=false;startAnimation();}
}//GEN-LAST:event_jButton27MouseClicked
private void jButton27ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton27ActionPerformed
frozen = true;
stopAnimation();
}//GEN-LAST:event_jButton27ActionPerformed
private void MultipleChoice() {
MultipleChoiceActivate();
jRadioButton5.setSelected(true);
jTextField2.setText("Επέλεξε μία απάντηση!");
jTextField1.setHorizontalAlignment(JTextField.CENTER);
jTextField2.setHorizontalAlignment(JTextField.CENTER);
ReadFromFile GetData = new ReadFromFile();
String[][] selection;
int index,question1,answer1;
int nextInt=0,nextInt2=0,nextInt3=0,nextInt4=0;
Random generator = new Random();
do {
selection=GetData.Selection(data); index=GetData.index();
} while (index==2);
String selectedcategory=GetData.selectedcategory();
jLabel28.setText("Κατηγορία: "+selectedcategory);
Category[num]=selectedcategory;
frozen=false;
String str;
int fps = 0;
str = getParameter("fps");
try {
if (str != null) {
fps = Integer.parseInt(str);
}
} catch (Exception e) {}
int delay = (fps > 0) ? (1000 / fps) : 1000;
timer = new Timer(delay, this);
timer.setInitialDelay(0);
timer.setCoalesce(true);
startAnimation();
question1 = generator.nextInt(2);
do {
answer1 = generator.nextInt(2);
} while (answer1==question1);
do {
nextInt = generator.nextInt(index);
} while (nextInt==0);
jTextField1.setText(selection[0][question1] +selection[nextInt][question1]+";");
int change;
do {
nextInt2 = generator.nextInt(index); change=0;
for (int i=0;i<index;i++) {
if (selection[nextInt2][answer1].equals(selection[i][answer1]) && selection[i][question1].equals(selection[nextInt][question1])) change=1;}
} while (selection[nextInt2][0].equals(selection[nextInt][0]) || selection[nextInt2][1].equals(selection[nextInt][1]) || nextInt2==0 || change==1);
if (index>3) {
do {
nextInt3 = generator.nextInt(index); change=0;
for (int i=0;i<index;i++) {
if (selection[nextInt3][answer1].equals(selection[i][answer1]) && selection[i][question1].equals(selection[nextInt][question1])) change=1;}
} while (selection[nextInt3][0].equals(selection[nextInt][0]) || selection[nextInt3][0].equals(selection[nextInt2][0]) ||
selection[nextInt3][1].equals(selection[nextInt][1]) || selection[nextInt3][1].equals(selection[nextInt2][1]) ||
nextInt3==0 || change==1);
if (index>4) {
do {
nextInt4 = generator.nextInt(index); change=0;
for (int i=0;i<index;i++) {
if (selection[nextInt4][answer1].equals(selection[i][answer1]) && selection[i][question1].equals(selection[nextInt][question1])) change=1;}
} while (selection[nextInt4][0].equals(selection[nextInt][0]) || selection[nextInt4][0].equals(selection[nextInt2][0]) || selection[nextInt4][0].equals(selection[nextInt3][0]) ||
selection[nextInt4][1].equals(selection[nextInt][1]) || selection[nextInt4][1].equals(selection[nextInt2][1]) || selection[nextInt4][1].equals(selection[nextInt3][1]) ||
nextInt4==0 || change==1);
}
}
ArrayList nums = new ArrayList();
nums.add(nextInt);
nums.add(nextInt2);
if (index>3) nums.add(nextInt3);
if (index>4) nums.add(nextInt4);
Collections.shuffle(nums);
int ind[]= {nextInt,nextInt2,nextInt3,nextInt4};
ind[0]=Integer.parseInt(nums.get(0).toString());
ind[1]=Integer.parseInt(nums.get(1).toString());
if (index>3) ind[2]=Integer.parseInt(nums.get(2).toString());
if (index>4) ind[3]=Integer.parseInt(nums.get(3).toString());
answ1=selection[ind[0]][answer1];
answ2=selection[ind[1]][answer1];
if (index>3) answ3=selection[ind[2]][answer1];
if (index>4) answ4=selection[ind[3]][answer1];
jRadioButton3.setVisible(false);
jRadioButton4.setVisible(false);
jRadioButton5.setVisible(false);
if (index>3) jRadioButton3.setVisible(true); jRadioButton3.setText(answ3);
if (index>4) jRadioButton4.setVisible(true); jRadioButton4.setText(answ4);
jRadioButton1.setText(answ1);
jRadioButton2.setText(answ2);
jRadioButton1.setEnabled(true);
jRadioButton2.setEnabled(true);
jRadioButton3.setEnabled(true);
jRadioButton4.setEnabled(true);
answ=selection[nextInt][answer1];
quest=selection[nextInt][0];
dbpedia=selection[nextInt][2];
wiki=selection[nextInt][3];
question[num]="Η ερώτηση ήταν: "+selection[0][question1] +selection[nextInt][question1]+";";
answer[num]="Η σωστή απάντηση ήταν: " +answ;
}
public void Anagram(){
frozen=false;
String str;
int fps = 0;
str = getParameter("fps");
try {
if (str != null) {
fps = Integer.parseInt(str);
}
} catch (Exception e) {}
int delay = (fps > 0) ? (1000 / fps) : 1000;
timer = new Timer(delay, this);
timer.setInitialDelay(0);
timer.setCoalesce(true);
startAnimation();
MultipleChoiceActivate();
jRadioButton5.setSelected(true);
jTextField2.setText("Οι απαντήσεις είναι αναγραμματισμένες! Υπάρχει μόνο 1 σωστή επιλογή!");
jTextField1.setHorizontalAlignment(JTextField.CENTER);
jTextField2.setHorizontalAlignment(JTextField.CENTER);
ReadFromFile GetData = new ReadFromFile();
String[][] selection;
int index,anagram,question1,answer1;
int nextInt=0,nextInt2=0,nextInt3=0,nextInt4=0;
Random generator = new Random();
do {
selection=GetData.Selection(data); index=GetData.index();anagram = GetData.anagram();//indexwithoutduplicates=GetData.indexwithoutduplicates();
} while (index==2);
String selectedcategory=GetData.selectedcategory();
jLabel28.setText("Κατηγορία: "+selectedcategory);
Category[num]=selectedcategory;
question1 = generator.nextInt(2);
if (anagram==0) question1=1;
do {
answer1 = generator.nextInt(2);
} while (answer1==question1);
do {
nextInt = generator.nextInt(index);
} while (nextInt==0);
jTextField1.setText(selection[0][question1] +selection[nextInt][question1]+";");
int change;
do {
nextInt2 = generator.nextInt(index); change=0;
for (int i=0;i<index;i++) {
if (selection[nextInt2][answer1].equals(selection[i][answer1]) && selection[i][question1].equals(selection[nextInt][question1])) change=1;}
} while (selection[nextInt2 ][0].equals(selection[nextInt][0]) || selection[nextInt2 ][1].equals(selection[nextInt][1]) || nextInt2==0 || change==1);
if (index>3) {
do {
nextInt3 = generator.nextInt(index); change=0;
for (int i=0;i<index;i++) {
if (selection[nextInt3][answer1].equals(selection[i][answer1]) && selection[i][question1].equals(selection[nextInt][question1])) change=1;}
} while (selection[nextInt3][0].equals(selection[nextInt][0]) || selection[nextInt3][0].equals(selection[nextInt2][0]) ||
selection[nextInt3][1].equals(selection[nextInt][1]) || selection[nextInt3][1].equals(selection[nextInt2][1]) || nextInt3==0 || change==1);
if (index>4) {
do {
nextInt4 = generator.nextInt(index); change=0;
for (int i=0;i<index;i++) {
if (selection[nextInt4][answer1].equals(selection[i][answer1]) && selection[i][question1].equals(selection[nextInt][question1])) change=1;}
} while (selection[nextInt4][0].equals(selection[nextInt][0]) || selection[nextInt4][0].equals(selection[nextInt2][0]) || selection[nextInt4][0].equals(selection[nextInt3][0]) ||
selection[nextInt4][1].equals(selection[nextInt][1]) || selection[nextInt4][1].equals(selection[nextInt2][1]) || selection[nextInt4][1].equals(selection[nextInt3][1]) ||
nextInt4==0 || change==1);
}
}
ArrayList nums = new ArrayList();
nums.add(nextInt);
nums.add(nextInt2);
if (index>3) nums.add(nextInt3);
if (index>4) nums.add(nextInt4);
Collections.shuffle(nums);
int ind[]= {nextInt,nextInt2,nextInt3,nextInt4};
ind[0]=Integer.parseInt(nums.get(0).toString());
ind[1]=Integer.parseInt(nums.get(1).toString());
if (index>3) ind[2]=Integer.parseInt(nums.get(2).toString());
if (index>4) ind[3]=Integer.parseInt(nums.get(3).toString());
answ1=selection[ind[0]][answer1];
answ2=selection[ind[1]][answer1];
if (index>3) answ3=selection[ind[2]][answer1];
if (index>4) answ4=selection[ind[3]][answer1];
// System.out.println("answ1="+answ1);
// System.out.println("answ2="+answ2);
// System.out.println("answ3="+answ3);
// System.out.println("answ4="+answ4);
Shuffle anagram1=new Shuffle();
String AnagramString=anagram1.AnagramString(selection[ind[0]][answer1]);
Shuffle anagram2=new Shuffle();
String AnagramString2=anagram2.AnagramString(selection[ind[1]][answer1]);
jRadioButton3.setVisible(false);
jRadioButton4.setVisible(false);
jRadioButton5.setVisible(false);
if (index>3) {
Shuffle anagram3=new Shuffle();
String AnagramString3=anagram3.AnagramString(selection[ind[2]][answer1]);
jRadioButton3.setVisible(true); jRadioButton3.setText(AnagramString3);
}
if (index>4) {
Shuffle anagram4=new Shuffle();
String AnagramString4=anagram4.AnagramString(selection[ind[3]][answer1]);
jRadioButton4.setVisible(true); jRadioButton4.setText(AnagramString4);
}
jRadioButton1.setText(AnagramString);
jRadioButton2.setText(AnagramString2);
jRadioButton1.setEnabled(true);
jRadioButton2.setEnabled(true);
jRadioButton3.setEnabled(true);
jRadioButton4.setEnabled(true);
answ=selection[nextInt][answer1];
quest=selection[nextInt][0];
dbpedia=selection[nextInt][2];
wiki=selection[nextInt][3];
question[num]="Η ερώτηση ήταν: "+selection[0][question1] +selection[nextInt][question1]+";";
answer[num]="Η σωστή απάντηση ήταν: " +answ;
}
private void Hangman() {
try {
URL url = new URL(URI1+"hangman/hanged0.jpg");
BufferedImage img = ImageIO.read(url);
Icon icon=new ImageIcon(img);
jLabel10.setIcon(icon);
} catch (IOException e) {System.out.println(e);}
jLabel10.setVisible(true);
frozen=false;
String str;
int fps = 0;
str = getParameter("fps");
try {
if (str != null) {
fps = Integer.parseInt(str);
}
} catch (Exception e) {}
int delay = (fps > 0) ? (1000 / fps) : 1000;
timer = new Timer(delay, this);
timer.setInitialDelay(0);
timer.setCoalesce(true);
startAnimation();
jTextField2.setText("Επέλεξε ένα γράμμα!");
HangmanActivate();
word=""; word2=""; word4=""; word6=""; word8=""; word9="";count=0;
jTextField1.setHorizontalAlignment(JTextField.CENTER);
jTextField2.setHorizontalAlignment(JTextField.CENTER);
jTextField5.setHorizontalAlignment(JTextField.CENTER);
ReadFromFile GetData = new ReadFromFile();
String[][] selection;
int index,hangman,nextInt,question1,answer1;
do {
selection = GetData.Selection(data);
index = GetData.index();
hangman = GetData.hangman();
} while (hangman==-1);
String selectedcategory=GetData.selectedcategory();
jLabel28.setText("Κατηγορία: "+selectedcategory);
Category[num]=selectedcategory;
Random generator = new Random();
question1 = generator.nextInt(2);
if (hangman==0) question1=1;
do {
answer1 = generator.nextInt(2);
} while (answer1==question1);
int play;
do {
nextInt = generator.nextInt(index);
play=0;
String check=selection[nextInt][answer1];
int length1 = check.length();
check=check.toUpperCase();
char [] array2check=check.toCharArray();
for (int s=0;s<length1;s++)
if (array2check[s]>='Α' && array2check[s]<='Ω') play++;
} while (nextInt==0 || play==0);
jTextField1.setText(selection[0][question1]+selection[nextInt][question1]+"; ");
wordold=selection[nextInt][answer1];
len = wordold.length();
wordold=wordold.replace('ΐ', 'ι');
wordold=wordold.replace('ΰ', 'υ');
wordnew=wordold.toUpperCase();
wordarray=wordnew.toCharArray();
for (int i = 0; i < len; i++) {
if (wordarray[i]=='Ά') {wordarray[i]='Α';}
if (wordarray[i]=='Έ') {wordarray[i]='Ε';}
if (wordarray[i]=='Ή') {wordarray[i]='Η';}
if (wordarray[i]=='Ί') {wordarray[i]='Ι';}
if (wordarray[i]=='Ό') {wordarray[i]='Ο';}
if (wordarray[i]=='Ύ') {wordarray[i]='Υ';}
if (wordarray[i]=='Ώ') {wordarray[i]='Ω';}
if (wordarray[i]=='Ϊ') {wordarray[i]='Ι';}
if (wordarray[i]=='Ϋ') {wordarray[i]='Υ';}
}
for (int i = 0; i < len; i++) word = word+wordarray[i];
word3=word;
for (int i = 0; i < len; i++) word4 = word4+ "*";
word5= new char[len];
word7= new char[len];
word5 = word.toCharArray();
word7 = word.toCharArray();
for (int i = 0; i < len; i ++)
if ((word7[i]>='Α')&&(word7[i]<='Ω')) word7[i] = '_';
for (int i = 0; i < len; i++) word8 = word8+word7[i]+' ';
if (word8.length()>185) jTextField5.setFont(new java.awt.Font("Tahoma", 1, 8));
else if (word8.length()>145) jTextField5.setFont(new java.awt.Font("Tahoma", 1, 10));
else if (word8.length()>135) jTextField5.setFont(new java.awt.Font("Tahoma", 1, 12));
else if (word8.length()>121) jTextField5.setFont(new java.awt.Font("Tahoma", 1, 14));
else if (word8.length()>117) jTextField5.setFont(new java.awt.Font("Tahoma", 1, 16));
else jTextField5.setFont(new java.awt.Font("Tahoma", 1, 18));
jTextField5.setText(word8);
quest=selection[nextInt][0];
dbpedia=selection[nextInt][2];
wiki=selection[nextInt][3];
question[num]="Η ερώτηση ήταν: "+selection[0][question1] +selection[nextInt][question1]+";";
answer[num]="Η σωστή απάντηση ήταν: " +selection[nextInt][answer1];
}
private void HangmanwithPicture() {
try {
URL url = new URL(URI1+"hangman/hanged0.jpg");
BufferedImage img = ImageIO.read(url);
Icon icon=new ImageIcon(img);
jLabel10.setIcon(icon);
} catch (IOException e) {System.out.println(e);}
jLabel10.setVisible(true);
jLabel2.setVisible(true);
jTextField2.setText("Επέλεξε ένα γράμμα!");
HangmanActivate();
word=""; word2=""; word4=""; word6=""; word8=""; word9="";count=0;
jTextField1.setHorizontalAlignment(JTextField.CENTER);
jTextField2.setHorizontalAlignment(JTextField.CENTER);
jTextField5.setHorizontalAlignment(JTextField.CENTER);
ReadFromFile GetData = new ReadFromFile();
String[][] selection;
int index,nextInt,question1,answer1;
selection = GetData.Selection1(data);
index = GetData.index();
String selectedcategory=GetData.selectedcategory();
jLabel28.setText("Κατηγορία: "+selectedcategory);
Category[num]=selectedcategory;
Random generator = new Random();
question1=1;
answer1=0;
String warning="Ο σύνδεσμος που περιέχει την εικόνα: ";
int play;
do {
nextInt = generator.nextInt(index);
play=0;
String check=selection[nextInt][0];
int length1 = check.length();
check=check.toUpperCase();
char [] array2check=check.toCharArray();
for (int s=0;s<length1;s++)
if (array2check[s]>='Α' && array2check[s]<='Ω') play++;
} while (nextInt==0 || play==0);
try {
URL url = new URL(selection[nextInt][1]);
BufferedImage img = ImageIO.read(url);
java.awt.Image img2=img.getScaledInstance(240,140,BufferedImage.SCALE_SMOOTH);
Icon icon=new ImageIcon(img2);
jLabel2.setIcon(icon);
} catch (IOException e) {
jLabel2.setText("Εικόνα:"+selection[nextInt][0]);
JOptionPane.showMessageDialog(this, warning+selection[nextInt][0]+" δε λειτουργεί!");
}
frozen=false;
String str;
int fps = 0;
str = getParameter("fps");
try {
if (str != null) {
fps = Integer.parseInt(str);
}
} catch (Exception e) {}
int delay = (fps > 0) ? (1000 / fps) : 1000;
timer = new Timer(delay, this);
timer.setInitialDelay(0);
timer.setCoalesce(true);
startAnimation();
jTextField1.setText(selection[0][question1]);
wordold=selection[nextInt][answer1];
len = wordold.length();
wordold=wordold.replace('ΐ', 'ι');
wordold=wordold.replace('ΰ', 'υ');
wordnew=wordold.toUpperCase();
wordarray=wordnew.toCharArray();
for (int i = 0; i < len; i++) {
if (wordarray[i]=='Ά') {wordarray[i]='Α';}
if (wordarray[i]=='Έ') {wordarray[i]='Ε';}
if (wordarray[i]=='Ή') {wordarray[i]='Η';}
if (wordarray[i]=='Ί') {wordarray[i]='Ι';}
if (wordarray[i]=='Ό') {wordarray[i]='Ο';}
if (wordarray[i]=='Ύ') {wordarray[i]='Υ';}
if (wordarray[i]=='Ώ') {wordarray[i]='Ω';}
if (wordarray[i]=='Ϊ') {wordarray[i]='Ι';}
if (wordarray[i]=='Ϋ') {wordarray[i]='Υ';}
}
for (int i = 0; i < len; i++) word = word+wordarray[i];
word3=word;
for (int i = 0; i < len; i++) word4 = word4+ "*";
word5= new char[len];
word7= new char[len];
word5 = word.toCharArray();
word7 = word.toCharArray();
for (int i = 0; i < len; i ++)
if ((word7[i]>='Α')&&(word7[i]<='Ω')) word7[i] = '_';
for (int i = 0; i < len; i++) word8 = word8+word7[i]+' ';
if (word8.length()>185) jTextField5.setFont(new java.awt.Font("Tahoma", 1, 8));
else if (word8.length()>145) jTextField5.setFont(new java.awt.Font("Tahoma", 1, 10));
else if (word8.length()>135) jTextField5.setFont(new java.awt.Font("Tahoma", 1, 12));
else if (word8.length()>121) jTextField5.setFont(new java.awt.Font("Tahoma", 1, 14));
else if (word8.length()>117) jTextField5.setFont(new java.awt.Font("Tahoma", 1, 16));
else jTextField5.setFont(new java.awt.Font("Tahoma", 1, 18));
jTextField5.setText(word8);
quest=selection[nextInt][0];
dbpedia=selection[nextInt][2];
wiki=selection[nextInt][3];
question[num]="Η ερώτηση ήταν: "+selection[0][question1] +selection[nextInt][question1]+";";
answer[num]="Η σωστή απάντηση ήταν: " +selection[nextInt][answer1];
}
private void Flag() {
frozen=false;
String str,warning;
int fps = 0;
MultipleChoiceActivate();
jLabel2.setVisible(true);
jRadioButton5.setSelected(true);
jTextField2.setText("Επέλεξε μία απάντηση!");
jTextField1.setHorizontalAlignment(JTextField.CENTER);
jTextField2.setHorizontalAlignment(JTextField.CENTER);
ReadFromFile GetData = new ReadFromFile();
String[][] selection;
int index,nextInt=0,nextInt2=0,nextInt3=0,nextInt4=0;
Random generator = new Random();
do {
selection=GetData.Selection1(data); index=GetData.index();//indexwithoutduplicates=GetData.indexwithoutduplicates();
} while (index==2);
String selectedcategory=GetData.selectedcategory();
jLabel28.setText("Κατηγορία: "+selectedcategory);
Category[num]=selectedcategory;
do {
nextInt = generator.nextInt(index);
} while (nextInt==0 );
warning="";
jTextField1.setText(selection[0][1]);
warning="Ο σύνδεσμος που περιέχει την εικόνα: ";
try {
URL url = new URL(selection[nextInt][1]);
BufferedImage img = ImageIO.read(url);
java.awt.Image img2=img.getScaledInstance(240,140,BufferedImage.SCALE_SMOOTH);
Icon icon=new ImageIcon(img2);
jLabel2.setIcon(icon);
} catch (IOException e) {
jLabel2.setText("Εικόνα:"+selection[nextInt][0]);
JOptionPane.showMessageDialog(this, warning+selection[nextInt][0]+" δε λειτουργεί!");
}
str = getParameter("fps");
try {
if (str != null) {
fps = Integer.parseInt(str);
}
} catch (Exception e) {}
int delay = (fps > 0) ? (1000 / fps) : 1000;
timer = new Timer(delay, this);
timer.setInitialDelay(0);
timer.setCoalesce(true);
startAnimation();
do {
nextInt2 = generator.nextInt(index);
} while (selection[nextInt2][0].equals(selection[nextInt][0]) || selection[nextInt2][1].equals(selection[nextInt][1]) || nextInt2==0);
if (index>3) {
do {
nextInt3 = generator.nextInt(index);
} while (selection[nextInt3][0].equals(selection[nextInt][0]) || selection[nextInt3][0].equals(selection[nextInt2][0]) ||
selection[nextInt3][1].equals(selection[nextInt][1]) || selection[nextInt3][1].equals(selection[nextInt2][1]) || nextInt3==0);
if (index>4) {
do {
nextInt4 = generator.nextInt(index);
} while (selection[nextInt4][0].equals(selection[nextInt][0]) || selection[nextInt4][0].equals(selection[nextInt2][0]) || selection[nextInt4][0].equals(selection[nextInt3][0]) ||
selection[nextInt4][1].equals(selection[nextInt][1]) || selection[nextInt4][1].equals(selection[nextInt2][1]) || selection[nextInt4][1].equals(selection[nextInt3][1]) || nextInt4==0);
}
}
//System.out.println("1. "+selection[nextInt][0]);
//System.out.println("2. "+selection[nextInt2][0]);
//System.out.println("3. "+selection[nextInt3][0]);
//System.out.println("4. "+selection[nextInt4][0]);
ArrayList nums = new ArrayList();
nums.add(nextInt);
nums.add(nextInt2);
if (index>3) nums.add(nextInt3);
if (index>4) nums.add(nextInt4);
Collections.shuffle(nums);
int ind[]= {nextInt,nextInt2,nextInt3,nextInt4};
ind[0]=Integer.parseInt(nums.get(0).toString());
ind[1]=Integer.parseInt(nums.get(1).toString());
if (index>3) ind[2]=Integer.parseInt(nums.get(2).toString());
if (index>4) ind[3]=Integer.parseInt(nums.get(3).toString());
answ1=selection[ind[0]][0];
answ2=selection[ind[1]][0];
if (index>3) answ3=selection[ind[2]][0];
if (index>4) answ4=selection[ind[3]][0];
jRadioButton3.setVisible(false);
jRadioButton4.setVisible(false);
jRadioButton5.setVisible(false);
if (index>3) jRadioButton3.setVisible(true); jRadioButton3.setText(answ3);
if (index>4) jRadioButton4.setVisible(true); jRadioButton4.setText(answ4);
jRadioButton1.setText(answ1);
jRadioButton2.setText(answ2);
jRadioButton1.setEnabled(true);
jRadioButton2.setEnabled(true);
jRadioButton3.setEnabled(true);
jRadioButton4.setEnabled(true);
answ=selection[nextInt][0];
quest=selection[nextInt][0];
dbpedia=selection[nextInt][2];
wiki=selection[nextInt][3];
// System.out.println("Η απάντηση είναι: "+answ);
question[num]="Η ερώτηση ήταν: "+selection[0][1] +selection[nextInt][1]+";";
answer[num]="Η σωστή απάντηση ήταν: " +selection[nextInt][0];
}
private void Flag2() {
String str;
MultipleChoiceActivate();
jTextField1.setHorizontalAlignment(JTextField.CENTER);
jTextField2.setHorizontalAlignment(JTextField.CENTER);
jTextField2.setText("Επέλεξε μία απάντηση!");
ReadFromFile GetData = new ReadFromFile();
String[][] selection;
int index,nextInt=0,nextInt2=0,nextInt3=0,nextInt4=0;
Random generator = new Random();
do {
selection=GetData.Selection1(data); index=GetData.index();//indexwithoutduplicates=GetData.indexwithoutduplicates();
} while (index==2);
String selectedcategory=GetData.selectedcategory();
jLabel28.setText("Κατηγορία: "+selectedcategory);
Category[num]=selectedcategory;
do {
nextInt = generator.nextInt(index);
} while (nextInt==0);
jTextField1.setText(selection[0][0]+selection[nextInt][0]+";");
do {
nextInt2 = generator.nextInt(index);
} while (selection[nextInt2][0].equals(selection[nextInt][0]) || selection[nextInt2][1].equals(selection[nextInt][1]) || nextInt2==0);
if (index>3) {
do {
nextInt3 = generator.nextInt(index);
} while (selection[nextInt3][0].equals(selection[nextInt][0]) || selection[nextInt3][0].equals(selection[nextInt2][0]) ||
selection[nextInt3][1].equals(selection[nextInt][1]) || selection[nextInt3][1].equals(selection[nextInt2][1]) || nextInt3==0);
if (index>4) {
do {
nextInt4 = generator.nextInt(index);
} while (selection[nextInt4][0].equals(selection[nextInt][0]) | selection[nextInt4][0].equals(selection[nextInt2][0]) || selection[nextInt4][0].equals(selection[nextInt3][0]) ||
selection[nextInt4][1].equals(selection[nextInt][1]) | selection[nextInt4][1].equals(selection[nextInt2][1]) || selection[nextInt4][1].equals(selection[nextInt3][1]) || nextInt4==0);
}
}
ArrayList nums = new ArrayList();
nums.add(nextInt);
nums.add(nextInt2);
if (index>3) nums.add(nextInt3);
if (index>4) nums.add(nextInt4);
Collections.shuffle(nums);
int ind[]= {nextInt,nextInt2,nextInt3,nextInt4};
ind[0]=Integer.parseInt(nums.get(0).toString());
ind[1]=Integer.parseInt(nums.get(1).toString());
if (index>3) ind[2]=Integer.parseInt(nums.get(2).toString());
if (index>4) ind[3]=Integer.parseInt(nums.get(3).toString());
answ1=selection[ind[0]][1];
answ2=selection[ind[1]][1];
if (index>3) answ3=selection[ind[2]][1];
if (index>4) answ4=selection[ind[3]][1];
jRadioButton3.setVisible(false);
jRadioButton4.setVisible(false);
if (index>3) {
jRadioButton3.setVisible(true);
try {
URL url = new URL(selection[ind[2]][1]);
BufferedImage img = ImageIO.read(url);
java.awt.Image img2 = img.getScaledInstance(150, 70, BufferedImage.SCALE_SMOOTH);
Icon icon=new ImageIcon(img2);
jRadioButton3.setIcon(icon);
} catch (IOException e) {
jRadioButton3.setText("Εικόνα:"+selection[ind[2]][0]);
JOptionPane.showMessageDialog(this, "Ο σύνδεσμος που περιέχει την εικόνα: "+selection[ind[2]][0]+" δε λειτουργεί!");
}
}
if (index>4) {
jRadioButton4.setVisible(true);
try {
URL url = new URL(selection[ind[3]][1]);
BufferedImage img = ImageIO.read(url);
java.awt.Image img2 = img.getScaledInstance(150, 70, BufferedImage.SCALE_SMOOTH);
Icon icon=new ImageIcon(img2);
jRadioButton4.setIcon(icon);
} catch (IOException e) {
jRadioButton4.setText("Εικόνα:"+selection[ind[3]][0]);
JOptionPane.showMessageDialog(this, "Ο σύνδεσμος που περιέχει την εικόνα: "+selection[ind[3]][0]+" δε λειτουργεί!");
}
}
try {
URL url = new URL(selection[ind[0]][1]);
BufferedImage img = ImageIO.read(url);
java.awt.Image img2 = img.getScaledInstance(150, 70, BufferedImage.SCALE_SMOOTH);
Icon icon=new ImageIcon(img2);
jRadioButton1.setIcon(icon);
} catch (IOException e) {
jRadioButton1.setText("Εικόνα:"+selection[ind[0]][0]);
JOptionPane.showMessageDialog(this, "Ο σύνδεσμος που περιέχει την εικόνα: "+selection[ind[0]][0]+" δε λειτουργεί!");
}
try {
URL url = new URL(selection[ind[1]][1]);
BufferedImage img = ImageIO.read(url);
java.awt.Image img2 = img.getScaledInstance(150, 70, BufferedImage.SCALE_SMOOTH);
Icon icon=new ImageIcon(img2);
jRadioButton2.setIcon(icon);
} catch (IOException e) {
jRadioButton2.setText("Εικόνα:"+selection[ind[1]][0]);
JOptionPane.showMessageDialog(this, "Ο σύνδεσμος που περιέχει την εικόνα: "+selection[ind[1]][0]+" δε λειτουργεί!");
}
frozen=false;
int fps = 0;
str = getParameter("fps");
try {
if (str != null) {
fps = Integer.parseInt(str);
}
} catch (Exception e) {}
int delay = (fps > 0) ? (1000 / fps) : 1000;
timer = new Timer(delay, this);
timer.setInitialDelay(0);
timer.setCoalesce(true);
startAnimation();
jRadioButton1.setEnabled(true);
jRadioButton2.setEnabled(true);
jRadioButton3.setEnabled(true);
jRadioButton4.setEnabled(true);
//System.out.println("1. "+selection[nextInt][0]);
//System.out.println("2. "+selection[nextInt2][0]);
//System.out.println("3. "+selection[nextInt3][0]);
//System.out.println("4. "+selection[nextInt4][0]);
answ=selection[nextInt][1];
if ("η χώρα είναι: ".equals(selection[0][0])) {
if (nextInt==ind[0]) {answw="η πρώτη σημαία";}
else if (nextInt==ind[1]) {answw="η δεύτερη σημαία";}
else if (nextInt==ind[2]) {answw="η τρίτη σημαία";}
else if (nextInt==ind[3]) {answw="η τέταρτη σημαία";}
}
else {
if (nextInt==ind[0]) {answw="η πρώτη εικόνα";}
else if (nextInt==ind[1]) {answw="η δεύτερη εικόνα";}
else if (nextInt==ind[2]) {answw="η τρίτη εικόνα";}
else if (nextInt==ind[3]) {answw="η τέταρτη εικόνα";}
}
quest=selection[nextInt][0];
dbpedia=selection[nextInt][2];
wiki=selection[nextInt][3];
question[num]="Η ερώτηση ήταν: "+selection[0][0] +selection[nextInt][0]+";";
answer[num]="Η σωστή απάντηση ήταν: " +selection[nextInt][1];
}
private void Matching() {
frozen=false;
String str;
int fps = 0;
str = getParameter("fps");
try {
if (str != null) {
fps = Integer.parseInt(str);
}
} catch (Exception e) {}
int delay = (fps > 0) ? (1000 / fps) : 1000;
timer = new Timer(delay, this);
timer.setInitialDelay(0);
timer.setCoalesce(true);
startAnimation();
MatchingActivate();
jTextField6.setVisible(true);
jTextField2.setText("Αφού επιλέξεις τις απαντήσεις σου, πάτησε υποβολή!");
jTextField1.setHorizontalAlignment(JTextField.CENTER);
jTextField2.setHorizontalAlignment(JTextField.CENTER);
jTextField6.setHorizontalAlignment(JTextField.CENTER);
jTextField6.setText("Πρέπει να τα βρεις όλα, για να θεωρηθεί η απάντηση σου σωστή!");
ReadFromFile GetData = new ReadFromFile();
String[][] selection;
int index,question1,answer1;
int nextInt=0,nextInt2=0,nextInt3=0,nextInt4=0;
Random generator = new Random();
do {
selection=GetData.Selection(data); index=GetData.index(); //indexwithoutduplicates=GetData.indexwithoutduplicates();
} while (index==2);
String selectedcategory=GetData.selectedcategory();
jLabel28.setText("Κατηγορία: "+selectedcategory);
Category[num]=selectedcategory;
comboindex=index;
question1 = generator.nextInt(2);
do {
answer1 = generator.nextInt(2);
} while (answer1==question1);
do {
nextInt = generator.nextInt(index);
} while (nextInt==0);
jTextField1.setText(selection[0][question1]);
jLabel27.setText("Αντιστοίχισε την 1η στήλη με τη 2η στήλη!");
int change;
do {
nextInt2 = generator.nextInt(index); change=0;
for (int i=0;i<index;i++) {
if ((selection[nextInt2][answer1].equals(selection[i][answer1]) && selection[i][question1].equals(selection[nextInt][question1])) ||
(selection[nextInt2][question1].equals(selection[i][question1]) && selection[i][answer1].equals(selection[nextInt][answer1])))
change=1;
}
} while (selection[nextInt2][0].equals(selection[nextInt][0]) || selection[nextInt2][1].equals(selection[nextInt][1]) || nextInt2==0 || change==1);
if (index>3) {
do {
nextInt3 = generator.nextInt(index); change=0;
for (int i=0;i<index;i++) {
if (((selection[nextInt3][answer1].equals(selection[i][answer1]) && selection[i][question1].equals(selection[nextInt][question1])) ||
(selection[nextInt3][question1].equals(selection[i][question1]) && selection[i][answer1].equals(selection[nextInt][answer1]))) ||
((selection[nextInt3][answer1].equals(selection[i][answer1]) && selection[i][question1].equals(selection[nextInt2][question1])) ||
(selection[nextInt3][question1].equals(selection[i][question1]) && selection[i][answer1].equals(selection[nextInt2][answer1]))))
change=1;
}
} while (selection[nextInt3][0].equals(selection[nextInt][0]) || selection[nextInt3][0].equals(selection[nextInt2][0]) ||
selection[nextInt3][1].equals(selection[nextInt][1]) || selection[nextInt3][1].equals(selection[nextInt2][1]) || nextInt3==0 ||
change==1);
if (index>4) {
do {
nextInt4 = generator.nextInt(index); change=0;
for (int i=0;i<index;i++) {
if (((selection[nextInt4][answer1].equals(selection[i][answer1]) && selection[i][question1].equals(selection[nextInt][question1])) ||
(selection[nextInt4][question1].equals(selection[i][question1]) && selection[i][answer1].equals(selection[nextInt][answer1]))) ||
((selection[nextInt4][answer1].equals(selection[i][answer1]) && selection[i][question1].equals(selection[nextInt2][question1])) ||
(selection[nextInt4][question1].equals(selection[i][question1]) && selection[i][answer1].equals(selection[nextInt2][answer1]))) ||
((selection[nextInt4][answer1].equals(selection[i][answer1]) && selection[i][question1].equals(selection[nextInt3][question1])) ||
(selection[nextInt4][question1].equals(selection[i][question1]) && selection[i][answer1].equals(selection[nextInt3][answer1]))))
change=1;
}
} while (selection[nextInt4][0].equals(selection[nextInt][0]) || selection[nextInt4][0].equals(selection[nextInt2][0]) || selection[nextInt4][0].equals(selection[nextInt3][0]) ||
selection[nextInt4][1].equals(selection[nextInt][1]) || selection[nextInt4][1].equals(selection[nextInt2][1]) || selection[nextInt4][1].equals(selection[nextInt3][1]) ||
nextInt4==0 || change==1);
}
}
ArrayList nums = new ArrayList();
nums.add(nextInt);
nums.add(nextInt2);
if (index>3) nums.add(nextInt3);
if (index>4) nums.add(nextInt4);
Collections.shuffle(nums);
int ind[]= {nextInt,nextInt2,nextInt3,nextInt4};
ind[0]=Integer.parseInt(nums.get(0).toString());
ind[1]=Integer.parseInt(nums.get(1).toString());
if (index>3) ind[2]=Integer.parseInt(nums.get(2).toString());
if (index>4) ind[3]=Integer.parseInt(nums.get(3).toString());
answ1=selection[ind[0]][answer1];
answ2=selection[ind[1]][answer1];
if (index>3) answ3=selection[ind[2]][answer1];
if (index>4) answ4=selection[ind[3]][answer1];
if (index>3){
jLabel5.setVisible(true); jLabel5.setText("3. "+selection[nextInt3][question1]);jComboBox3.setVisible(true);
}
if (index>4){
jLabel6.setVisible(true); jLabel6.setText("4. "+selection[nextInt4][question1]);jComboBox4.setVisible(true);
}
jLabel3.setVisible(true);jLabel3.setText("1. "+selection[nextInt][question1]);
jLabel4.setVisible(true);jLabel4.setText("2. "+selection[nextInt2][question1]);
jComboBox1.removeAllItems();
jComboBox1.insertItemAt(answ1, 0);
jComboBox1.insertItemAt(answ2, 1);
jComboBox2.removeAllItems();
jComboBox2.insertItemAt(answ1, 0);
jComboBox2.insertItemAt(answ2, 1);
if (index>3){
jComboBox1.insertItemAt(answ3, 2);
jComboBox2.insertItemAt(answ3, 2);
jComboBox3.removeAllItems();
jComboBox3.insertItemAt(answ1, 0);
jComboBox3.insertItemAt(answ2, 1);
jComboBox3.insertItemAt(answ3, 2);
}
if (index>4){
jComboBox1.insertItemAt(answ4, 3);
jComboBox2.insertItemAt(answ4, 3);
jComboBox3.insertItemAt(answ4, 3);
jComboBox4.removeAllItems();
jComboBox4.insertItemAt(answ1, 0);
jComboBox4.insertItemAt(answ2, 1);
jComboBox4.insertItemAt(answ3, 2);
jComboBox4.insertItemAt(answ4, 3);
}
answ1=selection[nextInt][answer1];
answ2=selection[nextInt2][answer1];
if (index>3) answ3=selection[nextInt3][answer1];
if (index>4) answ4=selection[nextInt4][answer1];
quest=selection[nextInt][0];
dbpedia=selection[nextInt][2];
wiki=selection[nextInt][3];
quest2=selection[nextInt2][0];
dbpedia2=selection[nextInt2][2];
wiki2=selection[nextInt2][3];
quest3=selection[nextInt3][0];
dbpedia3=selection[nextInt3][2];
wiki3=selection[nextInt3][3];
quest4=selection[nextInt4][0];
dbpedia4=selection[nextInt4][2];
wiki4=selection[nextInt4][3];
question[num]="Η ερώτηση ήταν: "+selection[0][question1];
if (index>4) answer[num]="Η σωστή απάντηση ήταν: 1. " +selection[nextInt][question1] +" - "+selection[nextInt][answer1] +" 2. "+selection[nextInt2][question1] +" - "+selection[nextInt2][answer1] +
" 3."+selection[nextInt3][question1] +" - "+selection[nextInt3][answer1] +" 4."+selection[nextInt4][question1] +" - "+selection[nextInt4][answer1];
else if (index==4) answer[num]="Η σωστή απάντηση ήταν: 1. " +selection[nextInt][question1] +" - "+selection[nextInt][answer1] +" 2. "+selection[nextInt2][question1] +" - "+selection[nextInt2][answer1] +
" 3."+selection[nextInt3][question1] +" - "+selection[nextInt3][answer1] ;
else if (index==3) answer[num]="Η σωστή απάντηση ήταν: 1. " +selection[nextInt][question1] +" - "+selection[nextInt][answer1] +" 2. "+selection[nextInt2][question1] +" - "+selection[nextInt2][answer1];
}
private void MultipleChoicewithDuplicates() {
jCheckBox1.setVisible(true);jCheckBox2.setVisible(true);jButton26.setVisible(true);
jTextField2.setText("Επέλεξε μία ή περισσότερες απαντήσεις!");
jTextField1.setHorizontalAlignment(JTextField.CENTER);
jTextField2.setHorizontalAlignment(JTextField.CENTER);
jCheckBox1.setSelected(false);jCheckBox2.setSelected(false);jCheckBox3.setSelected(false);
jCheckBox4.setSelected(false);jCheckBox5.setSelected(false);
jTextField6.setVisible(true);
jTextField6.setText("Πρέπει να τα βρεις όλα, για να θεωρηθεί η απάντηση σου σωστή!");
ReadFromFile GetData = new ReadFromFile();
String[][] selection;
int index,question1,answer1;
int nextInt=0,nextInt2=0,nextInt3=0,nextInt4=0,nextInt5=0;
Random generator = new Random();
numofcorrect=0;
do {
selection=GetData.Selection2(data); index=GetData.index();
} while (index==2);
String selectedcategory=GetData.selectedcategory();
jLabel28.setText("Κατηγορία: "+selectedcategory);
Category[num]=selectedcategory;
checkindex=index;
frozen=false;
String str;
int fps = 0;
str = getParameter("fps");
try {
if (str != null) {
fps = Integer.parseInt(str);
}
} catch (Exception e) {}
int delay = (fps > 0) ? (1000 / fps) : 1000;
timer = new Timer(delay, this);
timer.setInitialDelay(0);
timer.setCoalesce(true);
startAnimation();
question1=1;
answer1=0;
do {
nextInt = generator.nextInt(index);
} while (nextInt==0);
//System.out.println("Το nexIint είναι ="+nextInt);
jTextField1.setText(selection[0][question1] +selection[nextInt][question1]+";");
do {
nextInt2 = generator.nextInt(index);
} while (nextInt2 == nextInt || nextInt2==0 || selection[nextInt2][answer1].equals(selection[nextInt][answer1]));
//System.out.println("Το nexIint2 είναι ="+nextInt2);
if (index>3) {
do {
nextInt3 = generator.nextInt(index); //System.out.println("Το INDEX είναι ="+index);
} while (nextInt3 == nextInt || nextInt3 == nextInt2 || nextInt3==0 ||
selection[nextInt3][answer1].equals(selection[nextInt][answer1]) || selection[nextInt3][answer1].equals(selection[nextInt2][answer1]));
//System.out.println("Το nexIint3 είναι ="+nextInt3);
if (index>4) {
do {
nextInt4 = generator.nextInt(index);
} while (nextInt4 == nextInt || nextInt4 == nextInt2 || nextInt4 == nextInt3 || nextInt4==0 ||
selection[nextInt4][answer1].equals(selection[nextInt][answer1]) || selection[nextInt4][answer1].equals(selection[nextInt2][answer1]) ||
selection[nextInt4][answer1].equals(selection[nextInt3][answer1])) ;
//System.out.println("Το nexIint4 είναι ="+nextInt4);
if (index>5) {
do {
nextInt5 = generator.nextInt(index);
} while (nextInt5 == nextInt || nextInt5 == nextInt2 || nextInt5 == nextInt3 || nextInt5 == nextInt4 ||nextInt5==0 ||
selection[nextInt5][answer1].equals(selection[nextInt][answer1]) || selection[nextInt5][answer1].equals(selection[nextInt2][answer1]) ||
selection[nextInt5][answer1].equals(selection[nextInt3][answer1]) || selection[nextInt5][answer1].equals(selection[nextInt4][answer1])) ;
//System.out.println("Το nexIint5 είναι ="+nextInt5);
}
}
}
for (int i=0;i<index;i++) {
if (selection[nextInt2][answer1].equals(selection[i][answer1]) && selection[i][question1].equals(selection[nextInt][question1])) nextInt2=i;
if (index>3 && selection[nextInt3][answer1].equals(selection[i][answer1]) && selection[i][question1].equals(selection[nextInt][question1])) nextInt3=i;
if (index>4 && selection[nextInt4][answer1].equals(selection[i][answer1]) && selection[i][question1].equals(selection[nextInt][question1])) nextInt4=i;
if (index>5 && selection[nextInt5][answer1].equals(selection[i][answer1]) && selection[i][question1].equals(selection[nextInt][question1])) nextInt5=i;
}
ArrayList nums = new ArrayList();
nums.add(nextInt);
nums.add(nextInt2);
if (index>3) nums.add(nextInt3);
if (index>4) nums.add(nextInt4);
if (index>5) nums.add(nextInt5);
Collections.shuffle(nums);
int ind[]= {nextInt,nextInt2,nextInt3,nextInt4,nextInt5};
ind[0]=Integer.parseInt(nums.get(0).toString());
ind[1]=Integer.parseInt(nums.get(1).toString());
if (index>3) ind[2]=Integer.parseInt(nums.get(2).toString());
if (index>4) ind[3]=Integer.parseInt(nums.get(3).toString());
if (index>5) ind[4]=Integer.parseInt(nums.get(4).toString());
answ1=selection[ind[0]][answer1];
answ2=selection[ind[1]][answer1];
if (index>3) answ3=selection[ind[2]][answer1];
if (index>4) answ4=selection[ind[3]][answer1];
if (index>5) answ5=selection[ind[4]][answer1];
jCheckBox3.setVisible(false);
jCheckBox4.setVisible(false);
jCheckBox5.setVisible(false);
if (index>3) jCheckBox3.setVisible(true); jCheckBox3.setText(answ3);
if (index>4) jCheckBox4.setVisible(true); jCheckBox4.setText(answ4);
if (index>5) jCheckBox5.setVisible(true); jCheckBox5.setText(answ5);
jCheckBox1.setText(answ1);
jCheckBox2.setText(answ2);
jCheckBox1.setEnabled(true);
jCheckBox2.setEnabled(true);
jCheckBox3.setEnabled(true);
jCheckBox4.setEnabled(true);
jCheckBox5.setEnabled(true);
answ=selection[ind[0]][answer1];
quest=selection[ind[0]][question1];
dbpedia=selection[ind[0]][2];
wiki=selection[ind[0]][3];
answ2=selection[ind[1]][answer1];
quest2=selection[ind[1]][question1];
dbpedia2=selection[ind[1]][2];
wiki2=selection[ind[1]][3];
if (index>3) {
answ3=selection[ind[2]][answer1];
quest3=selection[ind[2]][question1];
dbpedia3=selection[ind[2]][2];
wiki3=selection[ind[2]][3];
}
if (index>4) {
answ4=selection[ind[3]][answer1];
quest4=selection[ind[3]][question1];
dbpedia4=selection[ind[3]][2];
wiki4=selection[ind[3]][3];
}
if (index>5) {
answ5=selection[ind[4]][answer1];
quest5=selection[ind[4]][question1];
dbpedia5=selection[ind[4]][2];
wiki5=selection[ind[4]][3];
}
question[num]=selection[0][question1] +selection[nextInt][question1]+";";
int answers=0;
answer[num]="";
if (selection[nextInt][question1].equals(selection[ind[0]][question1])) {
numofcorrect=numofcorrect+1;
if (answers==0) {answer[num]=answer[num]+selection[ind[0]][answer1]; answers=1;}
else if (answers==1) answer[num]=answer[num]+", "+selection[ind[0]][answer1];
}
if (selection[nextInt][question1].equals(selection[ind[1]][question1])) {
numofcorrect=numofcorrect+1;
if (answers==0) {answer[num]=answer[num]+selection[ind[1]][answer1];answers=1;}
else if (answers==1) answer[num]=answer[num]+", "+selection[ind[1]][answer1];
}
if (selection[nextInt][question1].equals(selection[ind[2]][question1])) {
numofcorrect=numofcorrect+1;
if (answers==0) {answer[num]=answer[num]+selection[ind[2]][answer1];answers=1;}
else if (answers==1) answer[num]=answer[num]+", "+selection[ind[2]][answer1];
}
if (selection[nextInt][question1].equals(selection[ind[3]][question1])) {
numofcorrect=numofcorrect+1;
if (answers==0) {answer[num]=answer[num]+selection[ind[3]][answer1];answers=1;}
else if (answers==1) answer[num]=answer[num]+", "+selection[ind[3]][answer1];
}
if (selection[nextInt][question1].equals(selection[ind[4]][question1])) {
numofcorrect=numofcorrect+1;
if (answers==0) {answer[num]=answer[num]+selection[ind[4]][answer1];answers=1;}
else if (answers==1) answer[num]=answer[num]+", "+selection[ind[4]][answer1];
}
// System.out.println("Οι σωστές είναι: "+numofcorrect);
duplicatequestion=selection[nextInt][question1];
jButton26.setEnabled(true);
correctanswers="";
correctanswers=answer[num]; // System.out.println("Correct="+correctanswers);
answer[num]="Η σωστή απάντηση είναι: "+answer[num];
}
private void MultipleChoiceActivate(){
jTextField5.setVisible(false);
jLabel2.setText(null);
jRadioButton5.setSelected(true);
jRadioButton1.setVisible(true);
jRadioButton2.setVisible(true);
jRadioButton3.setVisible(true);
jRadioButton4.setVisible(true);
}
private void HangmanActivate(){
try {
URL url = new URL(URI1+"hanged/hanged0.jpg");
BufferedImage img = ImageIO.read(url);
Icon icon=new ImageIcon(img);
jLabel10.setIcon(icon);
} catch (IOException e) {}
jRadioButton1.setVisible(false); jRadioButton2.setVisible(false); jRadioButton3.setVisible(false);
jRadioButton4.setVisible(false);jRadioButton5.setVisible(false);
jButton1.setEnabled(true); jButton2.setEnabled(true); jButton3.setEnabled(true);
jButton4.setEnabled(true); jButton5.setEnabled(true); jButton6.setEnabled(true);
jButton7.setEnabled(true); jButton8.setEnabled(true); jButton9.setEnabled(true);
jButton10.setEnabled(true); jButton11.setEnabled(true); jButton12.setEnabled(true);
jButton13.setEnabled(true); jButton14.setEnabled(true); jButton15.setEnabled(true);
jButton16.setEnabled(true); jButton17.setEnabled(true); jButton18.setEnabled(true);
jButton19.setEnabled(true); jButton20.setEnabled(true); jButton21.setEnabled(true);
jButton22.setEnabled(true); jButton23.setEnabled(true); jButton24.setEnabled(true);
jButton1.setVisible(true);jButton2.setVisible(true);jButton3.setVisible(true);
jButton4.setVisible(true); jButton5.setVisible(true); jButton6.setVisible(true);
jButton7.setVisible(true); jButton8.setVisible(true); jButton9.setVisible(true);
jButton10.setVisible(true); jButton11.setVisible(true); jButton12.setVisible(true);
jButton13.setVisible(true); jButton14.setVisible(true); jButton15.setVisible(true);
jButton16.setVisible(true); jButton17.setVisible(true); jButton18.setVisible(true);
jButton19.setVisible(true); jButton20.setVisible(true); jButton21.setVisible(true);
jButton22.setVisible(true); jButton23.setVisible(true); jButton24.setVisible(true);
jTextField5.setVisible(true);
}
private void MatchingActivate(){
jLabel3.setVisible(true);jLabel4.setVisible(true); jLabel5.setVisible(false);
jLabel6.setVisible(false);jLabel27.setVisible(true);
jComboBox1.setVisible(true);jComboBox2.setVisible(true);jComboBox3.setVisible(false);
jComboBox4.setVisible(false);jButton26.setVisible(true);
jComboBox1.setEnabled(true);jComboBox2.setEnabled(true);jComboBox3.setEnabled(true);
jComboBox4.setEnabled(true);jButton26.setEnabled(true);
}
private void DeActivateAll(){
jButton1.setEnabled(false); jButton2.setEnabled(false); jButton3.setEnabled(false);
jButton4.setEnabled(false); jButton5.setEnabled(false); jButton6.setEnabled(false);
jButton7.setEnabled(false); jButton8.setEnabled(false); jButton9.setEnabled(false);
jButton10.setEnabled(false); jButton11.setEnabled(false); jButton12.setEnabled(false);
jButton13.setEnabled(false); jButton14.setEnabled(false); jButton15.setEnabled(false);
jButton16.setEnabled(false); jButton17.setEnabled(false); jButton18.setEnabled(false);
jButton19.setEnabled(false); jButton20.setEnabled(false); jButton21.setEnabled(false);
jButton22.setEnabled(false); jButton23.setEnabled(false); jButton24.setEnabled(false);
jButton1.setVisible(false);jButton2.setVisible(false);jButton3.setVisible(false);
jButton4.setVisible(false); jButton5.setVisible(false); jButton6.setVisible(false);
jButton7.setVisible(false); jButton8.setVisible(false); jButton9.setVisible(false);
jButton10.setVisible(false); jButton11.setVisible(false); jButton12.setVisible(false);
jButton13.setVisible(false); jButton14.setVisible(false); jButton15.setVisible(false);
jButton16.setVisible(false); jButton17.setVisible(false); jButton18.setVisible(false);
jButton19.setVisible(false); jButton20.setVisible(false); jButton21.setVisible(false);
jButton22.setVisible(false); jButton23.setVisible(false); jButton24.setVisible(false);
jTextField5.setVisible(false); jTextField5.setText(null); jLabel2.setVisible(false);
jRadioButton1.setVisible(false);jRadioButton2.setVisible(false);jRadioButton3.setVisible(false);
jRadioButton4.setVisible(false);jRadioButton5.setVisible(false);
jLabel3.setVisible(false);jLabel4.setVisible(false);jLabel5.setVisible(false);jLabel6.setVisible(false);
jComboBox1.setVisible(false);jComboBox2.setVisible(false);jComboBox3.setVisible(false);
jComboBox4.setVisible(false);jButton26.setVisible(false);jTextField6.setVisible(false);
jRadioButton1.setText(null);jRadioButton1.setIcon(null);
jRadioButton2.setText(null);jRadioButton2.setIcon(null);
jRadioButton3.setText(null);jRadioButton3.setIcon(null);
jRadioButton4.setText(null);jRadioButton4.setIcon(null);
jLabel2.setIcon(null); jLabel10.setVisible(false); jLabel10.setIcon(null);
jLabel15.setVisible(false);jLabel16.setVisible(false);jLabel17.setVisible(false);
jLabel18.setVisible(false);jLabel19.setVisible(false);jLabel20.setVisible(false);
jLabel21.setVisible(false);jLabel22.setVisible(false);jLabel23.setVisible(false);
jLabel24.setVisible(false);jLabel25.setVisible(false);jLabel26.setVisible(false);
jLabel27.setVisible(false);jCheckBox1.setVisible(false);jCheckBox2.setVisible(false);
jCheckBox3.setVisible(false);jCheckBox4.setVisible(false);jCheckBox5.setVisible(false);
jLabel29.setVisible(false);jLabel30.setVisible(false);jLabel31.setVisible(false);
jLabel32.setText(null);
try {
URL url = new URL(URI1+"smileys/thinking.png");
BufferedImage smiley = ImageIO.read(url);
java.awt.Image smiley2=smiley.getScaledInstance(150,150,BufferedImage.SCALE_SMOOTH);
Icon icon=new ImageIcon(smiley2);
jLabel32.setIcon(icon);
} catch (IOException e) {}
}
private void ChooseGame(){
Random generator = new Random();
game=generator.nextInt(8); //System.out.println("Παιχνίδι: "+game);
jButton27.setVisible(true);
//if ((game==0 || game==1 || game==6) && indexnoimages==0) game=2;
//if ((game==4 || game==5) && indeximages==0) game=3;
//System.out.println("Game="+game);
frameNumber=frameNumber-1;
jButton25.setVisible(false);
num++;
int num_1=num+1;
//game=2;
jLabel1.setText("Ερώτηση: "+num_1+"η");
if (game==0) {GamePlayed[num]="Πολλαπλή Επιλογή (Multiple Choice)";MultipleChoice();}
else if (game==1) {GamePlayed[num]="Πολλαπλή Επιλογή με Αναγραμματισμό (Anagram Game)";Anagram();}
else if (game==2) {GamePlayed[num]="Κρεμάλα (Hangman)";Hangman();}
else if (game==3) {GamePlayed[num]="Κρεμάλα με εικόνα (Hangman)";HangmanwithPicture();}
else if (game==4) {GamePlayed[num]="Πολλαπλή Επιλογή (1 Εικόνα, 4 Επιλογές)";Flag();}
else if (game==5) {GamePlayed[num]="Πολλαπλή Επιλογή (Επιλογή από 4 Εικόνες)";Flag2();}
else if (game==6) {GamePlayed[num]="Αντιστοίχιση";Matching();}
else if (game==7) {GamePlayed[num]="Πολλαπλή Επιλογή με περισσότερες από 1 σωστές απαντήσεις";MultipleChoicewithDuplicates();}
}
@Override
public void start() { startAnimation(); }
public void stop() { stopAnimation(); }
public synchronized void startAnimation() {
if (frozen) {
}
else {
if (!timer.isRunning()) {
timer.start();
}
}
}
public synchronized void stopAnimation() {
if (timer.isRunning()) {
timer.stop();
}
}
@Override
public void actionPerformed(ActionEvent e) {
frameNumber++;
frameNumber1[num]++;
jLabel7.setText("Συνολικός Χρόνος: " + frameNumber+ " ''");
jLabel8.setText("Χρόνος: " + frameNumber1[num]+ " ''");
}
public void EndGame() {
if (GameOver==1) {TimesPlayed=total;}
jLabel28.setVisible(false); jButton27.setVisible(false);jLabel32.setVisible(false);
JOptionPane.showMessageDialog(this, name+", το παιχνίδι τελείωσε!");
//PrintStream stdout = System.out;
String correctness=""; String name1=name;
Calendar calendar = Calendar.getInstance();
Date date = calendar.getTime();
String date1=date.toString();
/*date1=date1.replace('/', '.'); date1=date1.replace(':', '.');
name=name.replace('/', '.'); name=name.replace('\\', '.');
name=name.replace(':', '.'); name=name.replace('*', '.');
name=name.replace('?', '.'); name=name.replace('"', '.');
name=name.replace('<', '.'); name=name.replace('>', '.');
name=name.replace('|', '.');
String filename=name+" "+date1+".txt";
String path2=JOptionPane.showInputDialog(null,"Γράψε το path στο οποίο θέλεις να σωθούν τα αποτελέσματα (π.χ. C:\\results). To default path είναι το:C:\\temp");
if (path2==null | "".equals(path2)) {path2="C:/temp";}
new File(path2).mkdir();
String path=path2+"/"+filename;
try{
File file=new File(path);
OutputStream output = new FileOutputStream(file);
PrintStream printOut = new PrintStream(output);
OutputStreamWriter out = new OutputStreamWriter(printOut, "Cp1253");
System.setOut(printOut);
}catch (Exception e){ }*/
// jTextArea1.setText("Ημερομηνία: "+date1);
//jTextArea1.setText("Όνομα παίχτη: "+name1);
String text= "Ημερομηνία: "+date1;
text=text+"\n"+"Όνομα παίχτη: "+name1;
text=text+"\n"+"Συνολικός χρόνος: "+frameNumber;
text=text+"\n"+"Πλήθος ερωτήσεων που απαντήθηκαν: "+total;
text=text+"\n"+"Απαντήθηκαν σωστά: "+score+" ερωτήσεις.";
int wrong=total-score;
text=text+"\n"+"Απαντήθηκαν λάθος: "+wrong+" ερωτήσεις.";
double score1=score, wrong1=wrong,percentage=(score1/total)*100,percentage2=(wrong1/total)*100;
DecimalFormat df = new DecimalFormat("#.##");
text=text+"\n"+"To ποσοστό των σωστών απαντήσεων ήταν: "+df.format(percentage)+"%";
text=text+"\n"+"To ποσοστό των λάθος απαντήσεων ήταν: "+df.format(percentage2)+"%";
text=text+"\n"+"----------------------------------------------------------------------------------------------------------------------------------------";
int time=0;
for (int i=0;i<TimesPlayed;i++) {
if (correct[i]==true) correctness="Σωστά";
else if (correct[i]==false) correctness="Λάθος";
int num1=i+1; time=time+frameNumber1[i];
text=text+"\n"+"Η "+num1+"η ερώτηση απαντήθηκε "+correctness+" σε "+frameNumber1[i]+" δευτερόλεπτα";
text=text+"\n"+"Το παιχνίδι που παίχτηκε ήταν το: "+GamePlayed[i];
text=text+"\n"+"Η κατηγορία του παιχνιδιού ήταν: "+Category[i];
text=text+"\n"+question[i]; text=text+"\n"+answer[i];
text=text+"\n"+"----------------------------------------------------------------------------------------------------------------------------------------";
}
int TimesPlayed_1=TimesPlayed+1;
if (GameOver==1 && time!=frameNumber) {
text=text+"\n"+"Η "+TimesPlayed_1+"η ερώτηση δεν απαντήθηκε. Χρόνος παραμονής στην ερώτηση: "+frameNumber1[TimesPlayed]+" δευτερόλεπτα";
text=text+"\n"+"Το παιχνίδι ήταν το: "+GamePlayed[TimesPlayed];
text=text+"\n"+"Η κατηγορία του παιχνιδιού ήταν: "+Category[TimesPlayed];
text=text+"\n"+question[TimesPlayed]; text=text+"\n"+answer[TimesPlayed];
text=text+"\n"+"----------------------------------------------------------------------------------------------------------------------------------------";
}
DeActivateAll();
jTextArea1.setText(text);
jTextField1.setVisible(false);
jLabel8.setVisible(false);
jButton25.setVisible(false);
//JOptionPane.showMessageDialog(this, "Το αρχείο με τα στατιστικά στοιχεία είναι έτοιμο!");
jTextField2.setVisible(false);//jTextField2.setText("Γεια σου!!!!!!!!!!");
//System.setOut(stdout);
jScrollPane1.setVisible(true);
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton10;
private javax.swing.JButton jButton11;
private javax.swing.JButton jButton12;
private javax.swing.JButton jButton13;
private javax.swing.JButton jButton14;
private javax.swing.JButton jButton15;
private javax.swing.JButton jButton16;
private javax.swing.JButton jButton17;
private javax.swing.JButton jButton18;
private javax.swing.JButton jButton19;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton20;
private javax.swing.JButton jButton21;
private javax.swing.JButton jButton22;
private javax.swing.JButton jButton23;
private javax.swing.JButton jButton24;
private javax.swing.JButton jButton25;
private javax.swing.JButton jButton26;
private javax.swing.JButton jButton27;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JButton jButton5;
private javax.swing.JButton jButton6;
private javax.swing.JButton jButton7;
private javax.swing.JButton jButton8;
private javax.swing.JButton jButton9;
private javax.swing.JCheckBox jCheckBox1;
private javax.swing.JCheckBox jCheckBox2;
private javax.swing.JCheckBox jCheckBox3;
private javax.swing.JCheckBox jCheckBox4;
private javax.swing.JCheckBox jCheckBox5;
private javax.swing.JComboBox jComboBox1;
private javax.swing.JComboBox jComboBox2;
private javax.swing.JComboBox jComboBox3;
private javax.swing.JComboBox jComboBox4;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel14;
private javax.swing.JLabel jLabel15;
private javax.swing.JLabel jLabel16;
private javax.swing.JLabel jLabel17;
private javax.swing.JLabel jLabel18;
private javax.swing.JLabel jLabel19;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel20;
private javax.swing.JLabel jLabel21;
private javax.swing.JLabel jLabel22;
private javax.swing.JLabel jLabel23;
private javax.swing.JLabel jLabel24;
private javax.swing.JLabel jLabel25;
private javax.swing.JLabel jLabel26;
private javax.swing.JLabel jLabel27;
private javax.swing.JLabel jLabel28;
private javax.swing.JLabel jLabel29;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel30;
private javax.swing.JLabel jLabel31;
private javax.swing.JLabel jLabel32;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JRadioButton jRadioButton1;
private javax.swing.JRadioButton jRadioButton2;
private javax.swing.JRadioButton jRadioButton3;
private javax.swing.JRadioButton jRadioButton4;
private javax.swing.JRadioButton jRadioButton5;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
private javax.swing.JTextField jTextField5;
private javax.swing.JTextField jTextField6;
// End of variables declaration//GEN-END:variables
}
| ComradeHadi/DBpedia-Game | ssg/src/Games/Game.java |
2,500 | package org.dklisiaris.downtown.maps;
import org.dklisiaris.downtown.FavsActivity;
import org.dklisiaris.downtown.GlobalData;
import org.dklisiaris.downtown.MainActivity;
import org.dklisiaris.downtown.MoreActivity;
import org.dklisiaris.downtown.R;
import org.dklisiaris.downtown.SearchActivity;
import org.dklisiaris.downtown.SingleListItem;
import org.dklisiaris.downtown.adapters.CustomSuggestionsAdapter;
import org.dklisiaris.downtown.db.Category;
import org.dklisiaris.downtown.db.Company;
import org.dklisiaris.downtown.db.DBHandler;
import org.dklisiaris.downtown.widgets.MultiSpinner;
import org.dklisiaris.downtown.widgets.MultiSpinner.MultiSpinnerListener;
import java.util.ArrayList;
import java.util.Locale;
import org.w3c.dom.Document;
import android.animation.IntEvaluator;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.SearchManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PointF;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBar.OnNavigationListener;
import android.support.v7.widget.SearchView;
import android.util.Log;
import android.util.SparseArray;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.LocationSource;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.Circle;
import com.google.android.gms.maps.model.CircleOptions;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import com.google.maps.android.clustering.Cluster;
import com.google.maps.android.clustering.ClusterManager;
public class Nearby extends AbstractMapActivity implements
OnNavigationListener, OnInfoWindowClickListener, LocationSource, LocationListener,
ClusterManager.OnClusterClickListener<CompanyMarker>,
ClusterManager.OnClusterInfoWindowClickListener<CompanyMarker>,
ClusterManager.OnClusterItemClickListener<CompanyMarker>,
ClusterManager.OnClusterItemInfoWindowClickListener<CompanyMarker>,MultiSpinnerListener,
SearchView.OnQueryTextListener{
private static final String STATE_NAV="nav";
/*
private static final int[] MAP_TYPE_NAMES= { R.string.normal,
R.string.hybrid, R.string.satellite, R.string.terrain };
private static final int[] MAP_TYPES= { GoogleMap.MAP_TYPE_NORMAL,
GoogleMap.MAP_TYPE_HYBRID, GoogleMap.MAP_TYPE_SATELLITE,
GoogleMap.MAP_TYPE_TERRAIN };
*/
private static final String[] DIRECTION_MODE_NAMES= {"Αυτοκίνητο","Πεζός","Λεωφορείο"};
private static final String[] DIRECTION_MODES_TYPES= {GMapV2Direction.MODE_DRIVING,
GMapV2Direction.MODE_WALKING,GMapV2Direction.MODE_TRANSIT};
SearchView searchView;
MenuItem searchMenuItem;
protected String directionMode = GMapV2Direction.MODE_DRIVING;
private GoogleMap map=null;
private OnLocationChangedListener mapLocationListener=null;
private LocationManager locMgr=null;
private Criteria crit=new Criteria();
private AlertDialog alert=null;
Location currentLocation=null;
protected ClusterManager<CompanyMarker> mClusterManager;
protected ArrayList<Company> nearComps=null;
protected Polyline currentPolyline=null;
protected Marker selectedMarker=null;
protected SparseArray<String> sparse=null;
protected ArrayList<String> selectedCategories = null;
int selectedID;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
supportRequestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
if (readyToGo()) {
setContentView(R.layout.map_fragment);
SupportMapFragment mapFrag=
(SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
initListNav();
initCategorySpinner();
map=mapFrag.getMap();
if (savedInstanceState == null) {
CameraUpdate center=
CameraUpdateFactory.newLatLng(new LatLng(37.9928920,
23.6772921));
CameraUpdate zoom=CameraUpdateFactory.zoomTo(15);
map.moveCamera(center);
map.animateCamera(zoom);
}
//map.setInfoWindowAdapter(new PopupAdapter(getLayoutInflater()));
//map.setOnInfoWindowClickListener(this);
locMgr=(LocationManager)getSystemService(LOCATION_SERVICE);
crit.setAccuracy(Criteria.ACCURACY_FINE);
map.setMyLocationEnabled(true);
map.getUiSettings().setMyLocationButtonEnabled(false);
mClusterManager = new ClusterManager<CompanyMarker>(this, map);
map.setOnCameraChangeListener(mClusterManager);
map.setOnMarkerClickListener(mClusterManager);
map.setOnInfoWindowClickListener(this);
mClusterManager.setOnClusterClickListener(this);
mClusterManager.setOnClusterInfoWindowClickListener(this);
mClusterManager.setOnClusterItemClickListener(this);
mClusterManager.setOnClusterItemInfoWindowClickListener(this);
if ( !locMgr.isProviderEnabled( LocationManager.GPS_PROVIDER ) &&
!locMgr.isProviderEnabled( LocationManager.NETWORK_PROVIDER ) ) {
buildAlertMessageNoGps();
}
}
else{
Log.e("NEARBY", "Error! Something is missing!");
Toast.makeText(this, R.string.no_maps, Toast.LENGTH_LONG).show();
this.finish();
}
}
@SuppressLint("NewApi")
@Override
public void onResume() {
super.onResume();
String provider=null;
for(String s : locMgr.getProviders(true)){
Log.d("PROVIDERS",s);
}
if(locMgr != null)
{
boolean networkIsEnabled = locMgr.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
boolean gpsIsEnabled = locMgr.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean passiveIsEnabled = locMgr.isProviderEnabled(LocationManager.PASSIVE_PROVIDER);
if(networkIsEnabled)
{
locMgr.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 60*1000L, 10.0F, this, null);
provider=LocationManager.NETWORK_PROVIDER;
}
else if(gpsIsEnabled)
{
locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60*1000L, 10.0F, this, null);
provider=LocationManager.GPS_PROVIDER;
}
else if(passiveIsEnabled)
{
locMgr.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, 60*1000L, 10.0F, this, null);
provider=LocationManager.PASSIVE_PROVIDER;
}
else
{
Toast.makeText(this, "Δεν υπάρχει ενεργοποιημένη υπηρεσία εύρεσης τοποθεσίας.", Toast.LENGTH_LONG).show();
}
}
else
{
Toast.makeText(this, "Δεν υπάρχει υπηρεσία εύρεσης τοποθεσίας στη συσκευή σας.", Toast.LENGTH_LONG).show();
}
/*
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
locMgr.requestLocationUpdates(0L, 0.0f, crit, this, null);
}else{
locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER,0L, 0.0f, this, null);
}
*/
map.setLocationSource(this);
if(provider!=null)
currentLocation = locMgr.getLastKnownLocation(provider);
if(currentLocation!=null)map.getUiSettings().setMyLocationButtonEnabled(true);
//drawCircle();
//Toast.makeText(this, "Lat: "+currentLocation.getLatitude()+" Long: "+currentLocation.getLongitude(), Toast.LENGTH_LONG).show();
if(currentLocation!=null){
new MarkerLoader().execute(currentLocation);
}
else Toast.makeText(this, "Η τοποθεσία σας δεν βρέθηκε. Ελέγξτε τις ρυθμίσεις gps.", Toast.LENGTH_LONG).show();
}
@Override
public void onPause() {
map.setMyLocationEnabled(false);
map.setLocationSource(null);
locMgr.removeUpdates(this);
if(alert != null) { alert.dismiss(); }
super.onPause();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_general, menu);
// Get the SearchView and set the searchable configuration
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.menu_search));
// Assumes current activity is the searchable activity
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(false); // Do not iconify the widget; expand it by default
//Create the search view
//searchView = new SearchView(getSupportActionBar().getThemedContext());
searchView.setQueryHint(getString(R.string.query_hint));
searchView.setOnQueryTextListener(this);
searchView.setSuggestionsAdapter(new CustomSuggestionsAdapter(this, searchManager.getSearchableInfo(getComponentName()), searchView));
//searchView.setIconified(true);
AutoCompleteTextView searchText = (AutoCompleteTextView) searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
searchText.setHintTextColor(getResources().getColor(R.color.white));
searchMenuItem = menu.findItem(R.id.menu_search);
searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean queryTextFocused) {
if(!queryTextFocused) {
MenuItemCompat.collapseActionView(searchMenuItem);
searchView.setQuery("", false);
}
}
});
//searchView.setSubmitButtonEnabled(true);
//SearchManager searchManager = (SearchManager)getSystemService(Context.SEARCH_SERVICE);
//SearchableInfo info = searchManager.getSearchableInfo(getComponentName());
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
case R.id.toMainHome:
Intent upIntent = new Intent(this,MainActivity.class);
upIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(upIntent);
finish();
return true;
case R.id.favourites:
Intent favIntent = new Intent(this,FavsActivity.class);
favIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(favIntent);
finish();
return true;
case R.id.FreeEntry:
Intent i = new Intent(this,MoreActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.putExtra("title","entry");
startActivity(i);
//finish();
return true;
case R.id.MoreInfo:
Intent mi = new Intent(this,MoreActivity.class);
mi.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
mi.putExtra("title","info");
startActivity(mi);
return true;
case R.id.Contact:
Intent ci = new Intent(this,MoreActivity.class);
ci.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
ci.putExtra("title","contact");
startActivity(ci);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public boolean onQueryTextSubmit(String query) {
if (query.length()<3){
Toast t = Toast.makeText(this, "Απαιτούνται τουλαχιστον 3 χαρακτήρες", Toast.LENGTH_LONG);
t.setGravity(Gravity.TOP|Gravity.CENTER_HORIZONTAL, 0, 0);
t.show();
}else{
Intent sIntent = new Intent(this,SearchActivity.class);
sIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
sIntent.putExtra("query",query);
//searchView.setIconified(true);
MenuItemCompat.collapseActionView(searchMenuItem);
startActivity(sIntent);
}
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
// TODO Auto-generated method stub
return false;
}
@Override
public void onItemsSelected(boolean[] selected) {
selectedCategories = new ArrayList<String>();
/* If -all categories- is selected we set selectedCategories null. this value will be used in query building. */
if(selected[0]){
selectedCategories=null;
}
/* Else we add the ids of selected categories to array list */
else{
for(int i=1;i<selected.length;i++){
if(selected[i]){
selectedCategories.add(sparse.get(i));
}
}
}
//Toast.makeText(this, "Activated: "+activated, Toast.LENGTH_LONG).show();
mClusterManager.clearItems();
//new MarkerLoader().execute(currentLocation);
onResume();
}
@Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
//map.setMapType(MAP_TYPES[itemPosition]);
directionMode = DIRECTION_MODES_TYPES[itemPosition];
return(true);
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putInt(STATE_NAV,
getSupportActionBar().getSelectedNavigationIndex());
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
getSupportActionBar().setSelectedNavigationItem(savedInstanceState.getInt(STATE_NAV));
}
@Override
public void onInfoWindowClick(Marker marker) {
int selectedPos=0;
/* Finding position of selected company in nearby companies collection*/
for(int i=0 ; i<nearComps.size() ; i++){
if(nearComps.get(i).getId()==selectedID){
selectedPos=i;
break;
}
}
((GlobalData)getApplicationContext()).setSelected_companies(nearComps);
Intent i = new Intent(getApplicationContext(), SingleListItem.class);
// sending data to new activity
i.putExtra("pos",selectedPos);
startActivity(i);
//Toast.makeText(this, "go there "+marker.getTitle(), Toast.LENGTH_LONG).show();
}
@Override
public void activate(OnLocationChangedListener listener) {
this.mapLocationListener=listener;
}
@Override
public void deactivate() {
this.mapLocationListener=null;
}
@Override
public void onLocationChanged(Location location) {
Log.d("LOC CHANGED!","");
if (mapLocationListener != null) {
mapLocationListener.onLocationChanged(location);
LatLng latlng=
new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate cu=CameraUpdateFactory.newLatLng(latlng);
map.animateCamera(cu);
}
}
@Override
public void onProviderDisabled(String provider) {
// unused
}
@Override
public void onProviderEnabled(String provider) {
// unused
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// unused
}
private void initCategorySpinner(){
DBHandler db = DBHandler.getInstance(this);
ArrayList<Category> cats = db.getCategories("cat_parent_id is not null");
ArrayList<String> items=new ArrayList<String>();
if(sparse==null)
sparse = new SparseArray<String>();
/* We add an extra item which represents ALL categories */
items.add("Όλες οι κατηγορίες");
/* We also put it in first (zero) position in sparse array*/
sparse.put(0, "0");
/*
* BE CAREFUL! We count from 0 so every category gets added to items
* but we put them in sparse shifted by one because zero position is taken by all categories item.
* */
for (int i=0; i<cats.size(); i++) {
items.add(cats.get(i).getCat_name());
sparse.put(i+1,Integer.toString(cats.get(i).getCat_id()));
}
MultiSpinner multiSpinner = (MultiSpinner) findViewById(R.id.multi_spinner);
multiSpinner.setItems(items,"Όλες οι κατηγορίες",this);
}
private void initListNav() {
ArrayList<String> items=new ArrayList<String>();
ArrayAdapter<String> nav=null;
ActionBar bar=getSupportActionBar();
/*
for (int type : MAP_TYPE_NAMES) {
items.add(getString(type));
}*/
for (String m : DIRECTION_MODE_NAMES) {
items.add(m);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
nav=
new ArrayAdapter<String>(
bar.getThemedContext(),
android.R.layout.simple_spinner_item,
items);
}
else {
nav=
new ArrayAdapter<String>(
this,
android.R.layout.simple_spinner_item,
items);
}
nav.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
bar.setListNavigationCallbacks(nav, this);
}
@SuppressWarnings("unused")
private void addMarker(GoogleMap map, double lat, double lon,
int title, int snippet) {
map.addMarker(new MarkerOptions().position(new LatLng(lat, lon))
.title(getString(title))
.snippet(getString(snippet)));
}
private void buildAlertMessageNoGps() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Ενεργοποίηση GPS")
.setMessage("Το GPS της συσκευής σας φαίνεται να είναι απενεργοποιημένο. Θέλετε να το ενεργοποιήσετε?")
.setCancelable(false)
.setPositiveButton("Ναι", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, final int id) {
startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
})
.setNegativeButton("Όχι", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, final int id) {
dialog.cancel();
}
});
alert = builder.create();
alert.show();
}
@SuppressLint("NewApi")
private void drawCircle(){
final Circle circle = map.addCircle(new CircleOptions()
.center(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()))
.strokeColor(Color.BLUE).radius(100));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
ValueAnimator vAnimator = new ValueAnimator();
vAnimator.setRepeatCount(0);
vAnimator.setRepeatMode(ValueAnimator.RESTART); /* PULSE */
vAnimator.setIntValues(0, 100);
vAnimator.setDuration(1000);
vAnimator.setEvaluator(new IntEvaluator());
vAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
vAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
float animatedFraction = valueAnimator.getAnimatedFraction();
// Log.e("", "" + animatedFraction);
circle.setRadius(animatedFraction * 100);
}
});
vAnimator.start();
}
}
/**
* Calculates the end-point from a given source at a given range (meters)
* and bearing (degrees). This methods uses simple geometry equations to
* calculate the end-point.
*
* @param point Point of origin
* @param range Range in meters
* @param bearing Bearing in degrees
* @return End-point from the source given the desired range and bearing.
*/
public static PointF calculateDerivedPosition(PointF point, double range, double bearing)
{
double EarthRadius = 6371000; // m
double latA = Math.toRadians(point.x);
double lonA = Math.toRadians(point.y);
double angularDistance = range / EarthRadius;
double trueCourse = Math.toRadians(bearing);
double lat = Math.asin(
Math.sin(latA) * Math.cos(angularDistance) +
Math.cos(latA) * Math.sin(angularDistance)
* Math.cos(trueCourse));
double dlon = Math.atan2(
Math.sin(trueCourse) * Math.sin(angularDistance)
* Math.cos(latA),
Math.cos(angularDistance) - Math.sin(latA) * Math.sin(lat));
double lon = ((lonA + dlon + Math.PI) % (Math.PI * 2)) - Math.PI;
lat = Math.toDegrees(lat);
lon = Math.toDegrees(lon);
PointF newPoint = new PointF((float) lat, (float) lon);
return newPoint;
}
protected class MarkerLoader extends AsyncTask<Location,CompanyMarker,ArrayList<CompanyMarker>>{
DBHandler db;
ArrayList<CompanyMarker> cms = new ArrayList<CompanyMarker>();
double t1,t2;
@Override
protected void onPreExecute() {
super.onPreExecute();
setSupportProgressBarIndeterminateVisibility(true);
t1 = System.nanoTime();
}
@Override
protected ArrayList<CompanyMarker> doInBackground(Location... loc) {
double lat = loc[0].getLatitude();
double lon = loc[0].getLongitude();
PointF center = new PointF((float) lat, (float) lon);
final double mult = 1; // mult = 1.1; is more reliable
int range = 1*1000; //1km around center
PointF p1 = calculateDerivedPosition(center, mult * range, 0);
PointF p2 = calculateDerivedPosition(center, mult * range, 90);
PointF p3 = calculateDerivedPosition(center, mult * range, 180);
PointF p4 = calculateDerivedPosition(center, mult * range, 270);
String whereClause =
"co_latitude > " + String.valueOf(p3.x) + " AND "
+ "co_latitude < " + String.valueOf(p1.x) + " AND "
+ "co_longitude < " + String.valueOf(p2.y) + " AND "
+ "co_longitude > " + String.valueOf(p4.y);
String whereCat = "";
if(selectedCategories!=null){
boolean isFirst=true;
for(String sc : selectedCategories){
if(isFirst){
whereCat += "( cc.category_id='"+sc+"'";
isFirst=false;
}
else{
whereCat += " OR cc.category_id='"+sc+"'";
}
}
whereCat += " ) AND ";
}
whereClause = whereCat + whereClause;
Log.d("--- Query ---", whereClause);
//clause to get companies in a 20km radius away from user - NOT WORKING in sqlite
/*
String whereClause = "ACOS( "+
"SIN( RADIANS( `latitude` ) ) * SIN( RADIANS( "+lat+" ) ) + COS( RADIANS( `latitude` ) ) * "+
"COS( RADIANS( "+lat+" )) * COS( RADIANS( `longitude` ) - RADIANS( "+lon+" )) ) * 6380 < 20";
*/
try{
db = DBHandler.getInstance(getApplicationContext());
if(selectedCategories!=null){
nearComps = db.getCompaniesJoinCCWhere(whereClause);
}else{
nearComps = db.getCompaniesWhere(whereClause);
}
}catch(Exception e){
e.printStackTrace();
}finally{
db.close();
}
//List<Marker> markers = new ArrayList<Marker>();
if(nearComps!=null && nearComps.size()>0){
for(Company c : nearComps){
CompanyMarker m = new CompanyMarker(c.getId(), c.getName(),
c.getAddress(),
c.getLatitude(),
c.getLongitude());
//mClusterManager.addItem(m);
//publishProgress(m);
cms.add(m);
/*
Marker m = map.addMarker(new MarkerOptions()
.position(new LatLng(c.getLatitude(),c.getLongitude()))
.title(c.getName())
.snippet(c.getAddress() +", "+c.getArea()));
markers.add(m);
*/
}
}
//Log.d("Num of markers",""+nearComps.size());
return cms;
}
protected void onProgressUpdate(CompanyMarker... companyMarkers){
//mClusterManager.addItem(companyMarkers[0]);
/*
map.addMarker(new MarkerOptions()
.position(companyMarkers[0].getPosition())
.title(companyMarkers[0].getTitle())
.snippet(companyMarkers[0].getSnippet()));
*/
}
protected void onPostExecute(ArrayList<CompanyMarker> cms){
if(cms!=null && cms.size()>0){
for(CompanyMarker cm : cms){
mClusterManager.addItem(cm);
}
}
setSupportProgressBarIndeterminateVisibility(false);
mClusterManager.cluster();
t2 = (System.nanoTime() - t1)/1000000.0;
//Log.d("---- Marker Loader completed in ----", Double.toString(t2));
}
}
@Override
public void onClusterItemInfoWindowClick(CompanyMarker item) {
}
@Override
public boolean onClusterItemClick(CompanyMarker item) {
//Toast.makeText(this, item.getTitle(), Toast.LENGTH_LONG).show();
//IconGenerator tc = new IconGenerator(this);
//Bitmap bmp = tc.makeIcon("hello"); // pass the text you want.
if(selectedMarker != null)
selectedMarker.remove();
selectedMarker = map.addMarker(new MarkerOptions()
.position(item.getPosition())
.title(item.getTitle())
.snippet(item.getSnippet()));
selectedMarker.showInfoWindow();
selectedID=item.getId();
LatLng from = new LatLng(currentLocation.getLatitude(),currentLocation.getLongitude());
LatLng[] fromTo = {from, item.getPosition()};
new DirectionsLoader().execute(fromTo);
return false;
}
@Override
public void onClusterInfoWindowClick(Cluster<CompanyMarker> cluster) {
}
@Override
public boolean onClusterClick(Cluster<CompanyMarker> cluster) {
return false;
}
protected class DirectionsLoader extends AsyncTask<LatLng,Void,DirectionsInfo>{
@Override
protected DirectionsInfo doInBackground(LatLng... params) {
GMapV2Direction md = new GMapV2Direction();
Document doc = md.getDocument(params[0], params[1], directionMode);
ArrayList<LatLng> directionPoint = md.getDirection(doc);
PolylineOptions rectLine = new PolylineOptions().width(3).color(Color.RED);
for(int i = 0 ; i < directionPoint.size() ; i++) {
rectLine.add(directionPoint.get(i));
}
DirectionsInfo directionsInfo = new DirectionsInfo(
null,md.getDurationValue(doc),
null,md.getDistanceValue(doc),
rectLine);
return directionsInfo;
}
protected void onPostExecute(DirectionsInfo directionsInfo){
if(currentPolyline!=null){
currentPolyline.remove();
}
currentPolyline = map.addPolyline(directionsInfo.getPolylineOptions());
double dist = (double)directionsInfo.getDistanceValue() * 1.0/1000.0;
int durat = (int)Math.round(directionsInfo.getDurationValue() * 1.0/60.0);
if(selectedMarker!=null){
selectedMarker.hideInfoWindow();
String snip = selectedMarker.getSnippet();
selectedMarker.setSnippet(snip+ ", Απόσταση: "+String.format(Locale.ENGLISH, "%.1f", dist)+" χλμ. Χρόνος Άφιξης: "+
durat+" λεπτα");
selectedMarker.showInfoWindow();
}
}
}
}
| manisoni28/downtown | downtown/src/main/java/org/dklisiaris/downtown/maps/Nearby.java |
2,501 | package org.teiath.ellak.ellakandroideducation;
import android.os.Bundle;
import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.content.Intent;
import android.graphics.Color;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBarActivity;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Timer;
import java.util.TimerTask;
/**
* Η MainScreen είναι η βασική activity της εφαρμογής. Παρουσιάζει τις ερωτήσεις και τις πιθανές απαντήσεις, καταγράφει
* τις απαντήσεις του χρήστη και τις αξιολογεί, μετράει το χρόνο, κ.λ.π.
* Τρέχει σε δύο καταστάσεις λειτουργίας: Σε κατάσταση "Εκπαίδευσης" και σε κατάσταση "Εξέτασης". Στην κατάσταση
* εκπαίδευσης δεν μετριέται χρόνος και μετά την καταχώρηση απάντησης από τον χρήστη παρουσιάζεται η σωστή απάντηση.
* Για την υλοποίηση της activity προτείνονται οι ακόλουθες προδιαγραφές: <ul>
* <li>H activity να καταλαμβάνει όλη την οθόνη και το κουμπί "back" να μην δουλεύει</li>
* <li>Να υπάρχει κουμπί καταχώρησης απάντησης ώστε αν ο χρήστης πατήσει λάθος απάντηση να μπορεί να
* διορθώσει την επιλογή του. Με το κουμπί καταχώρησης οριστικοποιείται η επιλογή.</li>
* <li>Να φαίνεται ο αριθμός της τρέχουσας ερώτησης και ο συνολοκός αριθμός ερωτήσεων</li>
* <li>Οι απαντήσεις να τοποθετηθούν σε ScrollView ώστε αν δεν χωράνε όλες στην οθόνη να σκρολάρει μόνο το τμήμα των
* απαντήσεων.</li>
* <li>Ο χρήστης να μπορεί να αφήσει μία ερώτηση για αργότερα και να προχωρήσει στην επόμενη. Μετά την τελευταία
* το πρόγραμμα θα γυρνά στην πρώτη που δεν έχει απαντηθεί και μετά στην επόμενη, κ.ο.κ.</li>
* <li>Ο χρήστης δεν θα μπορεί να γυρίσει σε προηγούμενη ερώτηση (πίσω)</li>
* <li>Ο υπολοιπόμενος χρόνος θα παρουσιάζεται με μορφή ProgressBar ή αντίστοιχη και όχι σε μορφή κειμένου.</li>
* </ul>
* Η Main Screen οδηγεί στην Results Screen
*/
public class MainScreen extends ActionBarActivity implements View.OnClickListener
{
LinearLayout llAnswers ;
ScrollView svAnswers ;
ImageView ivImage ;
TextView tvaNumOfQuestion ;
TextView tvaQuestion ;
ImageButton ibConfirm,ibNext;
ProgressBar pb;
Button bAns[] ;
Timer myTimer;
TimerTask myTask;
int count=0;
int corAns=-1 ; //-1 Απάντηση χρήστη
int sumOfButtons ;
ManageQuestions manQuestions ;
CountDownTimer cdtNextQuestion ;
boolean onClickIsNotBusy = true ;
Toast toastMessage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lay_main);
String testType,subject ;
Bundle bu = getIntent().getExtras();
testType = (String)bu.get("option") ;
subject = (String)bu.get("field") ;
/*if (bu != null)
{
testType = bu.getInt("TestType") ;
subject = bu.getInt("Subject") ; ;
}
else
{
testType = new Random().nextInt(2) ;
subject = 0 ;
}*/
manQuestions = new ManageQuestions(this,testType,subject) ;
ivImage = (ImageView) findViewById(R.id.Eikona) ;
tvaNumOfQuestion = (TextView) findViewById(R.id.arithmosErwtisis) ;
tvaQuestion = (TextView) findViewById(R.id.Erwtisi) ;
tvaQuestion.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
svAnswers = (ScrollView) findViewById(R.id.scrollView) ;
ibConfirm = (ImageButton) findViewById(R.id.confirm) ;
pb = (ProgressBar) findViewById(R.id.pb);
ibNext = (ImageButton) findViewById(R.id.next) ;
llAnswers = (LinearLayout)findViewById(R.id.linearLayout2);
sumOfButtons = manQuestions.getMaxAnswers() ;
bAns = new Button[sumOfButtons] ;
for (int i=0;i<sumOfButtons;i++) {
bAns[i] = new Button(this) ;
bAns[i].setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
bAns[i].setOnClickListener(this);
}
ibConfirm.setOnClickListener(this);
ibNext.setOnClickListener(this);
disableConfirm();
prepareToastMessage() ;
showToastMessage(manQuestions.getAllTotalQuestions() + " Questions !");
if (manQuestions.getCurrentType() == ManageQuestions.TestType.EDUCATION) {
pb.setVisibility(View.INVISIBLE);
prepareCountDownTimer() ;
}
else
{
pb.setVisibility(View.VISIBLE);
prepareProgressBar() ;
showToastMessage("Exam time : " + (manQuestions.getExamTime()));
}
viewInfo();
}
@Override
public void onBackPressed() {
}
@Override
public void onClick(View view)
{
if (onClickIsNotBusy)
{
onClickIsNotBusy = false ;
if(view==ibConfirm) {
buttonEffect(view);
manQuestions.setUserResponseToCurQuestion(corAns);
if (manQuestions.getCurrentType() == ManageQuestions.TestType.EDUCATION)
{
if (manQuestions.getCurCorrectAnswer() == corAns)
bAns[corAns].setBackgroundColor(Color.GREEN);
else
{
bAns[corAns].setBackgroundColor(Color.RED);
bAns[manQuestions.getCurCorrectAnswer()].setBackgroundColor(Color.GREEN);
}
showToastMessage(manQuestions.getScoreEducation()) ;
cdtNextQuestion.start();
}
else
{
if (manQuestions.haveFinishedQuestions())
completelyFininsh() ;
else
nextQuestion() ;
}
}
else if(view==ibNext)
{
buttonEffect(view);
nextQuestion() ;
}
else
{
view.setBackgroundColor(Color.YELLOW);
for(int i=0;i<sumOfButtons;i++)
if(bAns[i]!=view)
bAns[i].setBackgroundResource(android.R.drawable.btn_default);
else
corAns=i;
enableConfirm() ;
onClickIsNotBusy = true ;
}
}
}
private void viewInfo()
{
tvaQuestion.setText("" + manQuestions.getCurQuestionText());
tvaNumOfQuestion.setText("" + manQuestions.getCurQuestionNumber() + "/" + manQuestions.getAllTotalQuestions()) ;
ivImage.setImageBitmap(manQuestions.getCurQuestionImage());
String cans[]=manQuestions.getCurAnswerTexts();
llAnswers.removeAllViews();
for (int i=0;i<cans.length;i++) {
bAns[i].setText(cans[i]);
llAnswers.addView(bAns[i]);
}
for(int i=0;i<sumOfButtons;i++)
bAns[i].setBackgroundResource(android.R.drawable.btn_default);
svAnswers.scrollTo(0, 0);
}
//��� ��� ������������ �������� ��� activity (������������ ������)
private void completelyFininsh()
{
onClickIsNotBusy = false ; /*�� ��������� ��� ���������� �� activity �� ��� ������ �� �������
������ ������ ��� ���� �������� �� �������������� � manQuestions
(����� ������� null ...) (������ ����� ������� ���� ��� ���� ��� ��� ����..)*/
Intent nAct = new Intent(MainScreen.this, ResultScreen.class);
nAct.putExtras(manQuestions.getBundleOfResults()) ;
startActivity(nAct);
toastMessage = null ;
if (myTimer != null)
{
myTimer.cancel();
myTimer.purge();
myTimer = null;
}
if (cdtNextQuestion != null)
{
cdtNextQuestion.cancel(); ;
cdtNextQuestion = null ;
}
manQuestions = null ;
this.finish();
}
//Prepare :
private void prepareToastMessage()
{
toastMessage = Toast.makeText(getApplicationContext(),"",Toast.LENGTH_SHORT);
toastMessage.setGravity(Gravity.CENTER, 0, 0);
}
private void prepareProgressBar()
{
pb.setMax(manQuestions.getSecondsForTest());
myTask = new TimerTask() {
@Override
public void run() {
if (count++ > manQuestions.getSecondsForTest()) count = manQuestions.getSecondsForTest() ;
ShowMessage(count);
}
};
if (myTimer == null) {
myTimer = new Timer();
}
myTimer.schedule(myTask, 100, 1000);
myTask = new TimerTask() {
@Override
public void run() {
if (count >= manQuestions.getSecondsForTest()) {
ShowMessage(manQuestions.getSecondsForTest());
completelyFininsh();
}
}
};
myTimer.schedule(myTask, 0, 100);
}
public void ShowMessage (int Val)
{
Message msg = new Message ();
Bundle bun = new Bundle ();
bun.putInt("Value", Val);
msg.setData(bun);
MyHandler.sendMessage(msg);
}
Handler MyHandler = new Handler ()
{
@Override
public void handleMessage (Message Mess)
{
Bundle b = Mess.getData ();
int tbp = b.getInt("Value");
pb.setProgress(tbp);
if (tbp == manQuestions.getSeventyFivePercentOfsecondsForTest())
pb.setProgressDrawable(getResources().getDrawable(R.drawable.redpb));
}
};
private void prepareCountDownTimer()
{
cdtNextQuestion = new CountDownTimer(2000, 50) {
@Override
public void onTick(long arg0) {
// TODO Auto-generated method stub
}
@Override
public void onFinish() {
if (manQuestions.haveFinishedQuestions())
completelyFininsh() ;
else
nextQuestion() ;
}
} ;
}
//Prepare : END
//Tools :
private void nextQuestion()
{
disableConfirm();
corAns=-1;
if (manQuestions.next())
viewInfo() ;
onClickIsNotBusy = true ;
}
private void showToastMessage(String message)
{
toastMessage.setText(message);
toastMessage.show();
}
private void disableConfirm()
{
ibConfirm.setImageDrawable(getResources().getDrawable(R.drawable.confirmdisable));
ibConfirm.setEnabled(false);
}
private void enableConfirm()
{
ibConfirm.setImageDrawable(getResources().getDrawable(R.drawable.confirm));
ibConfirm.setEnabled(true);
}
//Tools : END
//Effects :
private void buttonEffect(View view)
{
Animator scale = ObjectAnimator.ofPropertyValuesHolder(view,
PropertyValuesHolder.ofFloat(View.SCALE_X, 1, 1.3f, 1),
PropertyValuesHolder.ofFloat(View.SCALE_Y, 1, 1.3f, 1)
);
scale.setDuration(200);
scale.start();
}
//Effects : END
}
| maellak/EllakAndroidEducation | app/src/main/java/org/teiath/ellak/ellakandroideducation/MainScreen.java |
2,503 | package org.teiath.ellak.ellakandroideducation;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
/**
* Η κλάση DBHandler επιστρέφει πληροφορίες από τη βάση δεδομένων και δημιουργεί ερωτηματολόγια. Περιγράφονται κάποιες
* από τις απαιτούμενες μεθόδους οι οποίες είναι απαραίτητες για την λειτουργία άλλων κλάσεων της εφαρμογής.
* Η κλάση DBHandler είναι singleton.
*/
public class DBHandler {
private static Context mcontext;
private static DBHandler ourInstance;
private Cursor cursor;
private Cursor catCursor;
private Cursor sumCursor;
private Cursor ansCursor;
private Cursor subCursor;
private SQLiteDatabase sqldb;
/**
* Επιστρέφει αναφορά στο μοναδικό αντικείμενο που δημιουργείται από την κλάση.
* Πρεπει να καλειται πρωτη για να λαμβανεται η αναφορα στο αντικειμενο.
*
* @param context ενα αντικειμενο context ειτε σαν μεταβλητη context ειτε σαν μεθοδο(getApplicationContext()).
* @return Η αναφορά στο αντικείμενο.
*/
public static DBHandler getInstance(Context context) {
if (ourInstance == null) {
ourInstance = new DBHandler(context.getApplicationContext());
}
return ourInstance;
}
/**
* Ο κατασκευαστής του αντικειμένου. Εδώ τοποθετούνται οι αρχικοποιήσεις του αντικειμένου. Μία από τις λειτουργίες
* πρέπει να είναι ο έλεγχος ύπαρξης του sqlite αρχείου στον αποθεκευτικό χώρο της εφαρμογής και η μεταφορά του από
* τα assets αν χρειάζεται.
*/
private DBHandler(Context context) {
mcontext = context;
if (!CheckDB())
CopyDB();
}
/**
* Επιστρέφει την λίστα με τα γνωστικά αντικείμενα τα οποίες βρίσκονται στη Βάση Δεδομένων. Τα γνωστικά αντικείμενα
* επιστρέφονται ως LinkedList με αντικείμενα {@link SubjectRec}.
*
* @return Η λίστα με τις κατηγορίες εξέτασης.
*/
public LinkedList<SubjectRec> GetKategories() {
LinkedList<SubjectRec> list = new LinkedList<>();
String MyDB = mcontext.getApplicationContext().getFilesDir().getAbsolutePath() + "/databases/EllakDB.sqlite";
SQLiteDatabase sqldb = SQLiteDatabase.openDatabase(MyDB, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
Cursor cursor = sqldb.rawQuery("SELECT COUNT(*) FROM Subjects", null);
cursor.moveToFirst();
int x = cursor.getInt(0);
SubjectRec[] sr = new SubjectRec[x];
for (int j = 0; j < sr.length; j++) {
sr[j] = new SubjectRec();
}
cursor = sqldb.rawQuery("SELECT * FROM Subjects", null);
cursor.moveToFirst();
for (int i = 0; i < sr.length; i++) {
sr[i].SubjectID = cursor.getInt(0);
sr[i].SubjectName = cursor.getString(1);
list.add(sr[i]);
cursor.moveToNext();
}
cursor.close();
sqldb.close();
return list;
}
/**
* Δημιουργεί και επιστρέφει ένα ολόκληρο ερωτηματολόγιο. Οι ερωτήσεις επιλέγονται τυχαία από τις διαθέσιμες
* υποκατηγορίες και οι διαθέσιμες απαντήσεις των ερωτήσεων τοποθετούνται με, επίσης, τυχαία σειρά.
*
* @param Subject Ο κωδικός του γνωστικού αντικειμένου της εξέτασης.
* @return Το ερωτηματολόγιο ως στιγμιότυπο της κλάσης {@link TestSheet}.
*/
public TestSheet CreateTestSheet(int Subject) {
List<Integer> list;
List<Integer> ansList = new LinkedList<>();
/** Χρησιμοποιούμε λίστες για να αποτρέψουμε την random από το να παράξει το ίδιο αποτέλεσμα **/
TestSheet ts = new TestSheet();
ts.SubjectID = Subject;
int count = 0;
cursorInit(Subject);
int[] categories = categInit();
ts.Quests = makeQuest();
ts.ReqCorAnswers = reqAnswers(ts.Quests);
for (int i = 0; i < categories.length; i++) {
int q = categories[i];
list = getSubCateg(i);
for (int j = 0; j < q; j++) {
ts.Quests[count] = insertQuestions(list, ansList);
ansList.clear();
count++;
}
list.clear();
}
cursor = sqldb.rawQuery("SELECT STime FROM Subjects WHERE SubjectCode = " + Subject, null);
cursor.moveToFirst();
ts.ExamTime = cursor.getInt(0);
cursor.close();
catCursor.close();
ansCursor.close();
subCursor.close();
sumCursor.close();
sqldb.close();
return ts;
}
/**
* Επιστρέφει την έκδοση της τρέχουσας έκδοσης της βάσης δεδομένων.
*
* @return Η τρέχουσα έκδοση της βάσης δεδομένων.
*/
public float GetVersion() {
String MyDB = mcontext.getApplicationContext().getFilesDir().getAbsolutePath() + "/databases/EllakDB.sqlite";
SQLiteDatabase sqldb = SQLiteDatabase.openDatabase(MyDB, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
Cursor cursor = sqldb.rawQuery("SELECT * FROM Misc", null);
cursor.moveToFirst();
float ver = cursor.getFloat(0);
cursor.close();
sqldb.close();
return ver;
}
private boolean CheckDB() {
String DB_PATH = mcontext.getApplicationContext().getFilesDir().getAbsolutePath() + "/databases/";
File dbf = new File(DB_PATH + "EllakDB.sqlite");
return dbf.exists();
}
private void CopyDB() {
InputStream myInput = null;
try {
myInput = mcontext.getApplicationContext().getAssets().open("EllakDB.sqlite");
CreateDirectory();
String DB_PATH = mcontext.getApplicationContext().getFilesDir().getAbsolutePath() + "/databases/";
String outFileName = DB_PATH + "EllakDB.sqlite";
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.close();
myInput.close();
} catch (IOException e) {
System.err.println("Error in copying: " + e.getMessage());
}
}
private void CreateDirectory() {
String DB_DIR = mcontext.getApplicationContext().getFilesDir().getAbsolutePath() + "/databases/";
File Dir = new File(DB_DIR);
if (!Dir.exists())
Dir.mkdir();
}
/**
* Τοποθετεί τα δεδομένα απο τη βάση σε cursors για να χρησιμοποιηθούν στην createTestSheet.
*
* @param Subject ο αριθμός του γνωστικού αντικειμένου στη βάση.
*/
private void cursorInit(int Subject) {
String MyDB = mcontext.getApplicationContext().getFilesDir().getAbsolutePath() + "/databases/EllakDB.sqlite";
sqldb = SQLiteDatabase.openDatabase(MyDB, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
cursor = sqldb.rawQuery("SELECT QCODE,QSUBJECT,QKATEG,QLECT,QPHOTO from questions where qsubject=" + Subject + " order by qkateg;", null);
catCursor = sqldb.rawQuery("SELECT Kategory,Numb FROM Numbers WHERE SCode=" + Subject, null);
sumCursor = sqldb.rawQuery("SELECT SUM(Numb) FROM Numbers WHERE SCode=" + Subject, null);
subCursor = sqldb.rawQuery("SELECT SLect FROM Subjects WHERE SubjectCode=" + Subject, null);
}
/**
* @return ο πίνακας των υποκατηγοριών και ο απαιτούμενος αριθμός ερωτήσεων για κάθε υποκατηγορία.
*/
private int[] categInit() {
int[] categories = new int[catCursor.getCount()];
catCursor.moveToFirst();
for (int i = 0; i < categories.length; i++) {
categories[i] = catCursor.getInt(1);
catCursor.moveToNext();
}
return categories;
}
/**
* Αρχικοποιεί έναν πίνακα με αντικείμενα Question
*
* @return ο πίνακας με τα αντικείμενα τύπου Question
*/
private Question[] makeQuest() {
sumCursor.moveToFirst();
Question[] Quests = new Question[sumCursor.getInt(0)];
for (int i = 0; i < Quests.length; i++) {
Quests[i] = new Question();
}
return Quests;
}
/**
* Λαμβάνοντας το μήκος του πίνακα των ερωτήσεων υπολογίζει τις απαιτούμενες σωστές απαντήσεις.
*
* @param Quests Ο πίνακας με τις ερωτήσεις
* @return Τον αριθμό των απαιτούμενων σωστών απαντήσεων
*/
private int reqAnswers(Question[] Quests) {
int ReqCorAnswers;
subCursor.moveToFirst();
if (subCursor.getString(0).equals("ΚΩΔΙΚΑΣ")) {
ReqCorAnswers = Quests.length - 2;
} else {
ReqCorAnswers = Quests.length - 1;
}
return ReqCorAnswers;
}
/**
* Γεμίζει μία λίστα με ερωτήσεις που ανήκουν σε μια συγκεκριμένη υποκατηγορία.
*
* @param i Ο αριθμός υποκατηγορίας
* @return Την λίστα με τις ερωτήσεις μιας συγκεκριμένης υποκατηγορίας
*/
private List<Integer> getSubCateg(int i) {
List<Integer> list = new LinkedList<>();
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
if (cursor.getInt(2) == i + 1) {
list.add(cursor.getPosition());
}
cursor.moveToNext();
}
return list;
}
/**
* Χρησιμοποιείται για να γεμίσει τον πίνακα των ερωτήσεων με τυχαίες ερωτήσεις
* και τοποθετεί τις απαντήσεις επίσης με τυχαια σειρά.
*
* @param list η λίστα των ερωτήσεων
* @param ansList η λίστα των απαντήσεων
* @return Το αντικέιμενο τύπου Question που περιέχει όλα τα δεδομένα.
*/
private Question insertQuestions(List<Integer> list, List<Integer> ansList) {
Question quest = new Question();
int numb = new Random().nextInt(list.size());
System.out.println(list.size());
cursor.moveToPosition(list.remove(numb));
ansCursor = sqldb.rawQuery("SELECT ALect,ACorr FROM Answers WHERE AQcod=" + cursor.getInt(0), null);
quest.AText = new String[ansCursor.getCount()];
quest.QNum = cursor.getInt(0);
quest.QText = cursor.getString(3);
if (cursor.getString(4).equals("0")) {
quest.PicName = "-";
} else {
quest.PicName = cursor.getString(4) + ".jpg";
}
for (int k = 0; k < ansCursor.getCount(); k++) {
ansList.add(k);
}
for (int k = 0; k < ansCursor.getCount(); k++) {
int ansNumb = new Random().nextInt(ansList.size());
ansCursor.moveToPosition(ansList.remove(ansNumb));
quest.AText[k] = ansCursor.getString(0);
if (ansCursor.getInt(1) == 1) {
quest.CorAnswer = k;
}
}
return quest;
}
}
/**
* Παριστά,ως record, ένα γνωστικό αντικείμενο εξέτασης.
*/
class SubjectRec {
/**
* Ο κωδικός του γνωστικού αντικειμένου εξέτασης.
*/
public int SubjectID;
/**
* Το λεκτικό (όνομα) του γνωστικού αντικειμένου.
*/
public String SubjectName;
}
/**
* Παριστά, ως Record, μία ερώτηση του ερωτηματολογίου.
*/
class Question {
/**
* Ο Αύξωντας Αριθμός της Ερώτησης στο ερωτηματολόγιο
*/
public int QNum;
/**
* Το κείμενο της ερώτησης
*/
public String QText;
/**
* Το όνομα του αρχείου εικόνας το οποίο αντιστοιχεί στην ερώτηση ("-" αν η ερώτηση δεν έχει εικόνα).
*/
public String PicName;
/**
* Πίνακας με τα κείμενα των απαντήσεων. Το μέγεθος του πίνακα δηλώνει και το πλήθος των απαντήσεων.
*/
public String[] AText;
/**
* Η θέση της σωστής απάντησης στον προηγούμενο πίνακα
*/
int CorAnswer;
}
/**
* Παριστά, ως Record, ένα ολόκληρο ερωτηματολόγιο.
*/
class TestSheet {
/**
* Ο κωδικός του γνωστικού αντικειμένου του ερωτηματολογίου
*/
public int SubjectID;
/**
* Ο χρόνος εξέτασης σε πρώτα λεπτά της ώρας.
*/
public int ExamTime;
/**
* Πίνακας με τις ερωτήσεις του ερωτηματολογίου. Κάθε ερώτηση είναι ένα αντικείμενο της κλάσης {@link Question}
*/
public Question[] Quests;
/**
* Το πλήθος των ερωτήσεων που πρέπει να απαντηθούν σωστά προκειμένου η εξέταση να θεωρηθεί επιτυχής.
*/
int ReqCorAnswers;
}
| maellak/EllakAndroidEducation | app/src/main/java/org/teiath/ellak/ellakandroideducation/DBHandler.java |
2,504 | package leitourgika_java;
import java.io.*;
/* Αυτή η κλάση υπολογίζει ορισμένα στατιστικά στοιχεία βάσει των διεργασιών
που εμφανίζονται στο σύστημα και τα αποθηκεύει σε ένα αρχείο */
public class Statistics implements Serializable {
private float averageWaitingTime;//ο τρεχων μεσος χρόνος αναμονης των διεργασιών προς εκτελεση
private int totalWaitingTime=0;//ο τρεχων συνολικός χρόνος αναμονης των διεργασιών
private int maximumLengthOfReadyProcessesList=0;//το τρεχων μεγιστο πληθος διεργασιών προς εκτελεση
public int totalNumberOfProcesses;//ο τρεχων συνολικός αριθμός διεργασιών
private int totalProcessesWaiting=0;
private File outputFile;//αρχειο που αποθηκεύονται τα στατιστικα δεδομενα
public Statistics(String filename){
try {
this.outputFile = new File(filename);
outputFile.createNewFile();
} catch (IOException e) {
System.out.println(e);
}
}
//ελέγχει το μήκος της λίστας έτοιμων διεργασιών και ενημερώνει αν είναι απαραίτητο την maximumLengthOfReadyProcessesList
public void UpdateMaximumListLength(ReadyProcessesList list){
if(maximumLengthOfReadyProcessesList<list.getsize())
maximumLengthOfReadyProcessesList=list.getsize();
}
//μετρητής για τον υπολογισμό του συνολικού totalWaitingTime
public void SumTotalWaitingTime(int numberOfWaitingProcesses){
totalWaitingTime=totalWaitingTime+numberOfWaitingProcesses;
}
//υπολογίζει τον μέσο χρόνο αναμονής
public String CalculateAverageWaitingTime(int quantum, int numberOfProcesses){
averageWaitingTime=totalWaitingTime/(quantum*numberOfProcesses);
System.out.println("totalWaitingTime="+totalWaitingTime);
return "\nO mesos xronos anamonhs einai: " +averageWaitingTime+" To megisto plhthos diergasiwn pros ektelesh einai:" +maximumLengthOfReadyProcessesList;
}
//γράφει τα τρέχοντα στατιστικά στο αρχείο outputFile
public void WriteStatistics2File(){
try{
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(outputFile)));
out.println("O mesos xronos anamonhs einai: " +averageWaitingTime+" To megisto plhthos diergasiwn pros ektelesh einai:" +maximumLengthOfReadyProcessesList);
out.close();
}catch(IOException e){
System.out.println(e);
}
}
}
| mpantogi/routine_scheduling | src/leitourgika_java/Statistics.java |
2,507 | package com.example.quickrepair.view.Customer.ShowCompletedRepairRequest;
public interface CustomerCompletedRepairRequestView {
/**
* Προβάλει μήνυμα λάθους
* @param message Το Μήνυμα λάθους
*/
void showError(String message);
/**
* Εμφανίζει τη δουλειά
* @param job Η δουλειά
*/
void setJob(String job);
/**
* Εμφανίζει το όνομα του τεχνικού
* @param technicianName Το όνομα του τεχνηκού
*/
void setTechnicianName(String technicianName);
/**
* Εμφανίζει τη διεύθυνση
* @param address Η διεύθυνση
*/
void setAddress(String address);
/**
* Εμφανίζει τα σχόλια
* @param comments Τα σχόλια
*/
void setComments(String comments);
/**
* Εμφανίζει την ημερομηνία διεξαγωγής της επισκευής
* @param conductionDate Η ημερομηνία διεξαγωγής της επισκευής
*/
void setConductionDate(String conductionDate);
/**
* Εμφανίζει το εκτιμώμενο απο τον τεχνικό χρόνο της επισκευής
* @param estimatedDuration Ο εκτιμώμενος απο τον τεχνικό χρόνος της επισκευής
*/
void setEstimatedDuration(String estimatedDuration);
/**
* Εμφανίζει το κόστος
* @param cost Το κόστος
*/
void setCost(String cost);
/**
* Εμφανίζει τα στοιχεία της αξιολόγησης
* @param title Ο τίτλος της αξιολόγησης
* @param comments Τα σχόλια της αξιολόγησης
* @param rate Η βαθμολογία της αξιολόγησης
*/
void setEvaluationData(String title, String comments, String rate);
/**
* Εμφανίζει τα πεδία για πληρωμή και προσθήκη σχολίων
*/
void setPayAndEvaluationFields();
/**
* Ενεργοποίηση δυνατότητας πληρωμής
*/
void setPayListener();
/**
* Αίτημα για πληρωμή και αξιολόγηση
*/
void donePayAndEvaluate();
}
| NickSmyr/UndergraduateProjects | 6th semester/SoftwareEngineering/android/app/src/main/java/com/example/quickrepair/view/Customer/ShowCompletedRepairRequest/CustomerCompletedRepairRequestView.java |
2,508 | package biz.aQute.scheduler.api;
/**
* The software utility Cron is a time-based job scheduler in Unix-like computer
* operating systems. People who set up and maintain software environments use
* cron to schedule jobs (commands or shell scripts) to run periodically at
* fixed times, dates, or intervals. It typically automates system maintenance
* or administration—though its general-purpose nature makes it useful for
* things like connecting to the Internet and downloading email at regular
* intervals.[1] The name cron comes from the Greek word for time, χρόνος
* chronos.
* <p>
* The Unix Cron defines a syntax that is used by the Cron service. A user
* should register a Cron service with the {@value CronJob#CRON} property. The
* value is according to the {link http://en.wikipedia.org/wiki/Cron}.
* <p>
*
* <pre>
* * * * * * * *
* | │ │ │ │ │ |
* | │ │ │ │ │ └ year (optional)
* | │ │ │ │ └── day of week from Monday (1) to Sunday (7).
* | │ │ │ └──── month (1 - 12) from January (1) to December (12).
* | │ │ └────── day of month (1 - 31)
* | │ └──────── hour (0 - 23)
* | └────────── min (0 - 59)
* └──────────── sec (0-59)
* </pre>
*
* <pre>
* Field name mandatory Values Special characters
* Seconds Yes 0-59 * / , -
* Minutes Yes 0-59 * / , -
* Hours Yes 0-23 * / , -
* Day of month Yes 1-31 * / , - ? L W
* Month Yes 1-12 or JAN-DEC * / , -
* Day of week Yes 1-7 or MON-SUN * / , - ? L #
* Year No 1970–2099 * / , -
* </pre>
*
* <h3>Asterisk ( * )</h3>
* <p>
* The asterisk indicates that the cron expression matches for all values of the
* field. E.g., using an asterisk in the 4th field (month) indicates every
* month.
* <h3>Slash ( / )</h3>
* <p>
* Slashes describe increments of ranges. For example 3-59/15 in the 1st field
* (minutes) indicate the third minute of the hour and every 15 minutes
* thereafter. The form "*\/..." is equivalent to the form "first-last/...",
* that is, an increment over the largest possible range of the field.
* <h3>Comma ( , )</h3>
* <p>
* Commas are used to separate items of a list. For example, using "MON,WED,FRI"
* in the 5th field (day of week) means Mondays, Wednesdays and Fridays. Hyphen
* ( - ) Hyphens define ranges. For example, 2000-2010 indicates every year
* between 2000 and 2010 AD, inclusive.
* <p>
* Additionally, you can use some fixed formats:
*
* <pre>
*
* @yearly (or @annually) Run once a year at midnight on the morning of January 0 0 0 1 JAN *
* @monthly Run once a month at midnight on the morning of the first day of the month 0 0 0 1 * *
* @weekly Run once a week at midnight on Sunday morning 0 0 0 * * 7
* @daily Run once a day at midnight 0 0 0 * * *
* @hourly Run once an hour at the beginning of the hour 0 * * * * *
* @reboot Run at startup @reboot (at service registration time)
* </pre>
* <p>
* Please not that for the constants we follow the Java 8 Date & Time constants.
* Major difference is the day number. In Quartz this is 0-6 for SAT-SUN while
* here it is 1-7 for MON-SUN.
*
*/
public interface CronJob {
/**
* The service property that specifies the cron schedule. The type is
* String+.
*/
String CRON = "cron";
String NAME = "name";
/**
* Run a cron job.
*
* @throws Exception
*/
public void run() throws Exception;
}
| aQute-os/biz.aQute.osgi.util | biz.aQute.api/src/main/java/biz/aQute/scheduler/api/CronJob.java |
2,509 | public class Station {
static int count=0;
protected double meanService; //μέσος χρόνος εξυπηρέτησης - εκθετική κατανομή
protected double routing[]; //πιθανότητες δρομολόγησης
protected int length=0; //αριθμός εργασιών στο σταθμό
protected double oldclock=0.0; //χρονική στιγμή τελευταίου γεγονότος στο σταθμό
protected double sumBusyTime; //άθροισμα διαστημάτων απασχόλησης
protected double bt=0.0;
public Station(double meanService){
this.meanService=meanService;
}
public void complete(Job job, double clock){}
public void arrive(Job job, double clock){}
public void extArrive(Job job, double clock){}
public void exit(Job job, double clock){}
protected int min(int a, int b){
if (a<=b) return a;
else return b;
}
public void withdraw(Job job, double clock) {}
public double[] getRouting() {
return routing;
}
public int getLength() {
return length;
}
public double getSumBusyTime() {
//sumBusyTime+=(Simulation.clock-oldclock);
//oldclock=Simulation.clock;
bt+=sumBusyTime;
sumBusyTime=0.0;
return bt;
}
}
| stchrysa/DE-QNet-SIM | src/Station.java |
2,510 | package osgi.enroute.scheduler.api;
/**
* The software utility Cron is a time-based job scheduler in Unix-like computer
* operating systems. People who set up and maintain software environments use
* cron to schedule jobs (commands or shell scripts) to run periodically at
* fixed times, dates, or intervals. It typically automates system maintenance
* or administration—though its general-purpose nature makes it useful for
* things like connecting to the Internet and downloading email at regular
* intervals.[1] The name cron comes from the Greek word for time, χρόνος
* chronos.
* <p>
* The Unix Cron defines a syntax that is used by the Cron service. A user
* should register a Cron service with the {@link CronJob#CRON} property. The
* value is according to the {link http://en.wikipedia.org/wiki/Cron}.
* <p>
*
* <pre>
* * * * * * * *
* | │ │ │ │ │ |
* | │ │ │ │ │ └ year (optional)
* | │ │ │ │ └── day of week from Monday (1) to Sunday (7).
* | │ │ │ └──── month (1 - 12) from January (1) to December (12).
* | │ │ └────── day of month (1 - 31)
* | │ └──────── hour (0 - 23)
* | └────────── min (0 - 59)
* └──────────── sec (0-59)
* </pre>
*
* <pre>
* Field name mandatory Values Special characters
* Seconds Yes 0-59 * / , -
* Minutes Yes 0-59 * / , -
* Hours Yes 0-23 * / , -
* Day of month Yes 1-31 * / , - ? L W
* Month Yes 1-12 or JAN-DEC * / , -
* Day of week Yes 1-7 or MON-SUN * / , - ? L #
* Year No 1970–2099 * / , -
* </pre>
*
* <h3>Asterisk ( * )</h3>
* <p>
* The asterisk indicates that the cron expression matches for all values of the
* field. E.g., using an asterisk in the 4th field (month) indicates every
* month.
* <h3>Slash ( / )</h3>
* <p>
* Slashes describe increments of ranges. For example 3-59/15 in the 1st field
* (minutes) indicate the third minute of the hour and every 15 minutes
* thereafter. The form "*\/..." is equivalent to the form "first-last/...",
* that is, an increment over the largest possible range of the field.
* <h3>Comma ( , )</h3>
* <p>
* Commas are used to separate items of a list. For example, using "MON,WED,FRI"
* in the 5th field (day of week) means Mondays, Wednesdays and Fridays. Hyphen
* ( - ) Hyphens define ranges. For example, 2000-2010 indicates every year
* between 2000 and 2010 AD, inclusive.
* <p>
* Additionally, you can use some fixed formats:
*
* <pre>
* @yearly (or @annually) Run once a year at midnight on the morning of January 1 0 0 1 1 *
* @monthly Run once a month at midnight on the morning of the first day of the month 0 0 1 * *
* @weekly Run once a week at midnight on Sunday morning 0 0 * * 0
* @daily Run once a day at midnight 0 0 * * *
* @hourly Run once an hour at the beginning of the hour 0 * * * *
* @reboot Run at startup @reboot (at service registration time)
* </pre>
* <p>
* Please not that for the constants we follow the Java 8 Date & Time constants.
* Major difference is the day number. In Quartz this is 0-6 for SAT-SUN while
* here it is 1-7 for MON-SUN.
*
* @param <T> The parameter for the cron job
*/
public interface CronJob<T> {
/**
* The service property that specifies the cron schedule. The type is
* String+.
*/
String CRON = "cron";
/**
* Run a cron job.
*
* @param data The data for the job
* @throws Exception
*/
public void run(T data) throws Exception;
}
| aQute-os/v2Archive.osgi.enroute | osgi.enroute.base.api/src/osgi/enroute/scheduler/api/CronJob.java |
2,512 | package gr.sch.ira.minoas.seam.components;
import gr.sch.ira.minoas.core.CoreUtils;
import gr.sch.ira.minoas.model.employee.Employee;
import gr.sch.ira.minoas.model.employee.EmployeeInfo;
import gr.sch.ira.minoas.model.employee.RankInfo;
import gr.sch.ira.minoas.model.employee.RegularEmployeeInfo;
import java.util.Date;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
/**
* @author <a href="mailto:[email protected]">Yorgos Andreadakis</a>
* @version $Id$
*/
@Name("rankInfoCalculation")
@Scope(ScopeType.APPLICATION)
@AutoCreate
public class RankInfoCalculation extends BaseDatabaseAwareSeamComponent {
/**
*
*/
private static final long serialVersionUID = 1L;
@In(value="coreSearching")
protected CoreSearching coreSearching;
@In(required=true, create=true)
private WorkExperienceCalculation workExperienceCalculation;
public void recalculateRankInfo(Employee employee) {
try {
EmployeeInfo eInfo = employee.getEmployeeInfo();
RankInfo rankInfo = eInfo.getCurrentRankInfo();
RankInfo recalculatedRankInfo = CoreUtils.RecalculateRankInfo(rankInfo, employee, workExperienceCalculation);
java.text.DateFormat df = java.text.SimpleDateFormat.getDateInstance(java.text.SimpleDateFormat.SHORT);
if(!rankInfo.getRank().equals(recalculatedRankInfo.getRank()) || rankInfo.getSalaryGrade()!=recalculatedRankInfo.getSalaryGrade()) {
RegularEmployeeInfo reinfo = employee.getRegularEmployeeInfo();
String AM = new String();
if (reinfo!= null) {
AM = reinfo.getRegistryID();
}
// info("|"+ AM +
// "|"+employee.getLastName() +
// "|" + employee.getFirstName() +
// "|" + employee.getFatherName() +
// "|" + rankInfo.prettyToString() +
// "|Πλεονάζ. Χρόνος στο βαθμό την|" + df.format(rankInfo.getLastRankDate()) + "|" + rankInfo.getSurplusTimeInRankYear_Month_Day() + "|"+rankInfo.getSurplusTimeInRank() + "|" +
// "|Πλεονάζ. Χρόνος στο βαθμό σήμερα|" + rankInfo.getSurplusTimeInRankUntilTodayYear_Month_Day() + "|"+rankInfo.getSurplusTimeInRankUntilToday() + "|" +
// "|Πλεονάζ. Χρόνος στο Μ.Κ. την|" + df.format(rankInfo.getLastSalaryGradeDate()) + "|" + rankInfo.getSurplusTimeInSalaryGradeYear_Month_Day() + "|"+rankInfo.getSurplusTimeInSalaryGrade() + "|" +
// "|Πλεονάζ. Χρόνος στο Μ.Κ. σήμερα|" + rankInfo.getSurplusTimeInSalaryGradeUntilTodayYear_Month_Day() + "|"+rankInfo.getSurplusTimeInSalaryGradeUntilToday() + "|" +
// "|πάει στο|" + recalculatedRankInfo.prettyToString() +
// "|Πλεονάζ. Χρόνος στο βαθμό την|" + df.format(recalculatedRankInfo.getLastRankDate()) + "|" + recalculatedRankInfo.getSurplusTimeInRankYear_Month_Day() + "|"+recalculatedRankInfo.getSurplusTimeInRank() + "|" +
// "|Πλεονάζ. Χρόνος στο βαθμό σήμερα|" + recalculatedRankInfo.getSurplusTimeInRankUntilTodayYear_Month_Day() + "|"+recalculatedRankInfo.getSurplusTimeInRankUntilToday() + "|" +
// "|Πλεονάζ. Χρόνος στο Μ.Κ. την|" + df.format(recalculatedRankInfo.getLastSalaryGradeDate()) + "|" + recalculatedRankInfo.getSurplusTimeInSalaryGradeYear_Month_Day() + "|"+recalculatedRankInfo.getSurplusTimeInSalaryGrade() + "|" +
// "|Πλεονάζ. Χρόνος στο Μ.Κ. σήμερα|" + recalculatedRankInfo.getSurplusTimeInSalaryGradeUntilTodayYear_Month_Day() + "|"+recalculatedRankInfo.getSurplusTimeInSalaryGradeUntilToday() + "|");
// set InsertedBy to Minoas user username
recalculatedRankInfo.setInsertedBy(null);
// set InsertedOn to today's date
recalculatedRankInfo.setInsertedOn(new Date());
// Link the new RankInfo with the previous one
recalculatedRankInfo.setPreviousRankInfo(rankInfo);
// save the new RankInfo
getEntityManager().persist(recalculatedRankInfo);
// set the newly created rankInfo as current at the respective employeeInfo
// NOTE: that method setCurrentRankInfo(rInfo) also adds rInfo to the Collection of RankInfos within EmployeeInfo !!!!
eInfo.setCurrentRankInfo(recalculatedRankInfo);
info("Rank Info #0 for employee #1 has been inserted", recalculatedRankInfo, employee);
} else {
// info("Recalculated RankInfo ("+recalculatedRankInfo.prettyToString()+") matches the current. Skipping RankInfo update for emplooyee: " + rankInfo.getEmployeeInfo().getEmployee().getLastName() +
// " " + rankInfo.getEmployeeInfo().getEmployee().getFirstName() +
// " " + rankInfo.getEmployeeInfo().getEmployee().getFatherName());
}
} catch(Exception ex) {
error(String.format("failed to recalculate rankInfo for employee '%s' due to an exception.", employee), ex);
}
}
}
| slavikos/minoas | gr.sch.ira.minoas/src/main/java/gr/sch/ira/minoas/seam/components/RankInfoCalculation.java |
2,516 | package com.example.quickrepair.view.Customer.ShowConfirmedRepairRequest;
public interface CustomerConfirmedRepairRequestView {
/**
* Προβάλει μήνυμα λάθους
* @param message Το Μήνυμα λάθους
*/
void showError(String message);
/**
* Εμφανίζει τη δουλειά
* @param job Η δουλειά
*/
void setJob(String job);
/**
* Εμφανίζει το όνομα του τεχνικού
* @param technicianName Το όνομα του τεχνηκού
*/
void setTechnicianName(String technicianName);
/**
* Εμφανίζει τη διεύθυνση
* @param address Η διεύθυνση
*/
void setAddress(String address);
/**
* Εμφανίζει τα σχόλια
* @param comments Τα σχόλια
*/
void setComments(String comments);
/**
* Εμφανίζει την ημερομηνία διεξαγωγής της επισκευής
* @param conductionDate Η ημερομηνία διεξαγωγής της επισκευής
*/
void setConductionDate(String conductionDate);
/**
* Εμφανίζει το εκτιμώμενο απο τον τεχνικό χρόνο της επισκευής
* @param estimatedDuration Ο εκτιμώμενος απο τον τεχνικό χρόνος της επισκευής
*/
void setEstimatedDuration(String estimatedDuration);
}
| NickSmyr/UndergraduateProjects | 6th semester/SoftwareEngineering/android/app/src/main/java/com/example/quickrepair/view/Customer/ShowConfirmedRepairRequest/CustomerConfirmedRepairRequestView.java |
2,518 | /**
* Copyright (c) 2010-2023 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.core.scheduler;
import java.util.Map;
import org.eclipse.jdt.annotation.NonNullByDefault;
/**
* The software utility Cron is a time-based job scheduler in Unix-like computer
* operating systems. People who set up and maintain software environments use
* cron to schedule jobs (commands or shell scripts) to run periodically at
* fixed times, dates, or intervals. It typically automates system maintenance
* or administration—though its general-purpose nature makes it useful for
* things like connecting to the Internet and downloading email at regular
* intervals.[1] The name cron comes from the Greek word for time, χρόνος
* chronos.
* <p>
* The Unix Cron defines a syntax that is used by the Cron service. A user
* should register a Cron service with the {@link CronJob#CRON} property. The
* value is according to the <a href="https://en.wikipedia.org/wiki/Cron">Cron</a>.
* <p>
*
* <pre>
* * * * * * * *
* | │ │ │ │ │ |
* | │ │ │ │ │ └ year (optional)
* | │ │ │ │ └── day of week from Monday (1) to Sunday (7).
* | │ │ │ └──── month (1 - 12) from January (1) to December (12).
* | │ │ └────── day of month (1 - 31)
* | │ └──────── hour (0 - 23)
* | └────────── min (0 - 59)
* └──────────── sec (0-59)
* </pre>
*
* <pre>
* Field name mandatory Values Special characters
* Seconds Yes 0-59 * / , -
* Minutes Yes 0-59 * / , -
* Hours Yes 0-23 * / , -
* Day of month Yes 1-31 * / , - ? L W
* Month Yes 1-12 or JAN-DEC * / , -
* Day of week Yes 1-7 or MON-SUN * / , - ? L #
* Year No 1970–2099 * / , -
* </pre>
*
* <h3>Asterisk ( * )</h3>
* <p>
* The asterisk indicates that the cron expression matches for all values of the
* field. E.g., using an asterisk in the 4th field (month) indicates every
* month.
* <h3>Slash ( / )</h3>
* <p>
* Slashes describe increments of ranges. For example 3-59/15 in the 1st field
* (minutes) indicate the third minute of the hour and every 15 minutes
* thereafter. The form "*\/..." is equivalent to the form "first-last/...",
* that is, an increment over the largest possible range of the field.
* <h3>Comma ( , )</h3>
* <p>
* Commas are used to separate items of a list. For example, using "MON,WED,FRI"
* in the 5th field (day of week) means Mondays, Wednesdays and Fridays. Hyphen
* ( - ) Hyphens define ranges. For example, 2000-2010 indicates every year
* between 2000 and 2010 AD, inclusive.
* <p>
* Additionally, you can use some fixed formats:
*
* <pre>
* @yearly (or @annually) Run once a year at midnight on the morning of January 1 0 0 1 1 *
* @monthly Run once a month at midnight on the morning of the first day of the month 0 0 1 * *
* @weekly Run once a week at midnight on Sunday morning 0 0 * * 0
* @daily Run once a day at midnight 0 0 * * *
* @hourly Run once an hour at the beginning of the hour 0 * * * *
* @reboot Run at startup @reboot
* </pre>
* <p>
* Please note that for the constants we follow the Java 8 Date & Time constants.
* Major difference is the day number. In Quartz this is 0-6 for SAT-SUN while
* here it is 1-7 for MON-SUN.
*
* @author Peter Kriens - Initial contribution
* @author Simon Kaufmann - adapted to CompletableFutures
* @author Hilbrand Bouwkamp - Moved Cron scheduling to it's own interface
*/
@NonNullByDefault
public interface CronScheduler {
/**
* Schedule a runnable to be executed for the give cron expression (See
* {@link CronJob}). Every time when the cronExpression matches the current
* time, the runnable will be run. The method returns a {@link ScheduledCompletableFuture}
* that can be used to stop scheduling. This variation does not take an
* environment object.
*
* @param runnable The runnable to run
* @param cronExpression A cron expression
* @return A {@link ScheduledCompletableFuture} to cancel the schedule
*/
ScheduledCompletableFuture<Void> schedule(SchedulerRunnable runnable, String cronExpression);
/**
* Schedule a runnable to be executed for the give cron expression (See
* {@link CronJob}). Every time when the cronExpression matches the current
* time, the runnable will be run. The method returns a {@link ScheduledCompletableFuture}
* that can be used to stop scheduling. The run method of cronJob takes
* an environment object. An environment object is a custom interface where
* the names of the methods are the keys in the properties (see {@link DTOs}).
*
* @param <T> The data type of the parameter for the cron job
* @param cronJob The runnable to run
* @param cronExpression A cron expression
* @return A {@link ScheduledCompletableFuture} to cancel the schedule
*/
ScheduledCompletableFuture<Void> schedule(CronJob cronJob, Map<String, Object> config, String cronExpression);
}
| TheNetStriker/openhab-core | bundles/org.openhab.core/src/main/java/org/openhab/core/scheduler/CronScheduler.java |
2,519 | /**
* Copyright (c) 2010-2022 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.core.scheduler;
import java.util.Map;
import org.eclipse.jdt.annotation.NonNullByDefault;
/**
* The software utility Cron is a time-based job scheduler in Unix-like computer
* operating systems. People who set up and maintain software environments use
* cron to schedule jobs (commands or shell scripts) to run periodically at
* fixed times, dates, or intervals. It typically automates system maintenance
* or administration—though its general-purpose nature makes it useful for
* things like connecting to the Internet and downloading email at regular
* intervals.[1] The name cron comes from the Greek word for time, χρόνος
* chronos.
* <p>
* The Unix Cron defines a syntax that is used by the Cron service. A user
* should register a Cron service with the {@link CronJob#CRON} property. The
* value is according to the <a href="https://en.wikipedia.org/wiki/Cron">Cron</a>.
* <p>
*
* <pre>
* * * * * * * *
* | │ │ │ │ │ |
* | │ │ │ │ │ └ year (optional)
* | │ │ │ │ └── day of week from Monday (1) to Sunday (7).
* | │ │ │ └──── month (1 - 12) from January (1) to December (12).
* | │ │ └────── day of month (1 - 31)
* | │ └──────── hour (0 - 23)
* | └────────── min (0 - 59)
* └──────────── sec (0-59)
* </pre>
*
* <pre>
* Field name mandatory Values Special characters
* Seconds Yes 0-59 * / , -
* Minutes Yes 0-59 * / , -
* Hours Yes 0-23 * / , -
* Day of month Yes 1-31 * / , - ? L W
* Month Yes 1-12 or JAN-DEC * / , -
* Day of week Yes 1-7 or MON-SUN * / , - ? L #
* Year No 1970–2099 * / , -
* </pre>
*
* <h3>Asterisk ( * )</h3>
* <p>
* The asterisk indicates that the cron expression matches for all values of the
* field. E.g., using an asterisk in the 4th field (month) indicates every
* month.
* <h3>Slash ( / )</h3>
* <p>
* Slashes describe increments of ranges. For example 3-59/15 in the 1st field
* (minutes) indicate the third minute of the hour and every 15 minutes
* thereafter. The form "*\/..." is equivalent to the form "first-last/...",
* that is, an increment over the largest possible range of the field.
* <h3>Comma ( , )</h3>
* <p>
* Commas are used to separate items of a list. For example, using "MON,WED,FRI"
* in the 5th field (day of week) means Mondays, Wednesdays and Fridays. Hyphen
* ( - ) Hyphens define ranges. For example, 2000-2010 indicates every year
* between 2000 and 2010 AD, inclusive.
* <p>
* Additionally, you can use some fixed formats:
*
* <pre>
* @yearly (or @annually) Run once a year at midnight on the morning of January 1 0 0 1 1 *
* @monthly Run once a month at midnight on the morning of the first day of the month 0 0 1 * *
* @weekly Run once a week at midnight on Sunday morning 0 0 * * 0
* @daily Run once a day at midnight 0 0 * * *
* @hourly Run once an hour at the beginning of the hour 0 * * * *
* @reboot Run at startup @reboot
* </pre>
* <p>
* Please note that for the constants we follow the Java 8 Date & Time constants.
* Major difference is the day number. In Quartz this is 0-6 for SAT-SUN while
* here it is 1-7 for MON-SUN.
*
* @author Peter Kriens - Initial contribution
* @author Simon Kaufmann - adapted to CompletableFutures
* @author Hilbrand Bouwkamp - Moved Cron scheduling to it's own interface
*/
@NonNullByDefault
public interface CronScheduler {
/**
* Schedule a runnable to be executed for the give cron expression (See
* {@link CronJob}). Every time when the cronExpression matches the current
* time, the runnable will be run. The method returns a {@link ScheduledCompletableFuture}
* that can be used to stop scheduling. This variation does not take an
* environment object.
*
* @param runnable The runnable to run
* @param cronExpression A cron expression
* @return A {@link ScheduledCompletableFuture} to cancel the schedule
*/
ScheduledCompletableFuture<Void> schedule(SchedulerRunnable runnable, String cronExpression);
/**
* Schedule a runnable to be executed for the give cron expression (See
* {@link CronJob}). Every time when the cronExpression matches the current
* time, the runnable will be run. The method returns a {@link ScheduledCompletableFuture}
* that can be used to stop scheduling. The run method of cronJob takes
* an environment object. An environment object is a custom interface where
* the names of the methods are the keys in the properties (see {@link DTOs}).
*
* @param <T> The data type of the parameter for the cron job
* @param cronJob The runnable to run
* @param cronExpression A cron expression
* @return A {@link ScheduledCompletableFuture} to cancel the schedule
*/
ScheduledCompletableFuture<Void> schedule(CronJob cronJob, Map<String, Object> config, String cronExpression);
}
| ccutrer/openhab-core | bundles/org.openhab.core/src/main/java/org/openhab/core/scheduler/CronScheduler.java |
2,520 | package osgi.enroute.scheduler.api;
import org.osgi.dto.DTO;
/**
* The software utility Cron is a time-based job scheduler in Unix-like computer
* operating systems. People who set up and maintain software environments use
* cron to schedule jobs (commands or shell scripts) to run periodically at
* fixed times, dates, or intervals. It typically automates system maintenance
* or administration—though its general-purpose nature makes it useful for
* things like connecting to the Internet and downloading email at regular
* intervals.[1] The name cron comes from the Greek word for time, χρόνος
* chronos.
* <p>
* The Unix Cron defines a syntax that is used by the Cron service. A user
* should register a Cron service with the {@link Schedule#CRON} property. The value
* is according to the {@see http://en.wikipedia.org/wiki/Cron}.
* <p>
*
* <pre>
* * * * * * * *
* | │ │ │ │ │ |
* | │ │ │ │ │ └ year (optional)
* | │ │ │ │ └── day of week (0 - 6) (0 to 6 are Sunday to Saturday, or use names; 7 is Sunday, the same as 0)
* | │ │ │ └──── month (1 - 12)
* | │ │ └────── day of month (1 - 31)
* | │ └──────── hour (0 - 23)
* | └────────── min (0 - 59)
* └──────────── sec (0-59)
* </pre>
*
* <pre>
* Field name mandatory Values Special characters
* Seconds Yes 0-59 * / , -
* Minutes Yes 0-59 * / , -
* Hours Yes 0-23 * / , -
* Day of month Yes 1-31 * / , - ? L W
* Month Yes 1-12 or JAN-DEC * / , -
* Day of week Yes 0-6 or SUN-SAT * / , - ? L #
* Year No 1970–2099 * / , -
* </pre>
*
* <h3>Asterisk ( * )</h3>
* <p>
* The asterisk indicates that the cron expression matches for all values of the
* field. E.g., using an asterisk in the 4th field (month) indicates every
* month.
* <h3>Slash ( / )</h3>
* <p>
* Slashes describe increments of ranges. For example 3-59/15 in the 1st field
* (minutes) indicate the third minute of the hour and every 15 minutes
* thereafter. The form "*\/..." is equivalent to the form "first-last/...",
* that is, an increment over the largest possible range of the field.
* <h3>Comma ( , )</h3>
* <p>
* Commas are used to separate items of a list. For example, using "MON,WED,FRI"
* in the 5th field (day of week) means Mondays, Wednesdays and Fridays. Hyphen
* ( - ) Hyphens define ranges. For example, 2000-2010 indicates every year
* between 2000 and 2010 AD, inclusive.
*/
public class Schedule extends DTO {
String CRON = "cron";
}
| kameshsampath/osgi.enroute | osgi.enroute.base/src/osgi/enroute/scheduler/api/Schedule.java |
2,521 | package operatingsystem;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;
// Χρίστος Γκόγκος (2738), Αθανάσιος Μπόλλας (2779), Δημήτριος Σβίγγας (2618), Αναστάσιος Τεμπερεκίδης (2808)
/* Η συγκεκριμένη κλάση αναπαριστά μια γεννήτρια διεργασιών για την προσομοίωση */
class ProcessGenerator {
/* αρχείο που αποθηκεύονται τα δεδομένα των νέων διεργασιών */
private BufferedReader reader;
private BufferedWriter writer;
private File inputFile;
private ArrayList<Process> processes;
private final Random rand = new Random();
private int n;
private int prev = 0; //Ο χρόνος άφοιξης της προηγούμενηυς διεργασίας. Την χρονική στιγμή 0 δεν ήρθε καμία διεργασία.
private final int cpuBurstTime = 60000; //60000 μπαίνει για να διαρκεί μια διεργασία από 0 εως 1 λεπτό. (60000 millisecond == 1 λεπτό).
private final int cpuArrivalTime = 2000; //2000 είναι τα περισσότερα millisecond "διαφοράς άφοιξης" που μπορεί να έχει η μια διεργασία από την προηγούμενη.
/* constructor της κλάσης; αν readFile == false δημιουργεί το αρχείο inputFile με όνομα
filename για αποθήκευση, αλλιώς ανοίγει το αρχείο inputFile για ανάγνωση */
public ProcessGenerator(String filename, boolean readFile) throws IOException {
inputFile = new File(filename);
if (readFile == false) {
inputFile.createNewFile();
inputFile.setReadable(true);
inputFile.setWritable(true);
n = rand.nextInt(200) + 50; //Δημιουργεί τυχαία από 50 εως 250 διεργασίες.
writer = new BufferedWriter(new FileWriter(filename));
for (int i = 0; i < n; i++) {
StoreProcessToFile();
}
writer.close();
} else {
if (inputFile.exists() == false) {
System.err.println("Error: file " + inputFile.getName() + " not found");
System.exit(2);
}
reader = new BufferedReader(new FileReader(filename));
processes = new ArrayList<>();
processes = parseProcessFile();
reader.close();
}
}
/* δημιουργία μιας νέας διεργασίας με (ψευδο-)τυχαία χαρακτηριστικά */
public Process createProcess(int pid) {
prev = (rand.nextInt(cpuArrivalTime)) + prev;
return new Process(pid, prev, rand.nextInt(cpuBurstTime));
}
/* αποθήκευση των στοιχείων της νέας διεργασίας στο αρχείο inputFile */
public void StoreProcessToFile() throws IOException {
prev += (rand.nextInt(cpuArrivalTime)); //Το cpuArrivalTime είναι σταθερό στα 2 δευτερόλεπτα, δηλαδή μια νέα διεργασία δεν θα αργεί να φτάσει στο σύστημα πάνω από 2 δευτερόλεπτα από την προηγούμενη.
writer.write(Integer.toString(prev)); //Χρόνος άφοιξης.
writer.newLine();
writer.write(Integer.toString(rand.nextInt(cpuBurstTime))); //Το cpuBurstTime είναι σταθερό στα 60 δευτερόλεπτα, δηλαδή μια διεργασία δεν θα μπορεί να χρειαστή την cpu για πάνω από 1 λεπτό.
writer.newLine();
}
/* ανάγνωση των στοιχείων νέων διεργασιών από το αρχείο inputFile */
public ArrayList<Process> parseProcessFile() throws FileNotFoundException, IOException {
int temp = 1;
String nextArrivalTime = reader.readLine();
String nextCpuBurstTime = reader.readLine();
if ((nextArrivalTime != null) && (nextCpuBurstTime != null)) {
do {
processes.add(new Process(temp, Integer.parseInt(nextArrivalTime), Integer.parseInt(nextCpuBurstTime)));
temp++;
nextArrivalTime = reader.readLine();
nextCpuBurstTime = reader.readLine();
} while ((nextArrivalTime != null) && (nextCpuBurstTime != null));
}
return processes; //Τοποθέτηση των νέων διεργασιών στην λίστα.
}
public void addProcessesToTemporayList() {
for (Process proc : processes) {
Main.newProcessList.addNewProcess(proc);
}
}
}
| TeamLS/Operating-System-Simulator | src/operatingsystem/ProcessGenerator.java |
2,522 | package osgi.enroute.scheduler.api;
/**
* The software utility Cron is a time-based job scheduler in Unix-like computer
* operating systems. People who set up and maintain software environments use
* cron to schedule jobs (commands or shell scripts) to run periodically at
* fixed times, dates, or intervals. It typically automates system maintenance
* or administration—though its general-purpose nature makes it useful for
* things like connecting to the Internet and downloading email at regular
* intervals.[1] The name cron comes from the Greek word for time, χρόνος
* chronos.
* <p>
* The Unix Cron defines a syntax that is used by the Cron service. A user
* should register a Cron service with the {@link CronJob#CRON} property. The
* value is according to the {link http://en.wikipedia.org/wiki/Cron}.
* <p>
*
* <pre>
* * * * * * * *
* | │ │ │ │ │ |
* | │ │ │ │ │ └ year (optional)
* | │ │ │ │ └── day of week from Monday (1) to Sunday (7).
* | │ │ │ └──── month (1 - 12) from January (1) to December (12).
* | │ │ └────── day of month (1 - 31)
* | │ └──────── hour (0 - 23)
* | └────────── min (0 - 59)
* └──────────── sec (0-59)
* </pre>
*
* <pre>
* Field name mandatory Values Special characters
* Seconds Yes 0-59 * / , -
* Minutes Yes 0-59 * / , -
* Hours Yes 0-23 * / , -
* Day of month Yes 1-31 * / , - ? L W
* Month Yes 1-12 or JAN-DEC * / , -
* Day of week Yes 1-7 or MON-SUN * / , - ? L #
* Year No 1970–2099 * / , -
* </pre>
*
* <h3>Asterisk ( * )</h3>
* <p>
* The asterisk indicates that the cron expression matches for all values of the
* field. E.g., using an asterisk in the 4th field (month) indicates every
* month.
* <h3>Slash ( / )</h3>
* <p>
* Slashes describe increments of ranges. For example 3-59/15 in the 1st field
* (minutes) indicate the third minute of the hour and every 15 minutes
* thereafter. The form "*\/..." is equivalent to the form "first-last/...",
* that is, an increment over the largest possible range of the field.
* <h3>Comma ( , )</h3>
* <p>
* Commas are used to separate items of a list. For example, using "MON,WED,FRI"
* in the 5th field (day of week) means Mondays, Wednesdays and Fridays. Hyphen
* ( - ) Hyphens define ranges. For example, 2000-2010 indicates every year
* between 2000 and 2010 AD, inclusive.
* <p>
* Additionally, you can use some fixed formats:
*
* <pre>
* @yearly (or @annually) Run once a year at midnight on the morning of January 1 0 0 1 1 *
* @monthly Run once a month at midnight on the morning of the first day of the month 0 0 1 * *
* @weekly Run once a week at midnight on Sunday morning 0 0 * * 0
* @daily Run once a day at midnight 0 0 * * *
* @hourly Run once an hour at the beginning of the hour 0 * * * *
* @reboot Run at startup @reboot (at service registration time)
* </pre>
* <p>
* Please not that for the constants we follow the Java 8 Date & Time constants.
* Major difference is the day number. In Quartz this is 0-6 for SAT-SUN while
* here it is 1-7 for MON-SUN.
*
* @param <T>
* The parameter for the cron job
*/
public interface CronJob<T> {
/**
* The service property that specifies the cron schedule. The type is
* String+.
*/
String CRON = "cron";
/**
* Run a cron job.
*
* @param data
* The data for the job
* @throws Exception
*/
public void run(T data) throws Exception;
}
| bjhargrave/osgi.enroute | osgi.enroute.base.api/src/osgi/enroute/scheduler/api/CronJob.java |
2,524 | package gr.aueb.cf.ch9;
import java.io.FileInputStream;
import java.io.FileOutputStream;
/**
* Αντιγράφει ένα αρχείο βίντεο. Υπολογίζει το χρόνο αντιγραφής.
* Χρησιμοποιεί FileInputStream kai FileOutputStream διαβάζοντας
* και γράφοντας ένα byte τη φορά.
*/
public class IOVideoCopy {
public static void main(String[] args) throws java.io.IOException {
int b, count = 0;
try (FileInputStream in = new FileInputStream("C:/Users/");
FileOutputStream out = new FileOutputStream("C:/Users/");) {
long start = System.nanoTime();
//Αντέγραψε το αρχείο
while ((b = in.read()) != -1) {
out.write(b);
count++;
}
long end = System.nanoTime();
long elapsed = end - start;
System.out.printf("Το αρχείο με μέγεθος %d Kbytes " +
"(%d bytes) αντιγράφηκε", count / 1024, count);
System.out.printf("Time: %.2f", elapsed / 1_000_000_000.0); //χρόνος εμφανίζεται σε sec
}
}
}
| KruglovaOlga/CodingFactoryJava | src/gr/aueb/cf/ch9/IOVideoCopy.java |
2,526 | package com.example.quickrepair.view.Technician.ShowConfirmedRepairRequest;
public interface TechnicianConfirmedRepairRequestView {
/**
* Προβάλει μήνυμα λάθους
* @param message Το Μήνυμα λάθους
*/
void showError(String message);
/**
* Αίτημα για ολοκλήρωση της επισκευής
*/
void complete();
/**
* Εμφανίζει τη δουλειά
* @param job Η δουλειά
*/
void setJob(String job);
/**
* Εμφανίζει το όνομα του πελάτη
* @param consumerName Το όνομα του πελάτη
*/
void setConsumerName(String consumerName);
/**
* Εμφανίζει τη διεύθυνση
* @param address Η διεύθυνση
*/
void setAddress(String address);
/**
* Εμφανίζει τα σχόλια
* @param comments Τα σχόλια
*/
void setComments(String comments);
/**
* Εμφανίζει την ημερομηνία διεξαγωγής της επισκευής
* @param conductionDate Η ημερομηνία διεξαγωγής της επισκευής
*/
void setConductionDate(String conductionDate);
/**
* Εμφανίζει το εκτιμώμενο απο τον τεχνικό χρόνο της επισκευής
* @param estimatedDuration Ο εκτιμώμενος απο τον τεχνικό χρόνος της επισκευής
*/
void setEstimatedDuration(String estimatedDuration);
/**
* Ενεργοποίηση κουμπιού ολοκλήρωσης
*/
void setButtonListeners();
}
| NickSmyr/UndergraduateProjects | 6th semester/SoftwareEngineering/android/app/src/main/java/com/example/quickrepair/view/Technician/ShowConfirmedRepairRequest/TechnicianConfirmedRepairRequestView.java |
2,527 | package com.example.quickrepair.view.Technician.ShowCompletedRepairRequest;
public interface TechnicianCompletedRepairRequestView {
/**
* Προβάλει μήνυμα λάθους
* @param message Το Μήνυμα λάθους
*/
void showError(String message);
/**
* Εμφανίζει τη δουλειά
* @param job Η δουλειά
*/
void setJob(String job);
/**
* Εμφανίζει το όνομα του πελάτη
* @param consumerName Το όνομα του πελάτη
*/
void setConsumerName(String consumerName);
/**
* Εμφανίζει τη διεύθυνση
* @param address Η διεύθυνση
*/
void setAddress(String address);
/**
* Εμφανίζει τα σχόλια
* @param comments Τα σχόλια
*/
void setComments(String comments);
/**
* Εμφανίζει την ημερομηνία διεξαγωγής της επισκευής
* @param conductionDate Η ημερομηνία διεξαγωγής της επισκευής
*/
void setConductionDate(String conductionDate);
/**
* Εμφανίζει το εκτιμώμενο απο τον τεχνικό χρόνο της επισκευής
* @param estimatedDuration Ο εκτιμώμενος απο τον τεχνικό χρόνος της επισκευής
*/
void setEstimatedDuration(String estimatedDuration);
/**
* Εμφανίζει το κόστος
* @param cost Το κόστος
*/
void setCost(String cost);
}
| NickSmyr/UndergraduateProjects | 6th semester/SoftwareEngineering/android/app/src/main/java/com/example/quickrepair/view/Technician/ShowCompletedRepairRequest/TechnicianCompletedRepairRequestView.java |
2,528 | /**
* Copyright (c) 2020-2021 Contributors to the OpenSmartHouse project
* Copyright (c) 2010-2021 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.core.scheduler;
import java.util.Map;
import org.eclipse.jdt.annotation.NonNullByDefault;
/**
* The software utility Cron is a time-based job scheduler in Unix-like computer
* operating systems. People who set up and maintain software environments use
* cron to schedule jobs (commands or shell scripts) to run periodically at
* fixed times, dates, or intervals. It typically automates system maintenance
* or administration—though its general-purpose nature makes it useful for
* things like connecting to the Internet and downloading email at regular
* intervals.[1] The name cron comes from the Greek word for time, χρόνος
* chronos.
* <p>
* The Unix Cron defines a syntax that is used by the Cron service. A user
* should register a Cron service with the {@link CronJob#CRON} property. The
* value is according to the {link http://en.wikipedia.org/wiki/Cron}.
* <p>
*
* <pre>
* * * * * * * *
* | │ │ │ │ │ |
* | │ │ │ │ │ └ year (optional)
* | │ │ │ │ └── day of week from Monday (1) to Sunday (7).
* | │ │ │ └──── month (1 - 12) from January (1) to December (12).
* | │ │ └────── day of month (1 - 31)
* | │ └──────── hour (0 - 23)
* | └────────── min (0 - 59)
* └──────────── sec (0-59)
* </pre>
*
* <pre>
* Field name mandatory Values Special characters
* Seconds Yes 0-59 * / , -
* Minutes Yes 0-59 * / , -
* Hours Yes 0-23 * / , -
* Day of month Yes 1-31 * / , - ? L W
* Month Yes 1-12 or JAN-DEC * / , -
* Day of week Yes 1-7 or MON-SUN * / , - ? L #
* Year No 1970–2099 * / , -
* </pre>
*
* <h3>Asterisk ( * )</h3>
* <p>
* The asterisk indicates that the cron expression matches for all values of the
* field. E.g., using an asterisk in the 4th field (month) indicates every
* month.
* <h3>Slash ( / )</h3>
* <p>
* Slashes describe increments of ranges. For example 3-59/15 in the 1st field
* (minutes) indicate the third minute of the hour and every 15 minutes
* thereafter. The form "*\/..." is equivalent to the form "first-last/...",
* that is, an increment over the largest possible range of the field.
* <h3>Comma ( , )</h3>
* <p>
* Commas are used to separate items of a list. For example, using "MON,WED,FRI"
* in the 5th field (day of week) means Mondays, Wednesdays and Fridays. Hyphen
* ( - ) Hyphens define ranges. For example, 2000-2010 indicates every year
* between 2000 and 2010 AD, inclusive.
* <p>
* Additionally, you can use some fixed formats:
*
* <pre>
* @yearly (or @annually) Run once a year at midnight on the morning of January 1 0 0 1 1 *
* @monthly Run once a month at midnight on the morning of the first day of the month 0 0 1 * *
* @weekly Run once a week at midnight on Sunday morning 0 0 * * 0
* @daily Run once a day at midnight 0 0 * * *
* @hourly Run once an hour at the beginning of the hour 0 * * * *
* @reboot Run at startup @reboot
* </pre>
* <p>
* Please note that for the constants we follow the Java 8 Date & Time constants.
* Major difference is the day number. In Quartz this is 0-6 for SAT-SUN while
* here it is 1-7 for MON-SUN.
*
* @author Peter Kriens - Initial contribution
* @author Simon Kaufmann - adapted to CompletableFutures
* @author Hilbrand Bouwkamp - Moved Cron scheduling to it's own interface
*/
@NonNullByDefault
public interface CronScheduler {
/**
* Schedule a runnable to be executed for the give cron expression (See
* {@link CronJob}). Every time when the cronExpression matches the current
* time, the runnable will be run. The method returns a {@link ScheduledCompletableFuture}
* that can be used to stop scheduling. This variation does not take an
* environment object.
*
* @param runnable The runnable to run
* @param cronExpression A cron expression
* @return A {@link ScheduledCompletableFuture} to cancel the schedule
*/
ScheduledCompletableFuture<Void> schedule(SchedulerRunnable runnable, String cronExpression);
/**
* Schedule a runnable to be executed for the give cron expression (See
* {@link CronJob}). Every time when the cronExpression matches the current
* time, the runnable will be run. The method returns a {@link ScheduledCompletableFuture}
* that can be used to stop scheduling. The run method of cronJob takes
* an environment object. An environment object is a custom interface where
* the names of the methods are the keys in the properties (see {@link DTOs}).
*
* @param <T> The data type of the parameter for the cron job
* @param cronJob The runnable to run
* @param cronExpression A cron expression
* @return A {@link ScheduledCompletableFuture} to cancel the schedule
*/
ScheduledCompletableFuture<Void> schedule(CronJob cronJob, Map<String, Object> config, String cronExpression);
}
| opensmarthouse/opensmarthouse-core | bundles/org.opensmarthouse.core.scheduler/src/main/java/org/openhab/core/scheduler/CronScheduler.java |
2,529 | /**
* Copyright (c) 2010-2019 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.smarthome.core.scheduler;
import java.util.Map;
import org.eclipse.jdt.annotation.NonNullByDefault;
/**
* The software utility Cron is a time-based job scheduler in Unix-like computer
* operating systems. People who set up and maintain software environments use
* cron to schedule jobs (commands or shell scripts) to run periodically at
* fixed times, dates, or intervals. It typically automates system maintenance
* or administration—though its general-purpose nature makes it useful for
* things like connecting to the Internet and downloading email at regular
* intervals.[1] The name cron comes from the Greek word for time, χρόνος
* chronos.
* <p>
* The Unix Cron defines a syntax that is used by the Cron service. A user
* should register a Cron service with the {@link CronJob#CRON} property. The
* value is according to the {link http://en.wikipedia.org/wiki/Cron}.
* <p>
*
* <pre>
* * * * * * * *
* | │ │ │ │ │ |
* | │ │ │ │ │ └ year (optional)
* | │ │ │ │ └── day of week from Monday (1) to Sunday (7).
* | │ │ │ └──── month (1 - 12) from January (1) to December (12).
* | │ │ └────── day of month (1 - 31)
* | │ └──────── hour (0 - 23)
* | └────────── min (0 - 59)
* └──────────── sec (0-59)
* </pre>
*
* <pre>
* Field name mandatory Values Special characters
* Seconds Yes 0-59 * / , -
* Minutes Yes 0-59 * / , -
* Hours Yes 0-23 * / , -
* Day of month Yes 1-31 * / , - ? L W
* Month Yes 1-12 or JAN-DEC * / , -
* Day of week Yes 1-7 or MON-SUN * / , - ? L #
* Year No 1970–2099 * / , -
* </pre>
*
* <h3>Asterisk ( * )</h3>
* <p>
* The asterisk indicates that the cron expression matches for all values of the
* field. E.g., using an asterisk in the 4th field (month) indicates every
* month.
* <h3>Slash ( / )</h3>
* <p>
* Slashes describe increments of ranges. For example 3-59/15 in the 1st field
* (minutes) indicate the third minute of the hour and every 15 minutes
* thereafter. The form "*\/..." is equivalent to the form "first-last/...",
* that is, an increment over the largest possible range of the field.
* <h3>Comma ( , )</h3>
* <p>
* Commas are used to separate items of a list. For example, using "MON,WED,FRI"
* in the 5th field (day of week) means Mondays, Wednesdays and Fridays. Hyphen
* ( - ) Hyphens define ranges. For example, 2000-2010 indicates every year
* between 2000 and 2010 AD, inclusive.
* <p>
* Additionally, you can use some fixed formats:
*
* <pre>
* @yearly (or @annually) Run once a year at midnight on the morning of January 1 0 0 1 1 *
* @monthly Run once a month at midnight on the morning of the first day of the month 0 0 1 * *
* @weekly Run once a week at midnight on Sunday morning 0 0 * * 0
* @daily Run once a day at midnight 0 0 * * *
* @hourly Run once an hour at the beginning of the hour 0 * * * *
* @reboot Run at startup @reboot
* </pre>
* <p>
* Please note that for the constants we follow the Java 8 Date & Time constants.
* Major difference is the day number. In Quartz this is 0-6 for SAT-SUN while
* here it is 1-7 for MON-SUN.
*
* @author Peter Kriens - initial contribution and API
* @author Simon Kaufmann - adapted to CompletableFutures
* @author Hilbrand Bouwkamp - Moved Cron scheduling to it's own interface
*/
@NonNullByDefault
public interface CronScheduler {
/**
* Schedule a runnable to be executed for the give cron expression (See
* {@link CronJob}). Every time when the cronExpression matches the current
* time, the runnable will be run. The method returns a {@link ScheduledCompletableFuture}
* that can be used to stop scheduling. This variation does not take an
* environment object.
*
* @param runnable The runnable to run
* @param cronExpression A cron expression
* @return A {@link ScheduledCompletableFuture} to cancel the schedule
*/
ScheduledCompletableFuture<Void> schedule(SchedulerRunnable runnable, String cronExpression);
/**
* Schedule a runnable to be executed for the give cron expression (See
* {@link CronJob}). Every time when the cronExpression matches the current
* time, the runnable will be run. The method returns a {@link ScheduledCompletableFuture}
* that can be used to stop scheduling. The run method of cronJob takes
* an environment object. An environment object is a custom interface where
* the names of the methods are the keys in the properties (see {@link DTOs}).
*
* @param <T> The data type of the parameter for the cron job
* @param cronJob The runnable to run
* @param cronExpression A cron expression
* @return A {@link ScheduledCompletableFuture} to cancel the schedule
*/
ScheduledCompletableFuture<Void> schedule(CronJob cronJob, Map<String, Object> config, String cronExpression);
}
| NorwinYu/UoN-Final-Year-Project-Public-Database | Download-Java-Files/Normal/CronScheduler.java |
2,530 | /**
* Copyright (c) 2010-2021 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.core.scheduler;
import java.util.Map;
import org.eclipse.jdt.annotation.NonNullByDefault;
/**
* The software utility Cron is a time-based job scheduler in Unix-like computer
* operating systems. People who set up and maintain software environments use
* cron to schedule jobs (commands or shell scripts) to run periodically at
* fixed times, dates, or intervals. It typically automates system maintenance
* or administration—though its general-purpose nature makes it useful for
* things like connecting to the Internet and downloading email at regular
* intervals.[1] The name cron comes from the Greek word for time, χρόνος
* chronos.
* <p>
* The Unix Cron defines a syntax that is used by the Cron service. A user
* should register a Cron service with the {@link CronJob#CRON} property. The
* value is according to the <a href="https://en.wikipedia.org/wiki/Cron">Cron</a>.
* <p>
*
* <pre>
* * * * * * * *
* | │ │ │ │ │ |
* | │ │ │ │ │ └ year (optional)
* | │ │ │ │ └── day of week from Monday (1) to Sunday (7).
* | │ │ │ └──── month (1 - 12) from January (1) to December (12).
* | │ │ └────── day of month (1 - 31)
* | │ └──────── hour (0 - 23)
* | └────────── min (0 - 59)
* └──────────── sec (0-59)
* </pre>
*
* <pre>
* Field name mandatory Values Special characters
* Seconds Yes 0-59 * / , -
* Minutes Yes 0-59 * / , -
* Hours Yes 0-23 * / , -
* Day of month Yes 1-31 * / , - ? L W
* Month Yes 1-12 or JAN-DEC * / , -
* Day of week Yes 1-7 or MON-SUN * / , - ? L #
* Year No 1970–2099 * / , -
* </pre>
*
* <h3>Asterisk ( * )</h3>
* <p>
* The asterisk indicates that the cron expression matches for all values of the
* field. E.g., using an asterisk in the 4th field (month) indicates every
* month.
* <h3>Slash ( / )</h3>
* <p>
* Slashes describe increments of ranges. For example 3-59/15 in the 1st field
* (minutes) indicate the third minute of the hour and every 15 minutes
* thereafter. The form "*\/..." is equivalent to the form "first-last/...",
* that is, an increment over the largest possible range of the field.
* <h3>Comma ( , )</h3>
* <p>
* Commas are used to separate items of a list. For example, using "MON,WED,FRI"
* in the 5th field (day of week) means Mondays, Wednesdays and Fridays. Hyphen
* ( - ) Hyphens define ranges. For example, 2000-2010 indicates every year
* between 2000 and 2010 AD, inclusive.
* <p>
* Additionally, you can use some fixed formats:
*
* <pre>
* @yearly (or @annually) Run once a year at midnight on the morning of January 1 0 0 1 1 *
* @monthly Run once a month at midnight on the morning of the first day of the month 0 0 1 * *
* @weekly Run once a week at midnight on Sunday morning 0 0 * * 0
* @daily Run once a day at midnight 0 0 * * *
* @hourly Run once an hour at the beginning of the hour 0 * * * *
* @reboot Run at startup @reboot
* </pre>
* <p>
* Please note that for the constants we follow the Java 8 Date & Time constants.
* Major difference is the day number. In Quartz this is 0-6 for SAT-SUN while
* here it is 1-7 for MON-SUN.
*
* @author Peter Kriens - Initial contribution
* @author Simon Kaufmann - adapted to CompletableFutures
* @author Hilbrand Bouwkamp - Moved Cron scheduling to it's own interface
*/
@NonNullByDefault
public interface CronScheduler {
/**
* Schedule a runnable to be executed for the give cron expression (See
* {@link CronJob}). Every time when the cronExpression matches the current
* time, the runnable will be run. The method returns a {@link ScheduledCompletableFuture}
* that can be used to stop scheduling. This variation does not take an
* environment object.
*
* @param runnable The runnable to run
* @param cronExpression A cron expression
* @return A {@link ScheduledCompletableFuture} to cancel the schedule
*/
ScheduledCompletableFuture<Void> schedule(SchedulerRunnable runnable, String cronExpression);
/**
* Schedule a runnable to be executed for the give cron expression (See
* {@link CronJob}). Every time when the cronExpression matches the current
* time, the runnable will be run. The method returns a {@link ScheduledCompletableFuture}
* that can be used to stop scheduling. The run method of cronJob takes
* an environment object. An environment object is a custom interface where
* the names of the methods are the keys in the properties (see {@link DTOs}).
*
* @param <T> The data type of the parameter for the cron job
* @param cronJob The runnable to run
* @param cronExpression A cron expression
* @return A {@link ScheduledCompletableFuture} to cancel the schedule
*/
ScheduledCompletableFuture<Void> schedule(CronJob cronJob, Map<String, Object> config, String cronExpression);
}
| J-N-K/openhab-core | bundles/org.openhab.core/src/main/java/org/openhab/core/scheduler/CronScheduler.java |
2,531 | /**
* Copyright (c) 2010-2020 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.core.scheduler;
import java.util.Map;
import org.eclipse.jdt.annotation.NonNullByDefault;
/**
* The software utility Cron is a time-based job scheduler in Unix-like computer
* operating systems. People who set up and maintain software environments use
* cron to schedule jobs (commands or shell scripts) to run periodically at
* fixed times, dates, or intervals. It typically automates system maintenance
* or administration—though its general-purpose nature makes it useful for
* things like connecting to the Internet and downloading email at regular
* intervals.[1] The name cron comes from the Greek word for time, χρόνος
* chronos.
* <p>
* The Unix Cron defines a syntax that is used by the Cron service. A user
* should register a Cron service with the {@link CronJob#CRON} property. The
* value is according to the <a href="https://en.wikipedia.org/wiki/Cron">Cron</a>.
* <p>
*
* <pre>
* * * * * * * *
* | │ │ │ │ │ |
* | │ │ │ │ │ └ year (optional)
* | │ │ │ │ └── day of week from Monday (1) to Sunday (7).
* | │ │ │ └──── month (1 - 12) from January (1) to December (12).
* | │ │ └────── day of month (1 - 31)
* | │ └──────── hour (0 - 23)
* | └────────── min (0 - 59)
* └──────────── sec (0-59)
* </pre>
*
* <pre>
* Field name mandatory Values Special characters
* Seconds Yes 0-59 * / , -
* Minutes Yes 0-59 * / , -
* Hours Yes 0-23 * / , -
* Day of month Yes 1-31 * / , - ? L W
* Month Yes 1-12 or JAN-DEC * / , -
* Day of week Yes 1-7 or MON-SUN * / , - ? L #
* Year No 1970–2099 * / , -
* </pre>
*
* <h3>Asterisk ( * )</h3>
* <p>
* The asterisk indicates that the cron expression matches for all values of the
* field. E.g., using an asterisk in the 4th field (month) indicates every
* month.
* <h3>Slash ( / )</h3>
* <p>
* Slashes describe increments of ranges. For example 3-59/15 in the 1st field
* (minutes) indicate the third minute of the hour and every 15 minutes
* thereafter. The form "*\/..." is equivalent to the form "first-last/...",
* that is, an increment over the largest possible range of the field.
* <h3>Comma ( , )</h3>
* <p>
* Commas are used to separate items of a list. For example, using "MON,WED,FRI"
* in the 5th field (day of week) means Mondays, Wednesdays and Fridays. Hyphen
* ( - ) Hyphens define ranges. For example, 2000-2010 indicates every year
* between 2000 and 2010 AD, inclusive.
* <p>
* Additionally, you can use some fixed formats:
*
* <pre>
* @yearly (or @annually) Run once a year at midnight on the morning of January 1 0 0 1 1 *
* @monthly Run once a month at midnight on the morning of the first day of the month 0 0 1 * *
* @weekly Run once a week at midnight on Sunday morning 0 0 * * 0
* @daily Run once a day at midnight 0 0 * * *
* @hourly Run once an hour at the beginning of the hour 0 * * * *
* @reboot Run at startup @reboot
* </pre>
* <p>
* Please note that for the constants we follow the Java 8 Date & Time constants.
* Major difference is the day number. In Quartz this is 0-6 for SAT-SUN while
* here it is 1-7 for MON-SUN.
*
* @author Peter Kriens - Initial contribution
* @author Simon Kaufmann - adapted to CompletableFutures
* @author Hilbrand Bouwkamp - Moved Cron scheduling to it's own interface
*/
@NonNullByDefault
public interface CronScheduler {
/**
* Schedule a runnable to be executed for the give cron expression (See
* {@link CronJob}). Every time when the cronExpression matches the current
* time, the runnable will be run. The method returns a {@link ScheduledCompletableFuture}
* that can be used to stop scheduling. This variation does not take an
* environment object.
*
* @param runnable The runnable to run
* @param cronExpression A cron expression
* @return A {@link ScheduledCompletableFuture} to cancel the schedule
*/
ScheduledCompletableFuture<Void> schedule(SchedulerRunnable runnable, String cronExpression);
/**
* Schedule a runnable to be executed for the give cron expression (See
* {@link CronJob}). Every time when the cronExpression matches the current
* time, the runnable will be run. The method returns a {@link ScheduledCompletableFuture}
* that can be used to stop scheduling. The run method of cronJob takes
* an environment object. An environment object is a custom interface where
* the names of the methods are the keys in the properties (see {@link DTOs}).
*
* @param <T> The data type of the parameter for the cron job
* @param cronJob The runnable to run
* @param cronExpression A cron expression
* @return A {@link ScheduledCompletableFuture} to cancel the schedule
*/
ScheduledCompletableFuture<Void> schedule(CronJob cronJob, Map<String, Object> config, String cronExpression);
}
| Hilbrand/openhab-core | bundles/org.openhab.core/src/main/java/org/openhab/core/scheduler/CronScheduler.java |
2,532 | /**
* Copyright (c) 2010-2019 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.smarthome.core.scheduler;
import java.util.Map;
import org.eclipse.jdt.annotation.NonNullByDefault;
/**
* The software utility Cron is a time-based job scheduler in Unix-like computer
* operating systems. People who set up and maintain software environments use
* cron to schedule jobs (commands or shell scripts) to run periodically at
* fixed times, dates, or intervals. It typically automates system maintenance
* or administration—though its general-purpose nature makes it useful for
* things like connecting to the Internet and downloading email at regular
* intervals.[1] The name cron comes from the Greek word for time, χρόνος
* chronos.
* <p>
* The Unix Cron defines a syntax that is used by the Cron service. A user
* should register a Cron service with the {@link CronJob#CRON} property. The
* value is according to the {link http://en.wikipedia.org/wiki/Cron}.
* <p>
*
* <pre>
* * * * * * * *
* | │ │ │ │ │ |
* | │ │ │ │ │ └ year (optional)
* | │ │ │ │ └── day of week from Monday (1) to Sunday (7).
* | │ │ │ └──── month (1 - 12) from January (1) to December (12).
* | │ │ └────── day of month (1 - 31)
* | │ └──────── hour (0 - 23)
* | └────────── min (0 - 59)
* └──────────── sec (0-59)
* </pre>
*
* <pre>
* Field name mandatory Values Special characters
* Seconds Yes 0-59 * / , -
* Minutes Yes 0-59 * / , -
* Hours Yes 0-23 * / , -
* Day of month Yes 1-31 * / , - ? L W
* Month Yes 1-12 or JAN-DEC * / , -
* Day of week Yes 1-7 or MON-SUN * / , - ? L #
* Year No 1970–2099 * / , -
* </pre>
*
* <h3>Asterisk ( * )</h3>
* <p>
* The asterisk indicates that the cron expression matches for all values of the
* field. E.g., using an asterisk in the 4th field (month) indicates every
* month.
* <h3>Slash ( / )</h3>
* <p>
* Slashes describe increments of ranges. For example 3-59/15 in the 1st field
* (minutes) indicate the third minute of the hour and every 15 minutes
* thereafter. The form "*\/..." is equivalent to the form "first-last/...",
* that is, an increment over the largest possible range of the field.
* <h3>Comma ( , )</h3>
* <p>
* Commas are used to separate items of a list. For example, using "MON,WED,FRI"
* in the 5th field (day of week) means Mondays, Wednesdays and Fridays. Hyphen
* ( - ) Hyphens define ranges. For example, 2000-2010 indicates every year
* between 2000 and 2010 AD, inclusive.
* <p>
* Additionally, you can use some fixed formats:
*
* <pre>
* @yearly (or @annually) Run once a year at midnight on the morning of January 1 0 0 1 1 *
* @monthly Run once a month at midnight on the morning of the first day of the month 0 0 1 * *
* @weekly Run once a week at midnight on Sunday morning 0 0 * * 0
* @daily Run once a day at midnight 0 0 * * *
* @hourly Run once an hour at the beginning of the hour 0 * * * *
* @reboot Run at startup @reboot
* </pre>
* <p>
* Please note that for the constants we follow the Java 8 Date & Time constants.
* Major difference is the day number. In Quartz this is 0-6 for SAT-SUN while
* here it is 1-7 for MON-SUN.
*
* @author Peter Kriens - Initial contribution
* @author Simon Kaufmann - adapted to CompletableFutures
* @author Hilbrand Bouwkamp - Moved Cron scheduling to it's own interface
*/
@NonNullByDefault
public interface CronScheduler {
/**
* Schedule a runnable to be executed for the give cron expression (See
* {@link CronJob}). Every time when the cronExpression matches the current
* time, the runnable will be run. The method returns a {@link ScheduledCompletableFuture}
* that can be used to stop scheduling. This variation does not take an
* environment object.
*
* @param runnable The runnable to run
* @param cronExpression A cron expression
* @return A {@link ScheduledCompletableFuture} to cancel the schedule
*/
ScheduledCompletableFuture<Void> schedule(SchedulerRunnable runnable, String cronExpression);
/**
* Schedule a runnable to be executed for the give cron expression (See
* {@link CronJob}). Every time when the cronExpression matches the current
* time, the runnable will be run. The method returns a {@link ScheduledCompletableFuture}
* that can be used to stop scheduling. The run method of cronJob takes
* an environment object. An environment object is a custom interface where
* the names of the methods are the keys in the properties (see {@link DTOs}).
*
* @param <T> The data type of the parameter for the cron job
* @param cronJob The runnable to run
* @param cronExpression A cron expression
* @return A {@link ScheduledCompletableFuture} to cancel the schedule
*/
ScheduledCompletableFuture<Void> schedule(CronJob cronJob, Map<String, Object> config, String cronExpression);
}
| rotty3000/openhab-core | bundles/org.openhab.core/src/main/java/org/eclipse/smarthome/core/scheduler/CronScheduler.java |
2,533 | /**
* Copyright (c) 2010-2020 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.core.scheduler;
import java.util.Map;
import org.eclipse.jdt.annotation.NonNullByDefault;
/**
* The software utility Cron is a time-based job scheduler in Unix-like computer
* operating systems. People who set up and maintain software environments use
* cron to schedule jobs (commands or shell scripts) to run periodically at
* fixed times, dates, or intervals. It typically automates system maintenance
* or administration—though its general-purpose nature makes it useful for
* things like connecting to the Internet and downloading email at regular
* intervals.[1] The name cron comes from the Greek word for time, χρόνος
* chronos.
* <p>
* The Unix Cron defines a syntax that is used by the Cron service. A user
* should register a Cron service with the {@link CronJob#CRON} property. The
* value is according to the {link http://en.wikipedia.org/wiki/Cron}.
* <p>
*
* <pre>
* * * * * * * *
* | │ │ │ │ │ |
* | │ │ │ │ │ └ year (optional)
* | │ │ │ │ └── day of week from Monday (1) to Sunday (7).
* | │ │ │ └──── month (1 - 12) from January (1) to December (12).
* | │ │ └────── day of month (1 - 31)
* | │ └──────── hour (0 - 23)
* | └────────── min (0 - 59)
* └──────────── sec (0-59)
* </pre>
*
* <pre>
* Field name mandatory Values Special characters
* Seconds Yes 0-59 * / , -
* Minutes Yes 0-59 * / , -
* Hours Yes 0-23 * / , -
* Day of month Yes 1-31 * / , - ? L W
* Month Yes 1-12 or JAN-DEC * / , -
* Day of week Yes 1-7 or MON-SUN * / , - ? L #
* Year No 1970–2099 * / , -
* </pre>
*
* <h3>Asterisk ( * )</h3>
* <p>
* The asterisk indicates that the cron expression matches for all values of the
* field. E.g., using an asterisk in the 4th field (month) indicates every
* month.
* <h3>Slash ( / )</h3>
* <p>
* Slashes describe increments of ranges. For example 3-59/15 in the 1st field
* (minutes) indicate the third minute of the hour and every 15 minutes
* thereafter. The form "*\/..." is equivalent to the form "first-last/...",
* that is, an increment over the largest possible range of the field.
* <h3>Comma ( , )</h3>
* <p>
* Commas are used to separate items of a list. For example, using "MON,WED,FRI"
* in the 5th field (day of week) means Mondays, Wednesdays and Fridays. Hyphen
* ( - ) Hyphens define ranges. For example, 2000-2010 indicates every year
* between 2000 and 2010 AD, inclusive.
* <p>
* Additionally, you can use some fixed formats:
*
* <pre>
* @yearly (or @annually) Run once a year at midnight on the morning of January 1 0 0 1 1 *
* @monthly Run once a month at midnight on the morning of the first day of the month 0 0 1 * *
* @weekly Run once a week at midnight on Sunday morning 0 0 * * 0
* @daily Run once a day at midnight 0 0 * * *
* @hourly Run once an hour at the beginning of the hour 0 * * * *
* @reboot Run at startup @reboot
* </pre>
* <p>
* Please note that for the constants we follow the Java 8 Date & Time constants.
* Major difference is the day number. In Quartz this is 0-6 for SAT-SUN while
* here it is 1-7 for MON-SUN.
*
* @author Peter Kriens - Initial contribution
* @author Simon Kaufmann - adapted to CompletableFutures
* @author Hilbrand Bouwkamp - Moved Cron scheduling to it's own interface
*/
@NonNullByDefault
public interface CronScheduler {
/**
* Schedule a runnable to be executed for the give cron expression (See
* {@link CronJob}). Every time when the cronExpression matches the current
* time, the runnable will be run. The method returns a {@link ScheduledCompletableFuture}
* that can be used to stop scheduling. This variation does not take an
* environment object.
*
* @param runnable The runnable to run
* @param cronExpression A cron expression
* @return A {@link ScheduledCompletableFuture} to cancel the schedule
*/
ScheduledCompletableFuture<Void> schedule(SchedulerRunnable runnable, String cronExpression);
/**
* Schedule a runnable to be executed for the give cron expression (See
* {@link CronJob}). Every time when the cronExpression matches the current
* time, the runnable will be run. The method returns a {@link ScheduledCompletableFuture}
* that can be used to stop scheduling. The run method of cronJob takes
* an environment object. An environment object is a custom interface where
* the names of the methods are the keys in the properties (see {@link DTOs}).
*
* @param <T> The data type of the parameter for the cron job
* @param cronJob The runnable to run
* @param cronExpression A cron expression
* @return A {@link ScheduledCompletableFuture} to cancel the schedule
*/
ScheduledCompletableFuture<Void> schedule(CronJob cronJob, Map<String, Object> config, String cronExpression);
}
| RafalLukawiecki/openhab-core | bundles/org.openhab.core/src/main/java/org/openhab/core/scheduler/CronScheduler.java |
2,534 | /**
* Copyright (c) 2010-2019 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.smarthome.core.scheduler;
import java.util.Map;
import org.eclipse.jdt.annotation.NonNullByDefault;
/**
* The software utility Cron is a time-based job scheduler in Unix-like computer
* operating systems. People who set up and maintain software environments use
* cron to schedule jobs (commands or shell scripts) to run periodically at
* fixed times, dates, or intervals. It typically automates system maintenance
* or administration—though its general-purpose nature makes it useful for
* things like connecting to the Internet and downloading email at regular
* intervals.[1] The name cron comes from the Greek word for time, χρόνος
* chronos.
* <p>
* The Unix Cron defines a syntax that is used by the Cron service. A user
* should register a Cron service with the {@link CronJob#CRON} property. The
* value is according to the {link http://en.wikipedia.org/wiki/Cron}.
* <p>
*
* <pre>
* * * * * * * *
* | │ │ │ │ │ |
* | │ │ │ │ │ └ year (optional)
* | │ │ │ │ └── day of week from Monday (1) to Sunday (7).
* | │ │ │ └──── month (1 - 12) from January (1) to December (12).
* | │ │ └────── day of month (1 - 31)
* | │ └──────── hour (0 - 23)
* | └────────── min (0 - 59)
* └──────────── sec (0-59)
* </pre>
*
* <pre>
* Field name mandatory Values Special characters
* Seconds Yes 0-59 * / , -
* Minutes Yes 0-59 * / , -
* Hours Yes 0-23 * / , -
* Day of month Yes 1-31 * / , - ? L W
* Month Yes 1-12 or JAN-DEC * / , -
* Day of week Yes 1-7 or MON-SUN * / , - ? L #
* Year No 1970–2099 * / , -
* </pre>
*
* <h3>Asterisk ( * )</h3>
* <p>
* The asterisk indicates that the cron expression matches for all values of the
* field. E.g., using an asterisk in the 4th field (month) indicates every
* month.
* <h3>Slash ( / )</h3>
* <p>
* Slashes describe increments of ranges. For example 3-59/15 in the 1st field
* (minutes) indicate the third minute of the hour and every 15 minutes
* thereafter. The form "*\/..." is equivalent to the form "first-last/...",
* that is, an increment over the largest possible range of the field.
* <h3>Comma ( , )</h3>
* <p>
* Commas are used to separate items of a list. For example, using "MON,WED,FRI"
* in the 5th field (day of week) means Mondays, Wednesdays and Fridays. Hyphen
* ( - ) Hyphens define ranges. For example, 2000-2010 indicates every year
* between 2000 and 2010 AD, inclusive.
* <p>
* Additionally, you can use some fixed formats:
*
* <pre>
* @yearly (or @annually) Run once a year at midnight on the morning of January 1 0 0 1 1 *
* @monthly Run once a month at midnight on the morning of the first day of the month 0 0 1 * *
* @weekly Run once a week at midnight on Sunday morning 0 0 * * 0
* @daily Run once a day at midnight 0 0 * * *
* @hourly Run once an hour at the beginning of the hour 0 * * * *
* @reboot Run at startup @reboot
* </pre>
* <p>
* Please note that for the constants we follow the Java 8 Date & Time constants.
* Major difference is the day number. In Quartz this is 0-6 for SAT-SUN while
* here it is 1-7 for MON-SUN.
*
* @author Peter Kriens - Initial contribution and API
* @author Simon Kaufmann - adapted to CompletableFutures
* @author Hilbrand Bouwkamp - Moved Cron scheduling to it's own interface
*/
@NonNullByDefault
public interface CronScheduler {
/**
* Schedule a runnable to be executed for the give cron expression (See
* {@link CronJob}). Every time when the cronExpression matches the current
* time, the runnable will be run. The method returns a {@link ScheduledCompletableFuture}
* that can be used to stop scheduling. This variation does not take an
* environment object.
*
* @param runnable The runnable to run
* @param cronExpression A cron expression
* @return A {@link ScheduledCompletableFuture} to cancel the schedule
*/
ScheduledCompletableFuture<Void> schedule(SchedulerRunnable runnable, String cronExpression);
/**
* Schedule a runnable to be executed for the give cron expression (See
* {@link CronJob}). Every time when the cronExpression matches the current
* time, the runnable will be run. The method returns a {@link ScheduledCompletableFuture}
* that can be used to stop scheduling. The run method of cronJob takes
* an environment object. An environment object is a custom interface where
* the names of the methods are the keys in the properties (see {@link DTOs}).
*
* @param <T> The data type of the parameter for the cron job
* @param cronJob The runnable to run
* @param cronExpression A cron expression
* @return A {@link ScheduledCompletableFuture} to cancel the schedule
*/
ScheduledCompletableFuture<Void> schedule(CronJob cronJob, Map<String, Object> config, String cronExpression);
}
| adjexpress/openhab-core | bundles/org.openhab.core/src/main/java/org/eclipse/smarthome/core/scheduler/CronScheduler.java |
2,535 | /**
* Copyright (c) 2014,2019 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.smarthome.core.scheduler;
import java.util.Map;
import org.eclipse.jdt.annotation.NonNullByDefault;
/**
* The software utility Cron is a time-based job scheduler in Unix-like computer
* operating systems. People who set up and maintain software environments use
* cron to schedule jobs (commands or shell scripts) to run periodically at
* fixed times, dates, or intervals. It typically automates system maintenance
* or administration—though its general-purpose nature makes it useful for
* things like connecting to the Internet and downloading email at regular
* intervals.[1] The name cron comes from the Greek word for time, χρόνος
* chronos.
* <p>
* The Unix Cron defines a syntax that is used by the Cron service. A user
* should register a Cron service with the {@link CronJob#CRON} property. The
* value is according to the {link http://en.wikipedia.org/wiki/Cron}.
* <p>
*
* <pre>
* * * * * * * *
* | │ │ │ │ │ |
* | │ │ │ │ │ └ year (optional)
* | │ │ │ │ └── day of week from Monday (1) to Sunday (7).
* | │ │ │ └──── month (1 - 12) from January (1) to December (12).
* | │ │ └────── day of month (1 - 31)
* | │ └──────── hour (0 - 23)
* | └────────── min (0 - 59)
* └──────────── sec (0-59)
* </pre>
*
* <pre>
* Field name mandatory Values Special characters
* Seconds Yes 0-59 * / , -
* Minutes Yes 0-59 * / , -
* Hours Yes 0-23 * / , -
* Day of month Yes 1-31 * / , - ? L W
* Month Yes 1-12 or JAN-DEC * / , -
* Day of week Yes 1-7 or MON-SUN * / , - ? L #
* Year No 1970–2099 * / , -
* </pre>
*
* <h3>Asterisk ( * )</h3>
* <p>
* The asterisk indicates that the cron expression matches for all values of the
* field. E.g., using an asterisk in the 4th field (month) indicates every
* month.
* <h3>Slash ( / )</h3>
* <p>
* Slashes describe increments of ranges. For example 3-59/15 in the 1st field
* (minutes) indicate the third minute of the hour and every 15 minutes
* thereafter. The form "*\/..." is equivalent to the form "first-last/...",
* that is, an increment over the largest possible range of the field.
* <h3>Comma ( , )</h3>
* <p>
* Commas are used to separate items of a list. For example, using "MON,WED,FRI"
* in the 5th field (day of week) means Mondays, Wednesdays and Fridays. Hyphen
* ( - ) Hyphens define ranges. For example, 2000-2010 indicates every year
* between 2000 and 2010 AD, inclusive.
* <p>
* Additionally, you can use some fixed formats:
*
* <pre>
* @yearly (or @annually) Run once a year at midnight on the morning of January 1 0 0 1 1 *
* @monthly Run once a month at midnight on the morning of the first day of the month 0 0 1 * *
* @weekly Run once a week at midnight on Sunday morning 0 0 * * 0
* @daily Run once a day at midnight 0 0 * * *
* @hourly Run once an hour at the beginning of the hour 0 * * * *
* @reboot Run at startup @reboot
* </pre>
* <p>
* Please note that for the constants we follow the Java 8 Date & Time constants.
* Major difference is the day number. In Quartz this is 0-6 for SAT-SUN while
* here it is 1-7 for MON-SUN.
*
* @author Peter Kriens - initial contribution and API
* @author Simon Kaufmann - adapted to CompletableFutures
* @author Hilbrand Bouwkamp - Moved Cron scheduling to it's own interface
*/
@NonNullByDefault
public interface CronScheduler {
/**
* Schedule a runnable to be executed for the give cron expression (See
* {@link CronJob}). Every time when the cronExpression matches the current
* time, the runnable will be run. The method returns a {@link ScheduledCompletableFuture}
* that can be used to stop scheduling. This variation does not take an
* environment object.
*
* @param runnable The runnable to run
* @param cronExpression A cron expression
* @return A {@link ScheduledCompletableFuture} to cancel the schedule
*/
ScheduledCompletableFuture<Void> schedule(SchedulerRunnable runnable, String cronExpression);
/**
* Schedule a runnable to be executed for the give cron expression (See
* {@link CronJob}). Every time when the cronExpression matches the current
* time, the runnable will be run. The method returns a {@link ScheduledCompletableFuture}
* that can be used to stop scheduling. The run method of cronJob takes
* an environment object. An environment object is a custom interface where
* the names of the methods are the keys in the properties (see {@link DTOs}).
*
* @param <T> The data type of the parameter for the cron job
* @param cronJob The runnable to run
* @param cronExpression A cron expression
* @return A {@link ScheduledCompletableFuture} to cancel the schedule
*/
ScheduledCompletableFuture<Void> schedule(CronJob cronJob, Map<String, Object> config, String cronExpression);
}
| evansj/openhab-core | bundles/org.openhab.core/src/main/java/org/eclipse/smarthome/core/scheduler/CronScheduler.java |
2,536 | package api;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import static org.junit.Assert.*;
public class ReviewTest {
public ArrayList<Accommodation> AccommodationsDB;
public ArrayList<Review> ReviewsDB;
public ArrayList<GeneralUser> AccountsDB;
public Review r1;
public Accommodation a;
public Accommodation a2;
public String time_now;
@Before
public void setUp() throws Exception {
AccommodationsDB= (ArrayList<Accommodation>) FileInteractions.loadFromBinaryFile(("src/files/accommodations.bin"));
ReviewsDB=(ArrayList<Review>) FileInteractions.loadFromBinaryFile(("src/files/reviews.bin"));
AccountsDB=(ArrayList<GeneralUser>) FileInteractions.loadFromBinaryFile(("src/files/accounts.bin"));
RegularUser gen = new RegularUser("test","test","test","test");
DateTimeFormatter format = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss"); //format για να φαίνεται ωραία η ημερομηνία και ο χρόνος
time_now = LocalDateTime.now().format(format).toString();
time_now = time_now.substring(0,14);
a = new Accommodation("test","a","a","aa","","1234","test");
a2 = new Accommodation("test2","a","a","aa","","1234","test");
r1=new Review(gen,a);
r1.setReviewStars(5);
r1.setReviewText("test");
}
@After
public void tearDown() throws Exception {
FileInteractions.saveToBinaryFile("src/files/accommodations.bin",AccommodationsDB);
FileInteractions.saveToBinaryFile("src/files/accounts.bin",AccountsDB);
FileInteractions.saveToBinaryFile("src/files/reviews.bin",ReviewsDB);
}
@Test
public void setReviewText() {
r1.setReviewText("test2");
assertEquals(r1.getReviewText(),"test2");
}
@Test
public void setReviewStars() {
r1.setReviewStars(3);
assertEquals(r1.getReviewStars(),3);
}
@Test
public void setAccommodationReviewed() {
r1.setAccommodationReviewed(a2);
assertEquals(r1.getAccommodationReviewed().getOwner(),"test2");
}
@Test
public void getReviewStars() {
assertEquals(r1.getReviewStars(),5);
}
@Test
public void getAuthor() {
assertEquals(r1.getAuthor().getUsername(),"test");
}
@Test
public void getAccommodationReviewed() {
assertTrue(r1.getAccommodationReviewed().equals(a));
}
@Test
public void getCurrentDate() {
assertTrue(r1.getCurrentDate().contains(time_now));
}
@Test
public void getReviewText() {
assertEquals(r1.getReviewText(),"test");
}
@Test
public void delete() {
r1.delete();
assertEquals(a.getNumberOfReviews(),0);
}
} | dallasGeorge/reviewsApp | test/api/ReviewTest.java |
2,539 | import java.util.*;
public class Main {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<String>();
names.add("John");
names.add("Bob");
names.add("Nick");
names.add("Mary");
names.add("Helen");
System.out.println("----Sorted----");
Collections.sort(names); // Ταξινομώ την λίστα
for(String name: names)
System.out.println(name);
System.out.println("----Reversed----");
Collections.reverse(names); // Αντιστρέφω την ταξινόμηση
for(String name: names)
System.out.println(name);
System.out.println("----Shuffled----");
Collections.shuffle(names); // Τυχαίο ανακάτεμα. Τυχαία σειρά
for(String name: names)
System.out.println(name);
System.out.println("----Swapped----");
Collections.swap(names, 2, 3); // Εναλλαγή σειράς
for(String name: names)
System.out.println(name);
System.out.println("----Frequency----");
names.add("Mary");
names.add("Mary");
int freq = Collections.frequency(names, "Mary"); // Εύρεση συχνότητας εμφάνισης
System.out.println("Frequency of Mary is: " + freq);
System.out.println("----Min and Max elements----"); // Βρίσκω το ελάχιστο και το μέγιστο
String max = Collections.max(names);
String min = Collections.min(names);
System.out.println("Max is: " + max);
System.out.println("Min is: " + min);
}
}
| iosifidis/UoM-Applied-Informatics | s3/object_oriented_programming/lectures/DataStructures9_Algorithms/src/Main.java |
2,540 | /*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package it2021091;
import static it2021091.It2021091.activeUser;
import static it2021091.It2021091.personsList;
import static it2021091.It2021091.showsList;
import static it2021091.It2021091.usersList;
import java.util.ArrayList;
import java.util.Scanner;
/**
*
* @author John skoul
*/
public class Account {
protected String username;
protected String password;
public Account(String username, String password) {
this.username = username;
this.password = password;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public void signInUser(User user){
activeUser=user;
}
public static void signOutUser(){
activeUser=null;
}
public void registerUser(String username,String password,String email){
User user = new User(username,password,email);
usersList.add(user);
System.out.println(user.toString());
}
public ArrayList<Show> searchShows(){
Scanner input = new Scanner(System.in);
System.out.println("Enter the title or firstYear to search a show:");
String search=input.nextLine();
ArrayList<Show> results= new ArrayList<>();
//βρίσκω τα αποτελεσματα που ταιριάζουν με αυτό που αναζητώ
for (Show show : showsList) {
if (show.getTitle().equalsIgnoreCase( search ) || Integer.toString( show.getFirstYear() ).equalsIgnoreCase( search ) ) {
results.add(show);
}
}
return results;
}
public Person searchPerson(){
Scanner input=new Scanner(System.in);
System.out.println("Enter the fullName of an actor/director:");
String fullName=input.nextLine();
if( personExists( fullName) ){
return returnPerson(fullName);
}else{
return null;
}
}
public ArrayList<Show> searchShowsWithPerson(Person person){
ArrayList<Show> results= new ArrayList<>();
for(Show show:showsList){
if( show.getDirector().getFullName().equalsIgnoreCase( person.getFullName() ) ){
results.add(show);
}else{
for(Person actor:show.getActors()){
if( actor.getFullName().equalsIgnoreCase( person.getFullName() ) ){
results.add(show);
}
}
}
}
return results;
}
public Show getHighestRatedShow(ArrayList<Show> results){
Show highest = null;
double highestRating =0.0;
for (Show show : results) {
double averageRating = show.getAvgRating();
if (averageRating > highestRating) {
highestRating = averageRating;
highest = show;
}
}
return highest;
}
public Show getLowestRatedShow(ArrayList<Show> results){
Show lowest = null;
double lowestRating =10.0;
for (Show show : results) {
double averageRating = show.getAvgRating();
if (averageRating < lowestRating) {
lowestRating = averageRating;
lowest = show;
}
}
return lowest;
}
public User findUser(String email,String password){
for(User u:usersList){
if(u.getEmail().equalsIgnoreCase(email) && u.getPassword().equalsIgnoreCase(password)){
return u;
}
}
return null;
}
public void viewResultRatings(ArrayList<Show> results){
for(Show show:results){
System.out.println("Show " + show.getTitle() + " Ratings:");
for(User user:usersList){
for(Rating rating:user.getUserRatings() ){
if(rating.getShow().getTitle().equalsIgnoreCase( show.getTitle() ) ){
System.out.println("User:"+ user.getUsername() +" Rating:" + rating.getGrade());
}
}
}
}
}
public boolean userExists(String username){
for (User user :usersList ) {
if (user.getUsername().equalsIgnoreCase(username) ) {
return true;
}
}
return false;
}
public boolean personExists(String personName){
for (Person person :personsList ) {
if (person.getFullName().equalsIgnoreCase(personName) ) {
return true;
}
}
return false;
}
public boolean ShowExists(String title){
for (Show show : showsList) {
if (show.getTitle().equalsIgnoreCase(title)) {
return true;
}
else{
try {
int id = Integer.parseInt(title);
if (show.getId() == id) {
return true;
}
} catch (NumberFormatException e) {
}
}
}
return false;
}
public Person returnPerson(String personName){
for (Person p :personsList ) {
if (p.getFullName().equalsIgnoreCase(personName)) {
return p;
}
}
return null;
}
public Show returnShow(String title) {
for (Show s : showsList) {
try {
if (s.getTitle().equalsIgnoreCase(title) || s.getId() == Integer.parseInt(title)) {
return s;
}
} catch (NumberFormatException e) {
}
}
return null;
}
}
| JohnSkouloudis/JavaMovieManagement | src/it2021091/Account.java |
2,548 | package com.example.eshop3;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import java.util.List;
public class QueryFragment extends Fragment {
//δηλωση μεταβλητων που θα χρησιμοποιησω
Spinner spinner;
ArrayAdapter<CharSequence> adapter;
TextView querytextView, querytextresult;
Button B_query_run;
int test;
public QueryFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
//δημιουργια view και αναθεση τιμων σε ενα πινακα τυπου String απο ένα string-array που εχω δηλώσει στο strings.xml
View view = inflater.inflate(R.layout.fragment_query, container, false);
final String[] queryArray = getResources().getStringArray(R.array.queries_description_array);
//αναθεση μεταβλητων με την findViewById
querytextView = view.findViewById(R.id.qeury_txt2);
spinner = view.findViewById(R.id.spinner);
//δημιουργια ενος adapter
adapter = ArrayAdapter.createFromResource(getContext(), R.array.queries_array, R.layout.support_simple_spinner_dropdown_item);
adapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
querytextView.setText(queryArray[position]);
test = position+1;
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
querytextresult =view.findViewById(R.id.query_results_txt);
B_query_run = view.findViewById(R.id.query_button);
B_query_run.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
querytextresult.setText("test" + test);
String result="";
switch (test){
case 1:
//Παιρνω μια λιστα απο ακαιρεους για αυτο και ResultInt integers
//Ετσι με μια αναζητηση και αναλογα το id βρισκω το απόθεμα για κάθε
//προιον ξεχωριστα, το ιδιο ισχυει για case 1,2,3,4
List<ResultInt> integers = MainActivity.myAppDatabase.myDao().getQuery1();
for (ResultInt i: integers) {
Integer p_id = i.getField1();
Integer posotita = i.getField2();
if (p_id == 1){
result = result + "\n Το απόθεμα είναι: " + posotita;
}
}
querytextresult.setText(result);
break;
case 2:
List<ResultInt> integers1 = MainActivity.myAppDatabase.myDao().getQuery1();
for (ResultInt i: integers1) {
Integer p_id = i.getField1();
Integer posotita = i.getField2();
if (p_id == 2){
result = result + "\n Το απόθεμα είναι: " + posotita;
}
}
querytextresult.setText(result);
break;
case 3:
List<ResultInt> integers2 = MainActivity.myAppDatabase.myDao().getQuery1();
for (ResultInt i: integers2) {
Integer p_id = i.getField1();
Integer posotita = i.getField2();
if (p_id == 3){
result = result + "\n Το απόθεμα είναι: " + posotita;
}
}
querytextresult.setText(result);
break;
case 4:
List<ResultInt> integers4 = MainActivity.myAppDatabase.myDao().getQuery1();
for (ResultInt i: integers4) {
Integer p_id = i.getField1();
Integer posotita = i.getField2();
if (p_id==4){
result = result + "\n Το απόθεμα είναι: " + posotita;
}
}
querytextresult.setText(result);
break;
case 5:
//παιρνω μια λιστα τυπου Pwliseis και για καθε αντικειμενο Pwliseis εμφανιζω ολα τις στηλες του
List<Pwliseis> pwliseis = MainActivity.myAppDatabase.myDao().getPwliseis();
for (Pwliseis i: pwliseis){
int id = i.getPpid();
String name = i.getOnoma();
Integer A = i.getPosoA();
Integer B = i.getPosoB();
Integer C = i.getPosoC();
Integer D = i.getPosoD();
result = result + "\n Id:" + id + "\n Όνομα:" + name + "\n Πλήθος προϊόν Α:" + A + "\n Πλήθος προϊόν Β:" + B + "\n Πλήθος προϊόν C:" + C + "\n Πλήθος προϊόν D:" + D;
}
querytextresult.setText(result);
break;
case 6:
//Βρίσκω τον αριθμό κάθε προιοντος που έχει καταχωρηθει σε καθε καταγραφη στον πινακα Πελατες
//και τα προσθέτω. Το ιδιο ισχυει για το το 6,το 7,το 8 και το 9
List<Pwliseis> pwliseis2 = MainActivity.myAppDatabase.myDao().getPwliseis();
int sum = 0;
for (Pwliseis i: pwliseis2) {
sum = sum + i.getPosoA();
}
result = result + "\n Οι συνολικές πωλήσεις είναι " + sum;
querytextresult.setText(result);
break;
case 7:
List<Pwliseis> pwliseis3 = MainActivity.myAppDatabase.myDao().getPwliseis();
int sum1 = 0;
for (Pwliseis i: pwliseis3) {
sum1 = sum1 + i.getPosoB();
}
result = result + "\n Οι συνολικές πωλήσεις είναι " + sum1;
querytextresult.setText(result);
break;
case 8:
List<Pwliseis> pwliseis4 = MainActivity.myAppDatabase.myDao().getPwliseis();
int sum2 = 0;
for (Pwliseis i: pwliseis4) {
sum2 = sum2 + i.getPosoC();
}
result = result + "\n Οι συνολικές πωλήσεις είναι " + sum2;
querytextresult.setText(result);
break;
case 9:
List<Pwliseis> pwliseis5 = MainActivity.myAppDatabase.myDao().getPwliseis();
int sum3 = 0;
for (Pwliseis i: pwliseis5) {
sum3 = sum3 + i.getPosoD();
}
result = result + "\n Οι συνολικές πωλήσεις είναι " + sum3;
querytextresult.setText(result);
break;
case 10:
//παιρνω μια λιστα τυπου Pelates και εμφανιζω ενα ενα ολα τα στοιχεια
List<Pelates> pelates = MainActivity.myAppDatabase.myDao().getPelates();
for (Pelates i: pelates){
int id = i.getId();
String name = i.getName();
String surname = i.getSurname();
String poli = i.getPoli();
result = result + "\n Id:" + id + "\n Όνομα:" + name + "\n Επίθετο: " + surname + "\n Πόλη: " + poli;
}
querytextresult.setText(result);
break;
case 11:
//παιρνω μια λιστα τυπου Proionta και εμφανιζω ενα ενα ολα τα στοιχεια
List<Proionta> proionta = MainActivity.myAppDatabase.myDao().getProionta();
for (Proionta i: proionta){
int id = i.getPid();
Integer posotita = i.getPosotita();
Integer xronologia = i.getXronologia();
Integer timi = i.getTimi();
result = result + "\n Id:" + id + "\n Απόθεμα:" + posotita + "\n Χρονολογία: " + xronologia + "\n Τιμή: " + timi;
}
querytextresult.setText(result);
break;
}
}
});
return view;
}
}
| EfthimisKele/E_Shop | app/src/main/java/com/example/eshop3/QueryFragment.java |
2,552 | public class EqualsNull {
public static void main(String[] args) {
// Δημιουργούμε το πρώτο μωρό
Baby george1 = new Baby("George", true);
// Δημιουργούμε το δεύτερο μωρό
Baby george2 = new Baby("George", true);
Baby george3 = null;
// Συγκρίνουμε τα δυο αντικείμενα
System.out.println(george1.equals(george2));
// Συγκρίνουμε τα δυο αντικείμενα
System.out.println(george1.equals(george3));
// Συγκρίνουμε τα δυο αντικείμενα
System.out.println(java.util.Objects.equals(george3, george1));
System.out.println(java.util.Objects.equals(george1, george3));
System.out.println(george1.equals(george3));
// Αυτό όμως αποτυγχάνει με NullPointerException
System.out.println(george3.equals(george1));
// Τι θα εμφανίσει;
}
}
| riggas-ionio/java | lecture-examples/03-classes-objects-intro/06-equals/EqualsNull.java |
2,555 | package gr.aueb.cf.testbed.ch4;
import java.util.Scanner;
/**
* Ελέγχει αν ένα έτος είναι Δίσεκτο (Leap).
* Δίσεκτο είναι ένα έτος αν διαιρείται
* με το 4 και όχι με το 100.
* Αν όμως διαιρείται με το 100 τότε
* δίσεκτο είναι αν διαιρείται με το
* 400.
*/
public class LeapYearApp {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int year = 0;
boolean isLeapYear = false;
System.out.println("Please insert a year (int)");
year = in.nextInt();
isLeapYear = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
if (year % 4 == 0) {
if (year % 100 != 0) {
isLeapYear = true;
} else if (year % 400 == 0) {
isLeapYear = true;
}
}
}
}
| a8anassis/codingfactory23a | src/gr/aueb/cf/testbed/ch4/LeapYearApp.java |
2,558 | package gr.aueb.cf.ch7String;
/**
* Typecast from String to int.
* If the String is not valid int then
* NumberFormatException is thrown.
*
* H nextInt() του scanner μετατρέπει αυτόματα τα strings σε ints
* • Αν όμως διαβάσουμε κανονικά με .next() τότε για να
* μετατρέψουμε σε int χρησιμοποιούμε την Integer.parseInt()
*/
import java.util.Scanner;
public class TypecastApp {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String lexeme = "";
int num = 0;
System.out.println("insert a string");
lexeme = in.next();
num = Integer.parseInt(lexeme);
System.out.println("Num is: " + num);
}
}
| KruglovaOlga/CodingFactoryJava | src/gr/aueb/cf/ch7String/TypecastApp.java |
2,559 | package rabbitminer.ClusterNode;
import Extasys.ManualResetEvent;
import Extasys.Network.TCP.Client.Exceptions.ConnectorCannotSendPacketException;
import Extasys.Network.TCP.Client.Exceptions.ConnectorDisconnectedException;
import java.net.InetAddress;
import rabbitminer.Cluster.ClusterCommunicationCommons;
import rabbitminer.ClusterNode.Client.ClusterClient;
import rabbitminer.ClusterNode.Miner.Miner;
import rabbitminer.Stratum.StratumJob;
/**
*
* @author Nikos Siatras
*/
public class ClusterNode
{
// Περίληψη:
// Το CLusterNode έχει έναν ClusterClient που μιλάμει με τον Cluster Server,
// έναν Miner που κάνει Mine
// και το Job που έχει στείλει ο Cluster Server
//////////////////////////////////////////////////////////////////////////////////
public static ClusterNode ACTIVE_INSTANCE;
private final ClusterClient fClusterClient;
private final Miner fMyMiner;
private StratumJob fCurrentJob;
private final Object fGetOrSetCurrentJobLock = new Object();
private long fJobReceivedTime;
public double fHashesPerMillisecond = 0;
///////////////////////////////////////////////////
private InetAddress fClusterIP;
private int fClusterPort;
private String fClusterPassword;
private String fStatus = "";
/////////////////////////////////////////
private boolean fKeepAskingForJobs = false;
private Thread fKeepAskingForJobsThread;
private final ManualResetEvent fAskServerForJobAndWaitForReplyEvent = new ManualResetEvent(false);
public ClusterNode(InetAddress clusterIP, int port, String password)
{
fClusterIP = clusterIP;
fClusterPort = port;
fClusterPassword = password;
fClusterClient = new ClusterClient(this);
fMyMiner = new Miner(this);
ACTIVE_INSTANCE = this;
}
public void StartNode() throws Exception
{
fClusterClient.Start();
}
public void StopNode()
{
fClusterClient.Stop();
}
/**
* Ο cluster server μας έστειλε ένα νέο Job. Προσοχή το Job μπορεί να είναι
* NULL!
*
* @param job
*/
public void ClusterSentNewJobToThisNode(StratumJob job)
{
synchronized (fGetOrSetCurrentJobLock)
{
try
{
fCurrentJob = job;
fJobReceivedTime = System.currentTimeMillis();
fAskServerForJobAndWaitForReplyEvent.Set();
if (job == null)
{
fStatus = "No job...";
}
else
{
fStatus = "Job received!";
// Κανε σετ στον Miner για το Job
fMyMiner.SetJob(job);
}
}
catch (Exception ex)
{
fStatus = "ClusterNode.ClusterSentNewJobToThisNode Error:" + ex.getMessage();
}
}
}
/**
* Ξεκίνα να ζητάς Jobs από τον Cluster Server
*/
public void StartAskingForJobs()
{
fKeepAskingForJobs = true;
if (fKeepAskingForJobsThread == null)
{
fKeepAskingForJobsThread = new Thread(() ->
{
while (fKeepAskingForJobs)
{
try
{
Thread.sleep(1000);
}
catch (Exception ex)
{
}
if (fCurrentJob == null)
{
AskServerForJobAndWaitForReply();
}
}
});
fKeepAskingForJobsThread.start();
}
}
private void AskServerForJobAndWaitForReply()
{
fStatus = "Asking cluster for a job...";
fAskServerForJobAndWaitForReplyEvent.Reset();
ManualResetEvent tmpWait = new ManualResetEvent(false);
try
{
tmpWait.WaitOne(100);
}
catch (Exception ex)
{
}
try
{
fAskServerForJobAndWaitForReplyEvent.Reset();
fClusterClient.SendData("GET_JOB" + ClusterCommunicationCommons.fMessageSplitter);
try
{
fAskServerForJobAndWaitForReplyEvent.WaitOne(5000);
}
catch (Exception ex)
{
}
}
catch (ConnectorDisconnectedException | ConnectorCannotSendPacketException ex)
{
fAskServerForJobAndWaitForReplyEvent.Set();
}
// Για να το πιάνει Garbage Collector σύντομα
tmpWait = null;
}
public void CleanJob()
{
synchronized (fGetOrSetCurrentJobLock)
{
fCurrentJob = null;
}
}
public void JobFinished(StratumJob job)
{
synchronized (fGetOrSetCurrentJobLock)
{
// Κάποιο απο τα Thread του Miner σκάναρε όλο το ευρος
// του Nonce που του δώθηκε.
// Για να προχωρήσουμε πρέπει όμως να ολοκληρώσουν το σκανάρισμα όλα τα Threads
fMyMiner.WaitForAllMinerThreadsToFinishWork();
long msPassedSinceJobReceived = (System.currentTimeMillis() - fJobReceivedTime);
fHashesPerMillisecond = (msPassedSinceJobReceived == 0) ? 0 : ((double) (job.getNOnceRangeTo() - job.getNOnceRangeFrom()) / (double) msPassedSinceJobReceived);
ClusterSentNewJobToThisNode(null);
}
}
/**
* Επιστρέφει την τρέχουσα δουλειά που έχει στείλει ο Cluster Server
*
* @return
*/
public StratumJob getCurrentJob()
{
synchronized (fGetOrSetCurrentJobLock)
{
return fCurrentJob;
}
}
public Miner getMyMiner()
{
return fMyMiner;
}
public ClusterClient getClusterClient()
{
return fClusterClient;
}
public InetAddress getClusterIP()
{
return fClusterIP;
}
public void setClusterIP(InetAddress ip)
{
fClusterIP = ip;
}
public int getClusterPort()
{
return fClusterPort;
}
public void setClusterPort(int port)
{
fClusterPort = port;
}
public String getClusterPassword()
{
return fClusterPassword;
}
public void setClusterPassword(String pass)
{
fClusterPassword = pass;
}
public String getStatus()
{
return fStatus;
}
public void setStatus(String status)
{
fStatus = status;
}
public double getHashesPerSecond()
{
return fMyMiner.getHashesPerSecond();
}
}
| SourceRabbit/Rabbit_Miner | RabbitMiner/src/rabbitminer/ClusterNode/ClusterNode.java |
2,568 | package gr.sch.ira.minoas.seam.components.management;
import gr.sch.ira.minoas.model.core.PYSDE;
import gr.sch.ira.minoas.model.core.School;
import gr.sch.ira.minoas.model.employee.Employee;
import gr.sch.ira.minoas.model.employement.Disposal;
import gr.sch.ira.minoas.model.employement.Employment;
import gr.sch.ira.minoas.model.employement.Secondment;
import gr.sch.ira.minoas.model.employement.SecondmentType;
import gr.sch.ira.minoas.model.employement.ServiceAllocation;
import gr.sch.ira.minoas.seam.components.BaseDatabaseAwareSeamComponent;
import gr.sch.ira.minoas.seam.components.home.EmployeeHome;
import gr.sch.ira.minoas.seam.components.home.SecondmentHome;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import org.apache.commons.lang.time.DateUtils;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.RaiseEvent;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.Transactional;
import org.jboss.seam.international.StatusMessage.Severity;
@Name(value = "employeeSecondmentsManagement")
@Scope(ScopeType.CONVERSATION)
public class EmployeeSecondmentsManagement extends BaseDatabaseAwareSeamComponent {
/**
* Comment for <code>serialVersionUID</code>
*/
private static final long serialVersionUID = 1L;
@In(required = true, create=true)
private EmployeeHome employeeHome;
/**
* @return the employeeHome
*/
public EmployeeHome getEmployeeHome() {
return employeeHome;
}
/**
* @param employeeHome the employeeHome to set
*/
public void setEmployeeHome(EmployeeHome employeeHome) {
this.employeeHome = employeeHome;
}
@In(required = true)
private SecondmentHome secondmentHome;
@Transactional
@RaiseEvent("secondmentCreated")
public String addEmployeeSecondmentAction() {
if (employeeHome.isManaged()) {
Employee employee = employeeHome.getInstance();
Employment currentEmployment = employee.getCurrentEmployment();
Secondment newSecondment = secondmentHome.getInstance();
Date established = DateUtils.truncate(newSecondment.getEstablished(), Calendar.DAY_OF_MONTH);
Date dueTo = DateUtils.truncate(newSecondment.getDueTo(), Calendar.DAY_OF_MONTH);
Date today = DateUtils.truncate(new Date(System.currentTimeMillis()), Calendar.DAY_OF_MONTH);
/* get some checking first */
if (!validateSecondment(newSecondment, true)) {
return ACTION_OUTCOME_FAILURE;
}
newSecondment.setSchoolYear(getCoreSearching().getActiveSchoolYear(getEntityManager()));
newSecondment.setActive(secondmentShouldBeActivated(newSecondment, today));
newSecondment.setTargetPYSDE(newSecondment.getTargetUnit().getPysde());
newSecondment.setSourcePYSDE(newSecondment.getSourceUnit().getPysde());
newSecondment.setInsertedBy(getPrincipal());
employee.addSecondment(newSecondment);
/*
* check if the secondment should be set as the employee's current secondment. A
* leave can be set as the employee's current secondment if and only if the
* secondments's period is current (ie, today is after and before leave's
* established and dueTo dates respectively).
*/
if (currentEmployment != null) {
if (today.after(established) && today.before(dueTo)) {
currentEmployment.setSecondment(newSecondment);
}
newSecondment.setAffectedEmployment(currentEmployment);
}
//
// /*
// * if there is a current secondment, disabled it and inform the user
// */
// if (currentSecondment != null) {
// currentSecondment.setActive(Boolean.FALSE);
// currentSecondment.setSupersededBy(newSecondment);
// getEntityManager().merge(currentSecondment);
// facesMessages
// .add(
// Severity.WARN,
// "Για τον εκπαιδευτικό #0 ο Μίνωας είχε καταχωρημένη και άλλη ενεργή απόσπαση στην μονάδα #1 με λήξη την #2, η οποία όμως ακυρώθηκε.",
// (employee.getLastName() + " " + employee
// .getFirstName()), currentSecondment
// .getTargetUnit().getTitle(),
// currentSecondment.getDueTo());
// }
secondmentHome.persist();
getEntityManager().flush();
return ACTION_OUTCOME_SUCCESS;
} else {
facesMessages.add(Severity.ERROR, "employee home #0 not managed.", employeeHome);
return ACTION_OUTCOME_FAILURE;
}
}
public String cancelSecondmentModificationAction() {
if(secondmentHome.isManaged()) {
secondmentHome.revert();
} else {
secondmentHome.clearInstance();
}
return ACTION_OUTCOME_SUCCESS;
}
/* this method is being called from the page containing a list of leaves and returns the CSS class that should be used by the leave row */
public String getTableCellClassForSecondment(Secondment secondment) {
if (secondment.isFuture()) {
return "rich-table-future-secondment";
} else if (secondment.isCurrent()) {
return "rich-table-current-secondment";
} else if (secondment.isPast()) {
return "rich-table-past-secondment";
} else
return "";
}
@Transactional
@RaiseEvent("secondmentDeleted")
public String deleteEmployeeSecondmentAction() {
if (employeeHome.isManaged() && secondmentHome.isManaged()) {
Employee employee = getEntityManager().merge(employeeHome.getInstance());
Secondment secondment = secondmentHome.getInstance();
info("deleting employee #0 secondment #1", employee, secondment);
// for (TeachingHourCDR cdr : leave.getLeaveCDRs()) {
// info("deleting leave's #0 cdr #1", employee, cdr);
// cdr.setLeave(null);
// getEntityManager().remove(cdr);
// }
//
// leave.getLeaveCDRs().removeAll(leave.getLeaveCDRs());
secondment.setActive(Boolean.FALSE);
secondment.setDeleted(Boolean.TRUE);
secondment.setDeletedOn(new Date());
secondment.setDeletedBy(getPrincipal());
secondmentHome.update();
info("secondent #0 for employee #1 has been deleted", secondment, employee);
getEntityManager().flush();
return ACTION_OUTCOME_SUCCESS;
} else {
facesMessages.add(Severity.ERROR, "employee home #0 or secondment home #1 not managed.", employeeHome,
secondmentHome);
return ACTION_OUTCOME_FAILURE;
}
}
protected boolean validateSecondment(Secondment secondment, boolean addMessages) {
DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
Date established = DateUtils.truncate(secondment.getEstablished(), Calendar.DAY_OF_MONTH);
Date dueTo = DateUtils.truncate(secondment.getDueTo(), Calendar.DAY_OF_MONTH);
School currentSchool = null;
try {
currentSchool = secondment.getEmployee().getCurrentEmployment().getSchool();
} catch(Exception ex) {
; // ignore
}
/* check if the secondoment's target unit is the employee's current school */
if(currentSchool!=null && currentSchool.getId().equals(secondment.getTargetUnit().getId())) {
if (addMessages)
facesMessages
.add(Severity.ERROR,
"Η τρέχουσα οργανική του εκπαιδευτικού είναι η ίδια με την μονάδα απόσπασης.");
return false;
}
/* check if the dates are correct */
if (established.after(dueTo)) {
if (addMessages)
facesMessages
.add(Severity.ERROR,
"Η ημερομηνία λήξης της απόσπασης πρέπει να είναι μεταγενέστερη της έναρξης. Κάνε ένα διάλειμα για καφέ !");
return false;
}
/* source & target unit must not be same */
if (secondment.getSourceUnit() != null &&
secondment.getSourceUnit().getId().equals(secondment.getTargetUnit().getId())) {
if (addMessages)
facesMessages
.add(Severity.ERROR,
"Η μονάδα αποσπάσης πρέπει να είναι διαφορετική από την τρέχουσα οργανική του εκπαιδευτικού. Καφέ ήπιες ;");
return false;
}
/* check if the employee has a disposal that conflicts with the new secondment */
Collection<Disposal> conflictingDisposals = getCoreSearching().getEmployeeDisposalWithingPeriod(getEntityManager(), secondment.getEmployee(), established, dueTo);
if(conflictingDisposals.size()>0) {
if (addMessages) {
Disposal d = conflictingDisposals.iterator().next();
String dunit = d.getDisposalUnit().getTitle();
String dfrom = df.format(d.getEstablished());
String dto = df.format(d.getDueTo());
facesMessages
.add(Severity.ERROR,String.format("Η απόσπαση δεν μπορεί να καταχωρηθεί γίατι για τον εκπαιδευτικό υπάρχει ήδη καταχωρημένη διάθεση στην μονάδα '%s' από '%s' εως '%s'.", dunit, dfrom, dto));
facesMessages.add(Severity.INFO,"Εαν η απόσπαση πρέπει να καταχωρηθεί, ακυρώστε πρώτα την διάθεση.");
}
return false;
}
/* check if the employee has a service allocation that conflicts with the new secondment */
Collection<ServiceAllocation> conflictingServiceAllocations = getCoreSearching().getEmployeeServiceAllocationWithinPeriod(getEntityManager(), secondment.getEmployee(), established, dueTo);
if(conflictingServiceAllocations.size()>0) {
if (addMessages) {
ServiceAllocation d = conflictingServiceAllocations.iterator().next();
String dunit = d.getServiceUnit().getTitle();
String dfrom = df.format(d.getEstablished());
String dto = df.format(d.getDueTo());
facesMessages
.add(Severity.ERROR,String.format("Η απόσπαση δεν μπορεί να καταχωρηθεί γίατι για τον εκπαιδευτικό υπάρχει ήδη καταχωρημένη θητεία στην μονάδα '%s' από '%s' εως '%s'.", dunit, dfrom, dto));
facesMessages.add(Severity.INFO,"Εαν η απόσπαση πρέπει να καταχωρηθεί, ακυρώστε πρώτα την θητεία.");
}
return false;
}
Collection<Secondment> current_secondments = getCoreSearching().getAllEmployeeSecondments(
employeeHome.getInstance());
for (Secondment current_secondment : current_secondments) {
if (current_secondment.getId().equals(secondment.getId()))
continue;
Date current_established = DateUtils.truncate(current_secondment.getEstablished(), Calendar.DAY_OF_MONTH);
Date current_dueTo = DateUtils.truncate(current_secondment.getDueTo(), Calendar.DAY_OF_MONTH);
if (DateUtils.isSameDay(established, current_established) || DateUtils.isSameDay(dueTo, current_dueTo)) {
if (addMessages)
facesMessages
.add(Severity.ERROR,
String.format(
"Για τον εκπαιδευτικό υπάρχει ήδη καταχωρημένη απόσπαση από '%s' εώς και '%s' στην μονάδα '%s' η οποία έχει τις ίδιες ημ/νιες με αυτή που προσπαθείτε να εισάγετε.",
df.format(current_secondment.getEstablished()), df.format(current_secondment.getDueTo()),
current_secondment.getTargetUnit().getTitle(),
df.format(secondment.getEstablished()),
df.format(secondment.getDueTo()),
secondment.getTargetUnit().getTitle()));
return false;
}
if (DateUtils.isSameDay(established, current_dueTo)) {
if (addMessages)
facesMessages
.add(Severity.ERROR,
"Η ημ/νία έναρξης της απόσπασης πρέπει να είναι μεταγενέστερη της λήξης της προηγούμενης απόσπασης.");
return false;
}
if ((established.before(current_established) && dueTo.after(current_established)) ||
(established.after(current_established) && dueTo.before(current_dueTo)) ||
(established.before(current_dueTo) && dueTo.after(current_dueTo))) {
if (addMessages)
facesMessages
.add(Severity.ERROR,
String.format(
"Για τον εκπαιδευτικό υπάρχει ήδη καταχωρημένη απόσπαση από '%s' εώς και '%s' στην μονάδα '%s' η οποία έχει επικάλυψη με την απόσπαση από '%s' εως και '%s' στην μονάδα '%s' που προσπαθείτε να εισάγετε.",
df.format(current_secondment.getEstablished()), df.format(current_secondment.getDueTo()),
current_secondment.getTargetUnit().getTitle(),
df.format(secondment.getEstablished()),
df.format(secondment.getDueTo()),
secondment.getTargetUnit().getTitle()));
return false;
}
}
return true;
}
@Transactional
@RaiseEvent("secondmentModified")
public String modifySecondment() {
if (secondmentHome.isManaged()) {
Secondment current_secondment = secondmentHome.getInstance();
Employee employee = employeeHome.getInstance();
Employment employment = current_secondment.getAffectedEmployment();
Date established = DateUtils.truncate(current_secondment.getEstablished(), Calendar.DAY_OF_MONTH);
Date dueTo = DateUtils.truncate(current_secondment.getDueTo(), Calendar.DAY_OF_MONTH);
Date today = DateUtils.truncate(new Date(System.currentTimeMillis()), Calendar.DAY_OF_MONTH);
if (!validateSecondment(current_secondment, true)) {
return ACTION_OUTCOME_FAILURE;
}
/*
* check if the secondment should be set as the employee's current
* leave. A secondment can be set as the employee's current leave if and
* only if the secondment's period is current (ie, today is after and
* before secondment's established and dueTo dates respectively).
*/
if (employment != null) {
if (today.after(established) && today.before(dueTo)) {
employment.setSecondment(current_secondment);
} else {
/*
* if the current secodnment is not the employee's current
* secondment, then check if the leave secondment to be the
* employee's current secodment and if so, remove it.
*/
if (employment.getSecondment() != null &&
employment.getSecondment().getId().equals(current_secondment.getId())) {
employment.setSecondment(null);
}
}
}
current_secondment.setActive(secondmentShouldBeActivated(current_secondment, today));
secondmentHome.update();
info("secondent #0 for employee #1 has been updated", current_secondment, employee);
getEntityManager().flush();
return ACTION_OUTCOME_SUCCESS;
} else {
facesMessages.add(Severity.ERROR, "employee home #0 or secondment home #1 not managed.", employeeHome,
secondmentHome);
return ACTION_OUTCOME_FAILURE;
}
}
/**
* Checks if a secondment should be set active in regards to the reference date.
* @param secondment
* @param referenceDate
* @return
*/
protected boolean secondmentShouldBeActivated(Secondment secondment, Date referenceDate) {
Date established = DateUtils.truncate(secondment.getEstablished(), Calendar.DAY_OF_MONTH);
Date dueTo = DateUtils.truncate(secondment.getDueTo(), Calendar.DAY_OF_MONTH);
Date today = DateUtils.truncate(referenceDate, Calendar.DAY_OF_MONTH);
if ((established.before(today) || established.equals(today)) && (dueTo.after(today) || dueTo.equals(today))) {
return true;
} else
return false;
}
/* this method is called when the user clicks the "add new secondment" */
public void prepareForNewSecondment() {
secondmentHome.clearInstance();
Secondment secondment = secondmentHome.getInstance();
secondment.setSecondmentType(SecondmentType.FULL_TO_SCHOOL);
secondment.setEmployeeRequested(Boolean.TRUE);
secondment.setEstablished(getCoreSearching().getActiveSchoolYear(getEntityManager())
.getTeachingSchoolYearStart());
secondment.setDueTo(getCoreSearching().getActiveSchoolYear(getEntityManager()).getTeachingSchoolYearStop());
secondment.setEmployee(employeeHome.getInstance());
secondment.setSchoolYear(getCoreSearching().getActiveSchoolYear(getEntityManager()));
Employment employment = employeeHome.getInstance().getCurrentEmployment();
if (employment != null) {
secondment.setSourceUnit(employment.getSchool());
secondment.setSourcePYSDE(employment.getSchool().getPysde());
secondment.setMandatoryWorkingHours(employment.getMandatoryWorkingHours());
secondment.setFinalWorkingHours(employment.getFinalWorkingHours());
} else {
/* check if the employee is not an employee of our PYSDE */
Employee employee = employeeHome.getInstance();
if(!employee.getCurrentPYSDE().isLocalPYSDE()) {
PYSDE currentPYSDE = employee.getCurrentPYSDE();
secondment.setSourceUnit(currentPYSDE.getRepresentedByUnit());
secondment.setSourcePYSDE(currentPYSDE);
secondment.setMandatoryWorkingHours(21);
secondment.setFinalWorkingHours(21);
}
}
}
}
| slavikos/minoas | gr.sch.ira.minoas/src/main/java/gr/sch/ira/minoas/seam/components/management/EmployeeSecondmentsManagement.java |
2,569 | /*
* Copyright 2016 IIT , NCSR Demokritos - http://www.iit.demokritos.gr,
* SciFY NPO http://www.scify.org.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package gr.demokritos.iit.recommendationengine;
import gr.demokritos.iit.pserver.ontologies.Client;
import gr.demokritos.iit.recommendationengine.api.RecommendationEngine;
import gr.demokritos.iit.recommendationengine.onologies.FeedObject;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
/**
*
* @author Giotis Panagiotis <[email protected]>
*/
public class RecommendationTest {
public static void main(String[] args) {
String username = "testUser1";
HashMap<String, String> attributes = new HashMap<>();
attributes.put("age", "25");
attributes.put("gender", "male");
HashMap<String, String> info = new HashMap<>();
//crete object
FeedObject fo = new FeedObject("0", "el", true, new Date().getTime());
//crete object 1
FeedObject fo1 = new FeedObject("1", "el", true, new Date().getTime());
ArrayList<String> text = new ArrayList<>();
ArrayList<String> categories = new ArrayList<>();
ArrayList<String> tags = new ArrayList<>();
text.add("Οι αθλητές θα έχουν τη δυνατότητα να χρησιμοποιούν παπούτσια πραγματικά κομμένα και ραμμένα στα μέτρα τους με στόχο τη βελτίωση των επιδόσεων τους");
categories.add("Τεχνολογία");
tags.add("παπούτσια");
tags.add("αθλητές");
fo1.setTexts(text);
fo1.setCategories(categories);
fo1.setTags(tags);
//create object 2
FeedObject fo2 = new FeedObject("2", "el", true, new Date().getTime());
ArrayList<String> text2 = new ArrayList<>();
ArrayList<String> categories2 = new ArrayList<>();
ArrayList<String> tags2 = new ArrayList<>();
text2.add("Ένα αμφιλεγόμενο ερευνητικό πρόγραμμα στην Ελβετία, με απώτερο στόχο την προσομοίωση ενός ανθρώπινου εγκεφάλου στον υπολογιστή, παρουσιάζει τα πρώτα σημαντικά αποτελέσματα: το ψηφιακό μοντέλο μιας περιοχής του εγκεφάλου του αρουραίου σε μέγεθος κόκκου άμμου.\nΌμως αρκετοί νευροεπιστήμονες δεν δείχνουν να πείθονται για τη χρησιμότητα της προσπάθειας.");
categories2.add("Επιστήμη");
tags2.add("έρευνα");
fo2.setTexts(text2);
fo2.setCategories(categories2);
fo2.setTags(tags2);
//create object 2
FeedObject fo3 = new FeedObject("3", "en", true, new Date().getTime());
ArrayList<String> text3 = new ArrayList<>();
ArrayList<String> categories3 = new ArrayList<>();
ArrayList<String> tags3 = new ArrayList<>();
text3.add("North Korean leader Kim Jong Un declared Saturday that his country was ready to stand up to any threat posed by the United States as he spoke at a lavish military parade to mark the 70th anniversary of the North's ruling party and trumpet his third-generation leadership.");
categories3.add("world");
tags3.add("military");
fo3.setTexts(text3);
fo3.setCategories(categories3);
fo3.setTags(tags3);
//----------------------------------------------------------------------
//Crete new client
Client cl = new Client("root", "root");
//Set client auth time
cl.setAuthenticatedTimestamp(new Date().getTime());
RecommendationEngine re = new RecommendationEngine(cl);
//add user
System.out.println(re.addUser(username, attributes, info));
//feed object 1
for (int i = 0; i < 5; i++) {
System.out.println("#" + i + " --> " + re.feed(username, fo1));
}
//feed object 2
for (int i = 0; i < 5; i++) {
System.out.println("#" + i + " --> " + re.feed(username, fo2));
}
//feed object 3
for (int i = 0; i < 5; i++) {
System.out.println("#" + i + " --> " + re.feed(username, fo3));
}
//Get recommendations
ArrayList<FeedObject> recommendationList = new ArrayList<>();
recommendationList.add(fo1);
recommendationList.add(fo2);
recommendationList.add(fo3);
LinkedHashMap<String, Double> recommedations = new LinkedHashMap<>(
re.getRecommendation(username, recommendationList));
//sout responce
for (String cObject : recommedations.keySet()) {
System.out.println("id: " + cObject + " score: " + recommedations.get(cObject));
}
//delete user
System.out.println(re.deleteUser(username));
}
}
| iit-Demokritos/PersonalAIz | RecommendationEngine/src/main/java/gr/demokritos/iit/recommendationengine/RecommendationTest.java |
2,570 | import java.util.Scanner;
/**
* Η κλάση Main είναι η πρώτη που θα εκτελεστεί από τον υπολογιστή.
*
* @author Δημήτριος Παντελεήμων Γιακάτος
* @version 1.0.0
*/
public class Main {
/**
* Η μέθοδο Main δέχεται από το χρήστη τον αριθμό P, το μήκος του μηνύματος που θα δημιουργηθεί, τη πιθανότητα
* σφάλματος και το πλήθος των μηνυμάτων που θα μεταδοθούν. Εκτελεί τη διαδικασία του CRC και εκτυπώνει στην οθόνη
* τα αποτελέσματα των ποσοστών.
* @param args Δεν χρησιμοποιείται στο πρόγραμμα, όμως είναι απαραίτητη για την εκτέλεση του προγράμματος από τον
* υπολογιστή.
*/
public static void main(String[] args) {
/*
* Το πρόγραμμα ζητάει από το χρήστη τα δώσει το τον αριθμό P. Το πρώτο και το τελευταίο ψηφίο του P πρέπει να
* είναι 1. Αν το πρώτο και το τελευταίο ψηφίο δεν είναι 1 τότε το πρόγραμμα ξαναζητάει από το χρήστη να δώσει
* ξανά τον αριθμό P.
* */
Transceiver transceiver = new Transceiver();
Scanner keyboard = new Scanner(System.in);
System.out.println("Give a binary key that the FIRST and the LAST element must be 1:");
String binaryKey = keyboard.next();
boolean isBinary = false;
while (!isBinary) {
if (!binaryKey.matches("^[1][0*1*]*[1]")) {
System.out.println("Wrong type. The key must be binary and the FIRST and the LAST element of the key must be 1. Please give the key again:");
binaryKey = keyboard.next();
} else {
isBinary = true;
}
}
/*
* Το πρόγραμμα ζητάει από το χρήστη τα δώσει το τον αριθμό k, δηλαδή το μήκος του μηνύματος που θέλει να
* δημιουργήσει. Ο αριθμός k πρέπει να είναι μεγαλύτερος ή ίσος από τον μήκος του αριθμού P. Αν δεν είναι τότε
* το πρόγραμμα ζητάει από το χρήστη να ξαναδώσει τον αριθμό k.
* */
System.out.println("Give the size of the data. The size must be positive integer number and equal or longer than the size of binary key:");
long binarySize = keyboard.nextLong();
boolean hasSize = false;
while (!hasSize) {
if (binarySize<binaryKey.length()) {
System.out.println("Wrong type. The size must be positive integer number and equal or longer than the size of binary key. Please give the key again:");
binarySize = keyboard.nextLong();
} else {
hasSize = true;
}
}
transceiver.setSize(binarySize);
/*
* Το πρόγραμμα ζητάει από το χρήστη τα δώσει τον αριθμό E, δηλαδή τη πιθανότητα σφάλματος. Ο αριθμός E
* πρέπει να είναι ανήκει στο διάστημα [0.0, 1.0]. Αν δεν ανήκει τότε το πρόγραμμα ζητάει από το χρήστη να
* ξαναδώσει τον αριθμό Ε.
* */
transceiver.setKey(binaryKey);
BitErrorRate bitErrorRate = new BitErrorRate();
System.out.println("Give the possibility of error:");
double possibilityError = keyboard.nextDouble();
boolean isPossibility = false;
while (!isPossibility) {
if (possibilityError<0.0 || possibilityError>1.0) {
System.out.println("Wrong type. The possibility error must be from 0 to 1 (exp. 0.003). Please give the key again:");
possibilityError = keyboard.nextDouble();
} else {
isPossibility = true;
}
}
bitErrorRate.setPossibility(possibilityError);
/*
* Το πρόγραμμα ζητάει από το χρήστη τα δώσει το πλήθος των μνημάτων που θέλει να δημιουργήσει το πρόγραμμα.
* Αν ο αριθμός είναι αρνητικός τότε το πρόγραμμα ζητάει από το χρήστη να ξαναδώσει το πλήθος των μηνυμάτων.
* */
System.out.println("Give the number of messages you want to send:");
int numberOfMessages = keyboard.nextInt();
boolean hasAnswer = false;
while (!hasAnswer) {
if (numberOfMessages < 0) {
System.out.println("Wrong type. The number of messages must be positive. Please give the key again:");
numberOfMessages = keyboard.nextInt();
} else {
hasAnswer = true;
}
}
/*
* Το πρόγραμμα δημιουργεί τόσα μηνύματα όσο το πλήθος των μηνυμάτων που έχει οριστεί από το χρήστη.
* Για κάθε μήνυμα ακολουθείται η εξής διαδικασία:
* 1) Αρχικά η μέθοδος transceiver.start δημιουργεί τυχαία ένα μήνυμα και αποθηκεύεται στη μεταβλητή data.
* 2) Το μήνυμα που είναι αποθηκευμένο στη μεταβλητή data ορίζεται ως όρισμα στη μέθοδο bitErrorRate.setData
* η οποία περνάει το μήνυμα από ένα κανάλι θορύβου και ανάλογα τη πιθανότητα σφάλματος αλλοιώνει τα bit του.
* 3) Καλείται η μέθοδο receiver.setData όπου δέχεται ως ορίσματα το πιθανό αλλοιωμένο μήνυμα που προέκυψε από
* το κανάλι θορύβου και το αναλλοίωτο μήνυμα που είναι αποθηκευμένο στη μεταβλητή data.
* 4) Καλείται η μέθοδο receiver.start όπου υλοποίει τη διαίρεση του πιθανού αλλοιωμένου μηνύματος με τον
* αριθμό P και το υπόλοιπο καθορίζει αν το σήμα έχει σφάλμα ή όχι.
* */
Receiver receiver = new Receiver();
receiver.setKey(binaryKey);
String data;
for (int i=0; i<numberOfMessages; i++) {
data = transceiver.start();
bitErrorRate.setData(data);
receiver.setData(bitErrorRate.start(), data);
receiver.start();
}
/*
* Εκτυπώνει τα ποσοστά στην οθόνη.
* */
System.out.println("Statistics data:");
System.out.println("Rate of messages with errors on transmission: " + (double) (receiver.getTotalErrorMessages()*100)/numberOfMessages + "%");
System.out.println("Rate of messages with errors detective by CRC: " + (double) (receiver.getErrorMessagesCrc()*100)/numberOfMessages + "%");
System.out.println("Rate of messages with errors that they were not detective by CRC: " + (double) (receiver.getErrorMessageCrcCorrect()*100)/numberOfMessages + "%");
}
}
| dpgiakatos/CRC | src/Main.java |
2,571 | import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
// Θέλω να αποθηκεύσω μια λίστα υπαλλήλων σε ένα δυαδικό αρχείο
Employee e1 = new Employee("John");
Employee e2 = new Employee("Bob");
Employee e3 = new Employee("Mary");
ArrayList<Employee> employees = new ArrayList<>();
employees.add(e1);
employees.add(e2);
employees.add(e3);
File file = new File("Employees.ser"); // Φτιάχνουμε ένα δυαδικό αρχείο
// Θα γράψουμε στο δυαδικό αρχείο, όμως θα μας στείλει exception όπότε μπαίνει σε try/catch
try {
FileOutputStream outputStream = new FileOutputStream(file);
ObjectOutputStream out = new ObjectOutputStream(outputStream);
out.writeObject(employees); // ΕΔΩ ΑΠΟΘΗΚΕΥΟΥΜΕ ΟΛΟΚΛΗΡΗ ΤΗΝ ARRAYLIST
System.out.println("Employees have been serialized");
out.close();
outputStream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| iosifidis/UoM-Applied-Informatics | s3/object_oriented_programming/lectures/BinaryFiles_v3/src/Main.java |
2,577 | /* LanguageTool, a natural language style checker
* Copyright (C) 2013 Daniel Naber (http://www.danielnaber.de)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package org.languagetool.rules.el;
import org.junit.Before;
import org.junit.Test;
import org.languagetool.JLanguageTool;
import org.languagetool.TestTools;
import org.languagetool.language.Greek;
import org.languagetool.rules.RuleMatch;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
public class GreekRedundancyRuleTest {
private GreekRedundancyRule rule;
private JLanguageTool langTool;
@Before
public void setUp() throws IOException {
rule = new GreekRedundancyRule(TestTools.getMessages("el"), new Greek());
langTool = new JLanguageTool(new Greek());
}
// correct sentences
@Test
public void testRule() throws IOException {
assertEquals(0, rule.match(langTool.getAnalyzedSentence("Τώρα μπαίνω στο σπίτι.")).length);
assertEquals(0, rule.match(langTool.getAnalyzedSentence("Απόψε θα βγω.")).length);
}
// test for redundancy within the sentence
@Test
public void testRuleWithinSentence() throws IOException {
RuleMatch[] matches = rule.match(langTool.getAnalyzedSentence("Τώρα μπαίνω μέσα στο σπίτι."));
assertEquals(1, matches.length);
assertEquals("μπαίνω", matches[0].getSuggestedReplacements().get(0));
}
// test for redundancy in the beggining of a sentence.
@Test
public void testRuleBegginingOfSentence() throws IOException {
RuleMatch[] matches = rule.match(langTool.getAnalyzedSentence(
"Απόψε το βράδυ θα βγω."));
assertEquals(1, matches.length);
assertEquals("Απόψε", matches[0].getSuggestedReplacements().get(0));
}
// test for redundancy with multiple suggestions
@Test
public void testRuleMultipleSuggestions() throws IOException {
RuleMatch[] matches = rule.match(langTool.getAnalyzedSentence(
"Το μαγαζί ήταν ωραίο, αλλά όμως δεν πέρασα καλά."));
assertEquals(1, matches.length);
assertEquals("αλλά,όμως", matches[0].getSuggestedReplacements().get(0));
}
} | languagetool-org/languagetool | languagetool-language-modules/el/src/test/java/org/languagetool/rules/el/GreekRedundancyRuleTest.java |
2,578 | package project.snow;
import android.content.Intent;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
/**
* EmployeeLoginActivity Class.
*
* This class is used to control and verify the login process of each employee.
*
* @author thanoskalantzis
*/
public class EmployeeLoginActivity extends AppCompatActivity {
//Class variables.
//url_get_all_employees variable is actually the url which corresponds to the php file for getting all currently registered employees.
private String url_get_all_employees;
//url_get_working_employees variable is actually the url which corresponds to the php file for getting all currently working employees.
private String url_get_working_employees;
//Just some more class variables.
private int afm;
private String password;
private Button employeeLoginButton;
private TextView employeeRegisterButton;
private static JSONObject allRegisteredEmployees;
private static JSONObject currentlyWorkingEmployees;
Toast myToast;
View myToastView;
TextView myToastTextView;
/**
* The following method is essential and necessary due to the fact that EmployeeLoginActivity class extends AppCompatActivity.
*
* @param savedInstanceState
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_employee_login);
//Initialize url_get_all_employees.
url_get_all_employees = getString(R.string.BASE_URL).concat("/connect/getallemployees.php");
//Initialize url_get_working_employees.
url_get_working_employees = getString(R.string.BASE_URL).concat("/connect/getworkingemployees.php");
//Setting the title of the action bar.
ActionBar actionBar = getSupportActionBar();
if(actionBar != null) {
actionBar.setTitle("Είσοδος Εργαζομένου");
}
//Here follows the process of verifying the login process of an employee.
employeeLoginButton = (Button) findViewById(R.id.employeeLoginButton);
employeeLoginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
EditText afmGiven = (EditText) findViewById(R.id.employeeLoginAfmInput);
afm = (int) Integer.parseInt(afmGiven.getText().toString().trim());
EditText passwordGiven = (EditText) findViewById(R.id.employeeLoginPasswordInput);
password = String.valueOf(passwordGiven.getText().toString().trim());
//params is the dynamic array of those parameters which will be used to send data to our online database.
List<NameValuePair> params = new ArrayList<NameValuePair>();
//Using the necessary params to access online database.
params.add(new BasicNameValuePair("DB_SERVER", getString(R.string.DATABASE_SERVER)));
params.add(new BasicNameValuePair("DB_NAME", getString(R.string.DATABASE_NAME)));
params.add(new BasicNameValuePair("DB_USER", getString(R.string.DATABASE_USERNAME)));
params.add(new BasicNameValuePair("DB_PASSWORD", getString(R.string.DATABASE_PASSWORD)));
JSONParser jsonParser1=new JSONParser();
allRegisteredEmployees = jsonParser1.makeHttpRequest(url_get_all_employees, "GET", params);
JSONParser jsonParser2=new JSONParser();
currentlyWorkingEmployees = jsonParser2.makeHttpRequest(url_get_working_employees, "GET", params);
loginValidation();
} catch (Exception e1) {
myToast = Toast.makeText(view.getContext(), "Συμπληρώστε πρώτα σωστά τα κατάλληλα πεδία και προσπαθήστε ξανά", Toast.LENGTH_LONG);
myToastView = myToast.getView();
//Gets the actual oval background of the Toast then sets the colour filter
myToastView.getBackground().setColorFilter(myToastView.getContext().getResources().getColor(R.color.red), PorterDuff.Mode.SRC_IN);
//Gets the TextView from the Toast so it can be editted
myToastTextView = myToastView.findViewById(android.R.id.message);
myToastTextView.setTextColor(myToastView.getContext().getResources().getColor(R.color.white));
myToast.show();
e1.printStackTrace();
}
}
});
//Here follows the button for a new employee registration.
employeeRegisterButton = (TextView) findViewById(R.id.employeeRegisterButton1);
employeeRegisterButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(EmployeeLoginActivity.this, EmployeeRegisterActivity.class);
startActivity(intent);
}
});
}
/**
* The follow method is responsible for verifying or not the login of a particular employee.
*
* @throws Exception
*/
private void loginValidation() throws Exception {
/* Just some variables declarations
* The following variables are later used as control variables inside if statements
*/
boolean employeeExists = false;
boolean employeeIsCurrentlyWorking = false;
//Other variables declarations
int indexOfEmployee = -1;
//Get all registered employees
ArrayList<Integer> allEmployeesAfmList = new ArrayList<Integer>();
ArrayList<String> firstNameList = new ArrayList<String>();
ArrayList<String> lastNameList = new ArrayList<String>();
ArrayList<String> emailList = new ArrayList<String>();
ArrayList<String> passwordList = new ArrayList<String>();
ArrayList<Long> phoneList = new ArrayList<Long>();
/* If there is at least 1 individual registered as an employee to our system, the successFlag1 will be 1.
* successFlag1 will be 0 instead.
*/
int successFlag1 = allRegisteredEmployees.getInt("success");
/* If there is at least 1 employee (that has successfully registered to our system) declared by any business as a working employee then successFlag2 will be 1.
* successFlag2 will be 0 instead.
*/
int successFlag2 = currentlyWorkingEmployees.getInt("success");
/* If there is at least 1 individual registered as an employee to our system, the successFlag1 will be 1.
* successFlag1 will be 0 instead.
*/
if (successFlag1 == 1) {
JSONArray allEmployeesArray = allRegisteredEmployees.getJSONArray("all_employees");
for (int i = 0; i < allEmployeesArray.length(); i++) {
allEmployeesAfmList.add(allEmployeesArray.getJSONObject(i).getInt("afm_employee"));
firstNameList.add(allEmployeesArray.getJSONObject(i).getString("first_name"));
lastNameList.add(allEmployeesArray.getJSONObject(i).getString("last_name"));
emailList.add(allEmployeesArray.getJSONObject(i).getString("email"));
passwordList.add(allEmployeesArray.getJSONObject(i).getString("password"));
phoneList.add(allEmployeesArray.getJSONObject(i).getLong("phone"));
}
for (int j = 0; j < allEmployeesAfmList.size(); j++) {
if ((afm == allEmployeesAfmList.get(j)) && password.equals(passwordList.get(j))) {
indexOfEmployee = j;
employeeExists = true;
break;
}
}
if(employeeExists){
/* If there is at least 1 employee (that has successfully registered to our system) declared by any business as a working employee then successFlag2 will be 1.
* successFlag2 will be 0 instead.
*/
if(successFlag2 == 0){
myToast = Toast.makeText(this, "Έχετε εγγραφεί επιτυχώς στο σύστημα ως εργαζόμενος.\nΌμως, δεν εργάζεστε σε κάποια συνεργαζόμενη επιχείρηση αυτήν την στιγμή*", Toast.LENGTH_LONG);
myToastView = myToast.getView();
//Gets the actual oval background of the Toast then sets the colour filter
myToastView.getBackground().setColorFilter(myToastView.getContext().getResources().getColor(R.color.red), PorterDuff.Mode.SRC_IN);
//Gets the TextView from the Toast so it can be editted
myToastTextView = myToastView.findViewById(android.R.id.message);
myToastTextView.setTextColor(myToastView.getContext().getResources().getColor(R.color.white));
myToast.show();
return;
}else{
JSONArray workingArray = currentlyWorkingEmployees.getJSONArray("working_employees");
//Get all currently working employees
ArrayList<Integer> workingEmployeesAfmList = new ArrayList<Integer>();
ArrayList<Integer> businessesAfmList = new ArrayList<Integer>();
for (int k = 0; k < workingArray.length(); k++) {
workingEmployeesAfmList.add(workingArray.getJSONObject(k).getInt("afm_employee"));
businessesAfmList.add(workingArray.getJSONObject(k).getInt("afm_business"));
}
ArrayList<Integer> businessesWorkingForList = new ArrayList<Integer>();
for(int p=0; p<workingEmployeesAfmList.size(); p++){
if(afm == workingEmployeesAfmList.get(p)){
businessesWorkingForList.add(businessesAfmList.get(p));
employeeIsCurrentlyWorking = true;
}
}
if(employeeIsCurrentlyWorking){
myToast = Toast.makeText(this, "Επιτυχής σύνδεση\n" + firstNameList.get(indexOfEmployee) + " " + lastNameList.get(indexOfEmployee), Toast.LENGTH_SHORT);
myToastView = myToast.getView();
//Gets the actual oval background of the Toast then sets the colour filter
myToastView.getBackground().setColorFilter(myToastView.getContext().getResources().getColor(R.color.lime), PorterDuff.Mode.SRC_IN);
//Gets the TextView from the Toast so it can be editted
myToastTextView = myToastView.findViewById(android.R.id.message);
myToastTextView.setTextColor(myToastView.getContext().getResources().getColor(R.color.black));
myToast.show();
int indexWorkingEmployee = -1;
for(int x=0; x<allEmployeesAfmList.size(); x++){
if(allEmployeesAfmList.get(x) == afm){
indexWorkingEmployee = x;
break;
}
}
Employee employee = new Employee();
employee.setAfmEmployee(allEmployeesAfmList.get(indexWorkingEmployee));
employee.setFirstName(firstNameList.get(indexWorkingEmployee));
employee.setLastName(lastNameList.get(indexWorkingEmployee));
employee.setEmail(emailList.get(indexWorkingEmployee));
employee.setPassword(passwordList.get(indexWorkingEmployee));
employee.setPhone(phoneList.get(indexWorkingEmployee));
Intent intent = new Intent(EmployeeLoginActivity.this, WorkSelectionActivity.class);
intent.putExtra("businessesWorkingForList", businessesWorkingForList);
intent.putExtra("currentEmployee", employee);
intent.putExtra("afm_employee", afm);
startActivity(intent);
finish();
//return;
}else {
myToast = Toast.makeText(this, "Έχετε εγγραφεί επιτυχώς στο σύστημα ως εργαζόμενος.\nΌμως, δεν εργάζεστε σε κάποια συνεργαζόμενη επιχείρηση αυτήν την στιγμή*", Toast.LENGTH_LONG);
myToastView = myToast.getView();
//Gets the actual oval background of the Toast then sets the colour filter
myToastView.getBackground().setColorFilter(myToastView.getContext().getResources().getColor(R.color.red), PorterDuff.Mode.SRC_IN);
//Gets the TextView from the Toast so it can be editted
myToastTextView = myToastView.findViewById(android.R.id.message);
myToastTextView.setTextColor(myToastView.getContext().getResources().getColor(R.color.white));
myToast.show();
return;
}
}
}else{
myToast = Toast.makeText(this, "Λανθασμένα στοιχεία εισόδου.\nΠροσπαθήστε ξανά", Toast.LENGTH_LONG);
myToastView = myToast.getView();
//Gets the actual oval background of the Toast then sets the colour filter
myToastView.getBackground().setColorFilter(myToastView.getContext().getResources().getColor(R.color.red), PorterDuff.Mode.SRC_IN);
//Gets the TextView from the Toast so it can be editted
myToastTextView = myToastView.findViewById(android.R.id.message);
myToastTextView.setTextColor(myToastView.getContext().getResources().getColor(R.color.white));
myToast.show();
}
}else{
myToast = Toast.makeText(this, "Κανένας εγγεγραμμένος εργαζόμενος στο σύστημα αυτή τη στιγμή", Toast.LENGTH_LONG);
myToastView = myToast.getView();
//Gets the actual oval background of the Toast then sets the colour filter
myToastView.getBackground().setColorFilter(myToastView.getContext().getResources().getColor(R.color.red), PorterDuff.Mode.SRC_IN);
//Gets the TextView from the Toast so it can be editted
myToastTextView = myToastView.findViewById(android.R.id.message);
myToastTextView.setTextColor(myToastView.getContext().getResources().getColor(R.color.white));
myToast.show();
}
employeeExists = false;
employeeIsCurrentlyWorking = false;
}
/**
* The commands inside the following method are executed when the back button is pressed.
*/
@Override
public void onBackPressed() {
Intent intent=new Intent(EmployeeLoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
super.onBackPressed();
}
/**
* Whenever the activity is destroyed (finished/closed) then the following method will be called.
*/
@Override
public void onDestroy() {
super.onDestroy();
}
}
| thanoskalantzis/S.now | Android/app/src/main/java/project/snow/EmployeeLoginActivity.java |
2,579 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package gr.demokritos.iit.recommendationengine.api;
import gr.demokritos.iit.pserver.ontologies.Client;
import gr.demokritos.iit.recommendationengine.onologies.FeedObject;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author Giotis Panagiotis <[email protected]>
*/
public class RecommendationEngineTest {
public RecommendationEngineTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
/**
* Test all Recommendation module
*/
@Test
public void testRecommendationEngine() {
boolean expResult = true;
boolean result;
System.out.println("* JUnitTest: RecommenationEngine class");
String username = "testReUser1";
HashMap<String, String> attributes = new HashMap<>();
attributes.put("age", "25");
attributes.put("gender", "male");
HashMap<String, String> info = new HashMap<>();
//crete object
FeedObject fo = new FeedObject("0", "el", true, new Date().getTime());
//crete object 1
FeedObject fo1 = new FeedObject("1", "el", true, new Date().getTime());
ArrayList<String> text = new ArrayList<>();
ArrayList<String> categories = new ArrayList<>();
ArrayList<String> tags = new ArrayList<>();
text.add("Οι αθλητές θα έχουν τη δυνατότητα να χρησιμοποιούν παπούτσια πραγματικά κομμένα και ραμμένα στα μέτρα τους με στόχο τη βελτίωση των επιδόσεων τους");
categories.add("Τεχνολογία");
tags.add("παπούτσια");
tags.add("αθλητές");
fo1.setTexts(text);
fo1.setCategories(categories);
fo1.setTags(tags);
//create object 2
FeedObject fo2 = new FeedObject("2", "el", true, new Date().getTime());
ArrayList<String> text2 = new ArrayList<>();
ArrayList<String> categories2 = new ArrayList<>();
ArrayList<String> tags2 = new ArrayList<>();
text2.add("Ένα αμφιλεγόμενο ερευνητικό πρόγραμμα στην Ελβετία, με απώτερο στόχο την προσομοίωση ενός ανθρώπινου εγκεφάλου στον υπολογιστή, παρουσιάζει τα πρώτα σημαντικά αποτελέσματα: το ψηφιακό μοντέλο μιας περιοχής του εγκεφάλου του αρουραίου σε μέγεθος κόκκου άμμου.\nΌμως αρκετοί νευροεπιστήμονες δεν δείχνουν να πείθονται για τη χρησιμότητα της προσπάθειας.");
categories2.add("Επιστήμη");
tags2.add("έρευνα");
fo2.setTexts(text2);
fo2.setCategories(categories2);
fo2.setTags(tags2);
//create object 2
FeedObject fo3 = new FeedObject("3", "en", true, new Date().getTime());
ArrayList<String> text3 = new ArrayList<>();
ArrayList<String> categories3 = new ArrayList<>();
ArrayList<String> tags3 = new ArrayList<>();
text3.add("North Korean leader Kim Jong Un declared Saturday that his country was ready to stand up to any threat posed by the United States as he spoke at a lavish military parade to mark the 70th anniversary of the North's ruling party and trumpet his third-generation leadership.");
categories3.add("world");
tags3.add("military");
fo3.setTexts(text3);
fo3.setCategories(categories3);
fo3.setTags(tags3);
//----------------------------------------------------------------------
//Crete new client
Client cl = new Client("root", "root");
//Set client auth time
cl.setAuthenticatedTimestamp(new Date().getTime());
RecommendationEngine instance = new RecommendationEngine(cl);
//add user
System.out.println("* JUnitTest: addUser() method");
result = instance.addUser(username, attributes, info);
assertEquals(expResult, result);
System.out.println("* JUnitTest: feed() method");
//feed object 1
for (int i = 0; i < 5; i++) {
result = instance.feed(username, fo1);
assertEquals(expResult, result);
}
//feed object 2
for (int i = 0; i < 5; i++) {
result = instance.feed(username, fo2);
assertEquals(expResult, result);
}
//feed object 3
for (int i = 0; i < 5; i++) {
result = instance.feed(username, fo3);
assertEquals(expResult, result);
}
//Get recommendations
System.out.println("* JUnitTest: getRecommendation() method");
ArrayList<FeedObject> recommendationList = new ArrayList<>();
recommendationList.add(fo1);
recommendationList.add(fo2);
recommendationList.add(fo3);
LinkedHashMap<String, Double> expReResult = new LinkedHashMap<>();
LinkedHashMap<String, Double> recResult = instance.getRecommendation(username,
recommendationList);
expReResult.put("2", 0.676879603269757);
expReResult.put("3", 0.6111415350830072);
expReResult.put("1", 0.4400359866366431);
assertEquals(expReResult, recResult);
//delete user
System.out.println("* JUnitTest: deleteUser() method");
result = instance.deleteUser(username);
assertEquals(expResult, result);
}
}
| iit-Demokritos/PersonalAIz | RecommendationEngine/src/test/java/gr/demokritos/iit/recommendationengine/api/RecommendationEngineTest.java |
2,583 | package gr.aueb.cf.ch4;
import java.util.Scanner;
/**
* Διαβάζει από τον χρήστη ένα αριθμό (ακέραιο),
* ένα σύμβολο πράξης, και ένα ακόμα ακέραιο και
* εκτελεί την πράξη, ανάλογα με το σύμβολο που
* έχει δοθεί: +, -, *, /, %
*/
public class CalculatorApp {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int num1 = 0;
int num2 = 0;
int result = 0;
int choice = 0;
char operator = ' ';
boolean isError = false;
System.out.println("Please insert an int, an operator and a second int");
num1 = in.nextInt();
operator = in.next().charAt(0);
num2 = in.nextInt();
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 != 0) {
result = num1 / num2;
}
break;
case '%':
if (num2 != 0) {
result = num1 % num2;
}
break;
default:
System.out.println("Error in operator");
isError = true;
break;
}
if (!isError)
System.out.printf("%d %c %d = %d", num1, operator, num2, result);
}
}
| a8anassis/cf4 | src/gr/aueb/cf/ch4/CalculatorApp.java |
2,589 | // Genikefsi - Polymorfismos #2
// ergastirio 9
import java.text.DecimalFormat;
public class TestTilefono {
// Έυρεση prefix, 2 (για σταθερό), 6 (για κινητό) τυχαίου αριθμού
// Δέχεται για παραμέτρους: 2 για σταθερό, 6 για κινητό και 0 για οποιοδήποτε μεταξύ των 2 και 6
public static String getRandomTelephoneNumber(int new_prefix) {
byte tmp_prefix;
Long tmp_number;
String tmp_num2str;
if (new_prefix != 0) {
do {
do {
tmp_prefix = (byte)Math.round(Math.random() * 10);
} while (tmp_prefix != new_prefix);
tmp_number = Math.round(Math.random() * 1000000000); // Επιστρέφει 9ψήφιο αριθμό
tmp_num2str = tmp_prefix + tmp_number.toString(); // Προσθέτει το tmp_prefix ώστε να γίνει 10ψήφιος ο αριθμός
} while (tmp_num2str.length() != 10);
}
else {
do {
do {
tmp_prefix = (byte)Math.round(Math.random() * 10);
} while (tmp_prefix != 2 && tmp_prefix != 6);
tmp_number = Math.round(Math.random() * 1000000000); // Επιστρέφει 9ψήφιο αριθμό
tmp_num2str = tmp_prefix + tmp_number.toString(); // Προσθέτει το tmp_prefix ώστε να γίνει 10ψήφιος ο αριθμός
} while (tmp_num2str.length() != 10);
}
return tmp_num2str;
}
public static void main(String[] args) {
// Δήλωση και αρχικοποίηση μεταβλητών
DecimalFormat df = new DecimalFormat(); // Για στρογγυλοποίηση των δεκαδικών ψηφίων του float
df.setMaximumFractionDigits(2); // Για στρογγυλοποίηση των δεκαδικών ψηφίων του float
int n, tmp_secondsOnCall, tmp_numOfRandomCalls;
int arithmosStatheron, arithmosKiniton; // Για τον υπολογισμό των τηλεφώνων
int tmp_thesi, tmp_Stathera = 0, tmp_Kinita = 0;
final float posostoStatheron = 0.6f;
System.out.print("Δώσε τον αριθμό των γραμμών της επιχείρησης: ");
n = UserInput.getInteger();
arithmosStatheron = Math.round(n * posostoStatheron);
arithmosKiniton = n - arithmosStatheron;
System.out.println("***** Σταθερά για υπολογισμό: " + arithmosStatheron + ". Κινητά για υπολογισμό: " + arithmosKiniton + ". *****\n");
// Δήλωση και αρχικοποίηση αντικειμένων
// Αρχικοποίηση πίνακα [n] θέσεων αντικειμένων της υπερκλάσης Tilefono()
Tilefono[] tilefona = new Tilefono[n];
// Εισαγωγή τηλεφώνων σε τυχαίες θέσεις του πίνακα ανάλογα με τα ποσοστά τους - ΑΡΧΗ
System.out.println("***** Υπολογισμός ΣΤΑΘΕΡΩΝ τηλεφώνων. Παρακαλώ περιμένετε *****");
while (tmp_Stathera < arithmosStatheron) {
tmp_thesi = (int) (Math.random() * n); // Εύρεση τυχαίας θέσης του αντικειμένου <Stathero> στον πίνακα
if (tilefona[tmp_thesi] == null) { // Αν το τηλέφωνο στη θέση [tmp_thesi] είναι null σημαίνει ότι η θέση έχει ακόμα το αρχικό ανρκείμενο Tilefono άρα είναι ελεύθερη
Stathero tmpStathero = new Stathero(getRandomTelephoneNumber(2));
tilefona[tmp_thesi] = tmpStathero;
tmp_Stathera++;
}
}
System.out.println("***** ΣΤΑΘΕΡΑ τηλέφωνα, υπολογίστηκαν. Συνεχίζουμε... *****\n");
System.out.println("***** Υπολογισμός ΚΙΝΗΤΩΝ τηλεφώνων. Παρακαλώ περιμένετε *****");
while (tmp_Kinita < arithmosKiniton) {
tmp_thesi = (int)(Math.random() * n); // Εύρεση τυχαίας θέσης του αντικειμένου <Kinito> στον πίνακα
if (tilefona[tmp_thesi] == null) { // Αν το τηλέφωνο στη θέση [tmp_thesi] είναι null σημαίνει ότι η θέση έχει ακόμα το αρχικό ανρκείμενο Tilefono άρα είναι ελεύθερη
Kinito tmpKinito = new Kinito(getRandomTelephoneNumber(6));
tilefona[tmp_thesi] = tmpKinito;
tmp_Kinita++;
}
}
System.out.println("***** ΚΙΝΗΤΑ τηλέφωνα, υπολογίστηκαν. Συνεχίζουμε... *****\n");
System.out.println("***************** Ο ΠΙΝΑΚΑΣ ΓΕΜΙΣΕ *****************");
// Εισαγωγή τηλεφώνων σε τυχαίες θέσεις του πίνακα ανάλογα με τα ποσοστά τους - ΤΕΛΟΣ
// Γέμισμα πίνακα με τυχαίες κλήσεις - ΑΡΧΗ
tmp_numOfRandomCalls = (int)Math.round(Math.random() * 1900) + 100; // Τυχαίος αριθμός κλήσεων από 100 έως 2000
for (int i = 1; i < tmp_numOfRandomCalls; i++) {
tmp_thesi = (int)Math.abs(Math.round(Math.random() * n - 1)); // Τυχαία θέση στον πίνακα τηλεφώνων για εξερχόμενη κλήση της γραμμής
tmp_secondsOnCall = (int)Math.round(Math.random() * 595) + 5; // Τυχαία διάρκεια κλήσης από 5 έως 600 δευτερόλεπτα
System.out.print("Α/Α κλήσης [" + i + "]: ");
tilefona[tmp_thesi].dial(getRandomTelephoneNumber(0), tmp_secondsOnCall);
}
System.out.println("***************** Ο ΠΙΝΑΚΑΣ ΓΕΜΙΣΕ ΜΕ [" + tmp_numOfRandomCalls + "] ΤΥΧΑΙΕΣ ΚΛΗΣΕΙΣ *****************");
// Γέμισμα πίνακα με τυχαίες κλήσεις - ΤΕΛΟΣ
// Εμφάνιση αποτελεσμάτων - ΖΗΤΟΥΜΕΝΑ ΑΣΚΗΣΗΣ
System.out.println("*********************************************************************************");
System.out.println("******************************* ΖΗΤΟΥΜΕΝΑ ΑΣΚΗΣΗΣ *******************************");
// Ζητούμενο άσκησης i.
System.out.println("***** i. Κατάλογος με τον αριθμό και το συνολικό κόστος κάθε τηλεφώνου **********");
for (int i = 0; i < n; i++)
System.out.println("[" + i +"] " + tilefona[i]);
System.out.println("*********************************************************************************");
// Ζητούμενο άσκησης ii.
System.out.println("***** ii. Σύνολο δευτερολέπτων και κόστους κλήσεων των ΣΤΑΘΕΡΩΝ τηλεφώνων *******");
int tmp_callsSecondsFromStahera = 0;
float tmp_callsCostFromStahera = 0.0f;
for (int i = 0; i < n; i++)
if (tilefona[i] instanceof Stathero) {
tmp_callsSecondsFromStahera = tmp_callsSecondsFromStahera + ((Stathero)tilefona[i]).getTotalSecondsOnCallFromLine();
tmp_callsCostFromStahera = tmp_callsCostFromStahera + ((Stathero)tilefona[i]).getTotalCostFromLine();
}
System.out.println(tmp_callsSecondsFromStahera + "sec. / " + df.format(tmp_callsCostFromStahera) + "€.");
System.out.println("*********************************************************************************");
// Ζητούμενο άσκησης iii.
System.out.println("***** iii. Σύνολο δευτερολέπτων και κόστους κλήσεων των ΚΙΝΗΤΩΝ τηλεφώνων *******");
int tmp_callsSecondsFromKinita = 0;
float tmp_callsCostFromKinita = 0.0f;
for (int i = 0; i < n; i++)
if (tilefona[i] instanceof Kinito) {
tmp_callsSecondsFromKinita = tmp_callsSecondsFromKinita + ((Kinito)tilefona[i]).getTotalSecondsOnCallFromLine();
tmp_callsCostFromKinita = tmp_callsCostFromKinita + ((Kinito)tilefona[i]).getTotalCostFromLine();
}
System.out.println(tmp_callsSecondsFromKinita + "sec. / " + df.format(tmp_callsCostFromKinita) + "€.");
System.out.println("*********************************************************************************");
// Ζητούμενο άσκησης iv.
float tmp_sumOfCostToStathera = 0.0f;
System.out.print("***** iv. Συνολικό κόστος κλήσεων προς ΣΤΑΘΕΡΑ: ");
for (int i = 0; i < n; i++)
tmp_sumOfCostToStathera = tmp_sumOfCostToStathera + (tilefona[i].getCallsToStatheroTotalSeconds() * tilefona[i].getCallToStatheroCostPerSecond());
System.out.println(df.format(tmp_sumOfCostToStathera) + "€. *******************");
System.out.println("*********************************************************************************");
// Ζητούμενο άσκησης v.
float tmp_sumOfCostToKinita = 0.0f;
System.out.print("***** v. Συνολικό κόστος κλήσεων προς ΚΙΝΗΤΑ: ");
for (int i = 0; i < n; i++)
tmp_sumOfCostToKinita = tmp_sumOfCostToKinita + (tilefona[i].getCallsToKinitoTotalSeconds() * tilefona[i].getCallToKinitoCostPerSecond());
System.out.println(df.format(tmp_sumOfCostToKinita) + "€. *******************");
System.out.println("*********************************************************************************");
System.out.print("***** vi. Συνολικό κόστος κλήσεων της επιχείρησης: "); // Ζητούμενο άσκησης vi.
float tmp_totalSumOfCost = tmp_sumOfCostToStathera + tmp_sumOfCostToKinita;
System.out.println(df.format(tmp_totalSumOfCost) + "€. *******************");
}
}
| panosale/DIPAE_OOP_2nd_Term-JAVA | Askisis/Ergastirio9(done)/src/TestTilefono.java |
2,592 | package com.example.skinhealthchecker;
/*
Είναι το activity που είναι υπεύθυνο για την εμφάνιση της συλλογής των αποθηκευμένων ελιών και των
δεδομένων τους για τον κάθε χρήστη . Λαμβάνονται απο την βάση όλα τα αποθηκευμένα mole . Προβάλονται
ένα κάθε φορά και ακόμα προβάλεται μια εικόνα κατάστασης - διάγνωσης μαζί με τα χαρακτηριστικά μιας ελιάς.
It is the activity that is responsible for displaying the collection of stored moles
their data for each user. All saved moles are taken from the base. They are being implemented
one at a time, and a status-diagnosis image along with the characteristics of an mole is displayed.
*/
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.io.*;
public class AppGallery extends AppCompatActivity {
List<Mole> mole ; // list of moles
Gallery galleryView; // instance of gallery -> xml
ImageView imgView; //instance of imageview -> xml
int [] ids; // list of mole ids
float initialX; //variable used for scroll function
// private Cursor cursor;
Bitmap value;//variable used to load the mole image
String TAG; // for logging
static final int MIN_DISTANCE = 150; // min scrolling distance for changing image
// static String DATA = new String();
int max=0; //variable which one contains the count of the moles
private boolean langu;//variable used to load correct active language
static InputStream imageStream;//variable used for loading mole images from storage
int curr=0; // //variable used to save current viewing mole id
//images from drawable
DatabaseHandler db; // database handler...
Bitmap [] imageResource; // list of images of moles
TextView textname; //variable used to viewing the mole characteristics
ImageView isok;//variable used to viewing diagnosis image
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
db = new DatabaseHandler(this); //attaching handler with the database
/*
start with detect specify what problems we should look for.
Methods whose names start with penalty specify what we should do when we detect a problem.
For example, detect everything and log anything that's found:
.detectAll()
.penaltyLog()
.build();
*/
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Configurations def = db.getDEf(); // getting the default-last Configurations of the app from database
langu=def.GetLanguage();// getting the language state(gr-en)
if (langu) // display the layout for en or gr . if langu==1 then language = gr
setContentView(R.layout.gallery);
else
setContentView(R.layout.galleryen);
textname = (TextView) findViewById(R.id.propert);// linking the TextView propert
isok = (ImageView) findViewById(R.id.isok);// linking the ImageView isok
// db = new DatabaseHandler(this);
if (GetNewId() < 0) //if nothing is written
db.getWritableDatabase();// seting that handler can write the database
// Configurations def =db.getDEf();
Profile pro =db.getProfile(def.GetPID()); // getting the app active profile
// mole = db.getAllMoles();
mole = db.getAllProfileMoles(pro);// getting the list of the active profile moles
if (mole.size() > 0) { // if there is moles in the list then....
imageResource = new Bitmap[mole.size()];// create a bitmap table with all moles
max = mole.size(); // moles count
ids = new int[mole.size()]; // creating a table of mole ids
int temp = 0;
for (int i = mole.size() - 1; i >= 0; i--) {
imageResource[temp] = Getbitmap(mole.get(i).GetId());// getting the image
ids[i] = temp; //getting the ids of moles order reverse row
temp++;
}
imgView = (ImageView) findViewById(R.id.imageView); //linking the imageview with the xml
galleryView = (Gallery) findViewById(R.id.gallery);//linking the galleryView with the xml
imgView.setImageBitmap(imageResource[0]); //seting the viewing image of last captured mole
galleryView.setAdapter(new myImageAdapter(this)); // This will bind to the Gallery view with a series of ImageView views
movetoid(ids[0]); //display the data of last captured mole
//gallery image onclick event
galleryView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int i, long id) {
curr = i; // when a thumb image is clicked curr will contains the position of the image
movetoid(ids[curr]);//geting the id from position/display the data of the mole which owning the id
// int imagePosition = i + 1;
imgView.setImageBitmap(imageResource[curr]); // displaying the image of the mole which owning the id
// Toast.makeText(getApplicationContext(), "You have selected image = " + imagePosition, Toast.LENGTH_LONG).show();
getWindow().getDecorView().findViewById(R.id.updateframe).invalidate(); // updating the graphics
}
});
}
Button captureButton = (Button) findViewById(R.id.Delete); // if the delete button pressed
captureButton.setFocusable(true);
// captureButton.setFocusableInTouchMode(true);
captureButton.requestFocus();
captureButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//
if (mole.size()>0){
db.deleteMole(mole.get(ids[curr]));// delete the active- viewing mole from database
finish();// restarting the activity
startActivity(getIntent());}
//
}
});
Button ftp = (Button) findViewById(R.id.button); // if the ftp button is pressed
ftp.setFocusable(true);
// captureButton.setFocusableInTouchMode(true);
ftp.requestFocus();
ftp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//
if (mole.size()>0) // if there is moles stored
ftpimage(mole.get(ids[curr])); //send the mole by ftp
//
}
});
Button captureButton1 = (Button) findViewById(R.id.Back12); // if back button pressed
captureButton1.setFocusable(true);
// captureButton.setFocusableInTouchMode(true);
captureButton1.requestFocus();
captureButton1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//
gotostart(); // go to cameraactivity -> first actiivty
//
}
});
}
// create a new ImageView for each item referenced by the Adapter
public class myImageAdapter extends BaseAdapter {
private Context mcontext;
public View getView(int position, View convertView, ViewGroup parent) {
ImageView mgalleryView = new ImageView(mcontext);
// mgalleryView.setImageResource(imageResource[position]);
mgalleryView.setImageBitmap(imageResource[position]);//Sets a Bitmap as the content of this ImageView.
//Gallery extends LayoutParams to provide a place to hold current Transformation information along with previous position/transformation info.
mgalleryView.setLayoutParams(new Gallery.LayoutParams(150, 150));
mgalleryView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);//Controls how the image should be resized or moved to match the size of this ImageView.
//imgView.setImageResource(R.drawable.image_border);
mgalleryView.setPadding(3, 3, 3, 3);//The padding is expressed in pixels for the left, top, right and bottom parts
return mgalleryView;
}
public myImageAdapter(Context c) {
mcontext = c;
}//
public int getCount() { return imageResource.length; } // returning the image list length
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
}
//this fuction returns the last created id of mole
public int GetNewId() {
Configurations def = db.getDEf();
int id = def.GetIdM();
return id;
}
public Bitmap Getbitmap(int id) { // reading the image from the storage giving the id of mole image
// returns the Bitmap of the image
Log.e(TAG, "geting bitmap");
String NOMEDIA=" .nomedia";
// File mediaStorageDir = new File(
// Environment
// .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES +NOMEDIA ),"MyCameraApp");
//geting the apps private path
File mediaStorageDir = new File(this.getExternalFilesDir(Environment.getDataDirectory().getAbsolutePath()).getAbsolutePath());
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) { // but normaly it will be created !!
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
File pictureFile = new File(Geturl(id)); // link the image from storage with pictureFile
// Geturl generating the dir of image using only the id of the image
try {// loads the image from storage and creating the image
imageStream = new FileInputStream(pictureFile);
value = BitmapFactory.decodeStream(imageStream);
value= Bitmap.createBitmap(
value,
0,
0,
value.getWidth()
,
value.getHeight()
);
// Bitmap lastBitmap = null;
//lastBitmap = Bitmap.createScaledBitmap(value, 2000, 2000, true);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return value;
}
// Geturl generating the dir of image using only the id of the image
// input: image id -> output : Directory position
public String Geturl(int id) {
// getting the app private dir
File mediaStorageDir = new File(
this.getExternalFilesDir(Environment.getDataDirectory().getAbsolutePath()).getAbsolutePath());
if (!mediaStorageDir.exists()) {
Log.d("MyCameraApp", "failed to create directory");
return null;
}// generating the image dir by adding the name of image . the image name will dir will be like-> SAVED+IDnum+.nodata
File pictureFile = new File(mediaStorageDir.getPath() + File.separator + "SAVED"+ Integer.toString(id) + ".nodata");
return pictureFile.getPath();}//returning the path
//checking if there is a slide to right or left
//if there is a slide then it moves to previous or next image
@Override
public boolean onTouchEvent(MotionEvent event) { // when the screen is touched
// TODO Auto-generated method stub
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
initialX = event.getX();// getting the first coordinate of touch
break;
case MotionEvent.ACTION_UP:
float finalX = event.getX(); // getting the last coordinate of touch
float deltaX = finalX - initialX; //calculating the distance
if (Math.abs(deltaX) > MIN_DISTANCE) // if the absolute distance is big enough
{
// Left to Right swipe action
if (finalX > initialX) // calculating if the last coordinate is bigger than first
//if so then moving to previous mole
{
if ((curr > 0 )&&(curr <= max-1)) {// checking if position is in limits
imgView.setImageBitmap(imageResource[curr - 1]);
movetoid(ids[curr-1]);
curr = curr - 1; } }
// Right to left swipe action
else
{
if ((curr >= 0 )&&(curr < max-1)) {// checking if position is in limits
//if so then moving to next mole
imgView.setImageBitmap(imageResource[curr
+1]);
movetoid(ids[curr+1]);
curr = curr+ 1;
} }
}
else
{
// consider as something else - a screen tap for example
}
break;
}
return false;
}
private void movetoid(int in) // viewing the information of mole which one id = in
{
// DATA="";
// Configurations def =db.getDEf();
// Profile pro =db.getProfile(def.GetPID());
StringBuilder sb = new StringBuilder();
if (!langu) { //if language is english
sb.append(" Name:\t");
sb.append(mole.get(in).GetName());//getting the name
sb.append(System.getProperty("line.separator"));
// sb.append(" Age:\t");
// sb.append(pro.GetAge());
// sb.append(System.getProperty("line.separator"));
// sb.append(" Gender:\t");
// sb.append(pro.GetSex());
// sb.append(System.getProperty("line.separator"));
sb.append(" Doubtful Perimeter:\t");
sb.append(mole.get(in).BadBorder);//getting the border status
sb.append(System.getProperty("line.separator"));
// sb.append(" Bad history:\t");
// sb.append(pro.GetHistory());
// sb.append(System.getProperty("line.separator"));
sb.append(" Color Normal :\t");
if (mole.get(in).GetColorCurve() < 3)//getting the color status
sb.append(true);
else
sb.append(false);
sb.append(System.getProperty("line.separator"));
sb.append(" Diameter:\t");//getting the mole diameter
sb.append(mole.get(in).GetDiameter() / 10);
sb.append(System.getProperty("line.separator"));
sb.append(" Evolving:\t");
sb.append(mole.get(in).GetEvolving());//getting the evolving status
sb.append(System.getProperty("line.separator"));
sb.append(" Has Asymmetry:\t");
sb.append(mole.get(in).GetHasAsymmetry());//getting the asymmetry status
sb.append(System.getProperty("line.separator"));
sb.append(" Has blood:\t");
sb.append(mole.get(in).GetHasBlood());//getting the blood status
sb.append(System.getProperty("line.separator"));
sb.append("Is Itching:\t");//getting the inch status
sb.append(mole.get(in).GetHasItch());
sb.append(System.getProperty("line.separator"));
sb.append(" It hurts:\t");
sb.append(mole.get(in).GetInPain());//getting the inpain status
sb.append(System.getProperty("line.separator"));
sb.append(" It's Hard:\t");
sb.append(mole.get(in).GetIsHard());//getting the ishard status
sb.append(System.getProperty("line.separator"));
sb.append("Has Uploaded to server:\t");//getting the if the mole has uploaded to server status
// sb.append(mole.get(in).GetIsHard());
sb.append(mole.get(in).GetDLD());
sb.append(System.getProperty("line.separator"));
} else // if the active language is greek
{
sb.append(" Όνομα:\t"); //setting the same information but in greek language
sb.append(mole.get(in).GetName());
sb.append(System.getProperty("line.separator"));
// sb.append(" Ηλικία:\t");
// sb.append(pro.GetAge());
// sb.append(System.getProperty("line.separator"));
// sb.append(" Φύλο:\t");
// sb.append(pro.GetSex());
// sb.append(System.getProperty("line.separator"));
sb.append(" Αμφίβολη Περίμετρος:\t");
if (mole.get(in).BadBorder)
sb.append("Ναι");
else
sb.append("Όχι");
sb.append(System.getProperty("line.separator"));
// sb.append(" Κακό Ιστορικό:\t");
// if (pro.GetHistory())
// sb.append("Ναι");
// else
// sb.append("Όχι");
// sb.append(System.getProperty("line.separator"));
sb.append(" Χρωματικά Φυσιολογικός :\t");
if (mole.get(in).GetColorCurve() < 3)
sb.append("Ναι");
else
sb.append("Όχι");
sb.append(System.getProperty("line.separator"));
sb.append(" Διάμετρος:\t");
sb.append(mole.get(in).GetDiameter() / 10);
sb.append(System.getProperty("line.separator"));
sb.append(" Εξελίσσεται:\t");
// sb.append();
if (mole.get(in).GetEvolving())
sb.append("Ναι");
else
sb.append("Όχι");
sb.append(System.getProperty("line.separator"));
sb.append(" Έχει Ασυμμετρία:\t");
if (mole.get(in).GetHasAsymmetry())
sb.append("Ναι");
else
sb.append("Όχι");
sb.append(System.getProperty("line.separator"));
sb.append(" Έχει Αίμα:\t");
// sb.append(mole.get(in).GetHasBlood());
if (mole.get(in).GetHasBlood())
sb.append("Ναι");
else
sb.append("Όχι");
sb.append(System.getProperty("line.separator"));
sb.append(" Έχει Φαγούρα:\t");
// sb.append(mole.get(in).GetHasItch());
if (mole.get(in).GetHasItch())
sb.append("Ναι");
else
sb.append("Όχι");
sb.append(System.getProperty("line.separator"));
sb.append(" Πονάει:\t");
// sb.append(mole.get(in).GetInPain());
if (mole.get(in).GetInPain())
sb.append("Ναι");
else
sb.append("Όχι");
sb.append(System.getProperty("line.separator"));
sb.append(" Είναι Σκληρός:\t");
// sb.append(mole.get(in).GetIsHard());
if (mole.get(in).GetIsHard())
sb.append("Ναι");
else
sb.append("Όχι");
sb.append(System.getProperty("line.separator"));
sb.append("Έχει ανεβέι στον σερβερ:\t");
// sb.append(mole.get(in).GetIsHard());
if (mole.get(in).GetDLD())
sb.append("Ναι");
else
sb.append("Όχι");
sb.append(System.getProperty("line.separator"));
}
// sb.append(" Όνομα:\t"); sb.append(mole.get(in));
// sb.append(System.getProperty("line.separator"));
Log.d("hard",Boolean.toString(mole.get(in).GetIsbad()));
Log.d("is",String.valueOf(mole.get(in).GetId()));
if (!mole.get(in).GetIsbad())// if the diagnosis is positive then the mole will have one green ν image near the characteristics
isok.setImageResource(R.drawable.n);//else will have X image
else
isok.setImageResource(R.drawable.x);
textname.setText(sb.toString());// setting the text of mole characteristics
getWindow().getDecorView().findViewById(R.id.updateframe).invalidate();//updating graphics
}
// this function is starting the first activity(start screen)
public void gotostart() {
Intent intent = new Intent(getApplicationContext(), CameraActivity.class);
startActivity(intent);
}
@Override
public void onBackPressed() {// if the android back button is pressed
gotostart();
}
@Override
protected void onDestroy() { //if app close deleting all bitmaps from memory
super.onDestroy();
try {
for (int i = 0; i < imageResource.length; i++)
imageResource[i].recycle();
}
catch (NullPointerException e){
}
}
//This function gets input of a mole instance . It sends thw mole data ( image and characteristics )
// first the function creates a file to storage called INFO.nodata
//then connects to the ftp server and sends INFO.data and SAVED.data (image)
public void ftpimage(Mole mole){
FTPClient ftpClient = new FTPClient(); // is the ftp client incant
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss:SS"); //this date format will be used for creating timestamp
Configurations def = db.getDEf();// loading app init configurations
String tempstring =Getinfo(mole); //creates string of mole data
String temp= saveinfo(tempstring,mole.GetId()); // creates INFO.no data file .the returning ver "temp" contains the saved dir
if (mole.GetDLD()){//if the mole rules is not right
if (!langu)// prints to screen message
Toast.makeText(getApplicationContext(), "This mole record has already uploaded!The dermatologist will check the data!", Toast.LENGTH_LONG).show();
else
Toast.makeText(getApplicationContext(), "Τα δεδομένα αυτού του σπίλου έχουν ανεβεί ήδη μια φορά στον Server.Ο δερματολόγος θα τα ελένξει !", Toast.LENGTH_LONG).show();
}
else if (def.GetPID()==0){// cant upload using DEFAuLT profile
if (!langu)
Toast.makeText(getApplicationContext(), "You cant upload a mole record by using DEFAULT profile.Please create or choose another !", Toast.LENGTH_LONG).show();
else
Toast.makeText(getApplicationContext(), "Δεν μπορείτε να ανεβάσετε μια εγγραφή σπίλου χρησιμοποιώντας το προφίλ DEFAULT.Παρακαλώ δημιουργήστε ή επιλέξτε ένα άλλο !", Toast.LENGTH_LONG).show();
}
else {// if mole is edible to uploaded , the app creates ftp connection
try {
ftpClient.connect("aigroup.ceid.upatras.gr", 21); //imports server's url and port
ftpClient.login("aig01", "aig842");//importing server's login data
ftpClient.changeWorkingDirectory("/files/");// set that data will saved to folder "files"
File mediaStorageDir = new File(this.getExternalFilesDir(Environment.getDataDirectory().getAbsolutePath()).getAbsolutePath());
// mediaStorageDir=app private dir
if (!mediaStorageDir.exists())
{
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
// return null;
}
}
Log.d("ftp", ftpClient.getReplyString());
if (ftpClient.getReplyString().contains("250") || ftpClient.getReplyString().contains("230")) {
/// if confection established successfully
ftpClient.setFileType(FTP.BINARY_FILE_TYPE); //FTP.BINARY_FILE_TYPE, is used for file transfer
// BufferedInputStream buffIn = null;
// buffIn = new BufferedInputStream(new FileInputStream(mediaStorageDir.getPath() + File.separator + "SAVED"+ Integer.toString(mole.GetId()) + ".nodata"));
ftpClient.enterLocalPassiveMode(); //Set the current data connection mode to PASSIVE_LOCAL_DATA_CONNECTION_MODE .
// Handler progressHandler=null;
// ProgressInputStream progressInput = new ProgressInputStream(buffIn, progressHandler);
Log.d("ftp", mediaStorageDir.getPath() + File.separator + "SAVED" + Integer.toString(mole.GetId()) + ".nodata");
// sending the image
FileInputStream srcFileStream = new FileInputStream(mediaStorageDir.getPath() + File.separator + "SAVED" + Integer.toString(mole.GetId()) + ".nodata");
// the name of sending file includes timestamp on server side
boolean result = ftpClient.storeFile("SAVED" + dateFormat.format(new Date()) + Integer.toString(mole.GetId()), srcFileStream);
// sending the INFO
FileInputStream srcFileStream2 = new FileInputStream(temp);
// the name of sending file includes timestamp on server side
boolean result2 = ftpClient.storeFile("INFO" + dateFormat.format(new Date()) + Integer.toString(mole.GetId()), srcFileStream2);
Log.d("ftp", Integer.toString(ftpClient.getReplyCode()));
// buffIn.close();
ftpClient.logout();///closes connections
ftpClient.disconnect();
if (result && result2) { // prints message to user about the conclusion of ftp transfer
if (!langu)
Toast.makeText(getApplicationContext(), "Upload successful !The dermatologist will check the data!", Toast.LENGTH_LONG).show();
else
Toast.makeText(getApplicationContext(), "Τα δεδομένα στάλθηκαν στον δερματολόγο !", Toast.LENGTH_LONG).show();
mole.SetDLD(true);
// mole.SetIsHard(true);
db.updateMole(mole);// updating the data base that correct mole has uploaded ones
// Mole test = db.getMole(mole.GetId());
// Toast.makeText(getApplicationContext(), Boolean.toString(test.GetDLD()), Toast.LENGTH_LONG).show();
// Toast.makeText(getApplicationContext(), Boolean.toString(test.GetIsHard()), Toast.LENGTH_LONG).show();
}
}
} catch (SocketException e) {
Log.e(" FTP", e.getStackTrace().toString());
} catch (UnknownHostException e) {
Log.e(" FTP", e.getStackTrace().toString());
} catch (IOException e) {
Log.e("FTP", e.getStackTrace().toString());
System.out.println("IO Exception!");
}
}
}
public static final int MEDIA_TYPE_IMAGE = 1;
// the saveinfo function gets input of mole's info and mole's id number and creates INFO.nodata file
//which saves to app storage dir
public String saveinfo(String data ,int id) {
PrintWriter writer=null;
// Log.d("ftp",data);
File file = getOutputMediaFile(MEDIA_TYPE_IMAGE,id); //creating the file in app's directory
NullPointerException e = null;
if (file == null) {
Log.d(TAG,
"Error creating media file, check storage permissions: "
+ e.getMessage());
return null;
}
try {
// FileOutputStream fos = new FileOutputStream(file);
writer = new PrintWriter(file ); //writing data
writer.print(data);
writer.flush();
writer.close();
// fos.write(data.getBytes());
// fos.flush();
// fos.close();
} catch (FileNotFoundException e1) {
Log.d(TAG, "File not found: " + e1.getMessage());
} catch (IOException e1) {
Log.d(TAG, "Error accessing file: " + e1.getMessage());
}
return file.getAbsolutePath();
}
// The getOutputMediaFile function returns the app private dir
public File getOutputMediaFile(int type,int id) {
String NOMEDIA=" .nomedia";
File mediaStorageDir = new File(this.getExternalFilesDir(Environment.getDataDirectory().getAbsolutePath()).getAbsolutePath());
if(!mediaStorageDir.exists())
{
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
// String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new
// Date());
File pictureFile = new File(mediaStorageDir.getPath() + File.separator + "INFO" + ".nodata");
return pictureFile;
}
// The Getinfo function get's input of a mole instance and returns a string containing mole's and active profile's info
private String Getinfo (Mole mole) {
Profile prof1 ;
Configurations def1 =db.getDEf();
prof1= db.getProfile(def1.GetPID());
StringBuilder sb = new StringBuilder();//generating string
sb.append(" Όνομα - Επωνυμο :\t");
sb.append(prof1.GetName());
sb.append(System.getProperty("line.separator"));
sb.append(" Mail :\t");
sb.append(prof1.GetMail());
sb.append(System.getProperty("line.separator"));
sb.append(" Αρ.Τηλεφώνου:\t");
sb.append(prof1.GetPhone());
sb.append(System.getProperty("line.separator"));
sb.append(" Ηλικία:\t");
sb.append(prof1.GetAge());
sb.append(System.getProperty("line.separator"));
sb.append(" Ψευδώνυμο Σπίλου:\t");
sb.append(mole.GetName());
sb.append(System.getProperty("line.separator"));
sb.append(" Φύλο:\t");
sb.append(prof1.GetSex());
sb.append(System.getProperty("line.separator"));
sb.append(" Αμφίβολη Περίμετρος:\t");
if (mole.BadBorder)
sb.append("Ναι");
else
sb.append("Όχι");
sb.append(System.getProperty("line.separator"));
sb.append(" Κακό Ιστορικό:\t");
sb.append(System.getProperty("line.separator"));
if (prof1.GetHistory())
sb.append("Ναι");
else
sb.append("Όχι");
sb.append(System.getProperty("line.separator"));
sb.append("Χρωματικά Φυσιολογικός :\t");
if (mole.GetColorCurve() < 3)
sb.append("Ναι");
else
sb.append("Όχι");
sb.append(System.getProperty("line.separator"));
sb.append(" Διάμετρος:\t");
sb.append(mole.GetDiameter() / 10);
sb.append(System.getProperty("line.separator"));
sb.append(" Εξελίσσεται:\t");
// sb.append();
if (mole.GetEvolving())
sb.append("Ναι");
else
sb.append("Όχι");
sb.append(System.getProperty("line.separator"));
sb.append(" Έχει Ασυμμετρία:\t");
if (mole.GetHasAsymmetry())
sb.append("Ναι");
else
sb.append("Όχι");
sb.append(System.getProperty("line.separator"));
sb.append(" Έχει Αίμα:\t");
// sb.append(mole.get(in).GetHasBlood());
if (mole.GetHasBlood())
sb.append("Ναι");
else
sb.append("Όχι");
sb.append(System.getProperty("line.separator"));
sb.append(" Έχει Φαγούρα:\t");
// sb.append(mole.get(in).GetHasItch());
if (mole.GetHasItch())
sb.append("Ναι");
else
sb.append("Όχι");
sb.append(System.getProperty("line.separator"));
sb.append(" Πονάει:\t");
// sb.append(mole.get(in).GetInPain());
if (mole.GetInPain())
sb.append("Ναι");
else
sb.append("Όχι");
sb.append(System.getProperty("line.separator"));
sb.append(" Είναι Σκληρός:\t");
// sb.append(mole.get(in).GetIsHard());
if (mole.GetIsHard())
sb.append("Ναι");
else
sb.append("Όχι");
sb.append(System.getProperty("line.separator"));
return sb.toString();
}
} | litsakis/SkinHealthChecker | skinHealthChecker/src/main/java/com/example/skinhealthchecker/AppGallery.java |
2,596 | /*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/GUIForms/JFrame.java to edit this template
*/
package apartease;
import java.sql.ResultSetMetaData;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.*;
/**
*
* @author Θεοδόσης
*/
public class UtilityBills extends javax.swing.JFrame implements DBConnection{
/**
* Creates new form UtilityBills
*/
public UtilityBills() {
initComponents();
try
{
Statement stmt = connectdata();
ResultSet rs = stmt.executeQuery("select user_id from login_status where id=1");
rs.next();
int user_id = Integer.valueOf(rs.getString(1));
rs = stmt.executeQuery("select utility_bills_apartment.apartment_amount, utility_bills_apartment.paid from utility_bills_apartment, apartment, user_has_apartment, utility_bills_building where '"+user_id+"'=user_has_apartment.user_id AND user_has_apartment.apartment_id=apartment.id AND apartment.id=utility_bills_apartment.apartment_id AND utility_bills_apartment.utility_bills_building_id=utility_bills_building.id AND month(curdate())=month(utility_bills_building.publish_date) ");
rs.next();
String utility_bills=rs.getString(1);
String paid=rs.getString(2);
jLabel1.setText("Τα κοινόχρηστα για τον τρέχον μήνα είναι:");
jLabel2.setText(utility_bills);
if ("true".equals(paid)){
jLabel4.setText("Πληρωμένα");
}else{
jLabel4.setText("Απλήρωτα");
}
rs = stmt.executeQuery("select wallet from user where '"+user_id+"'=id");
rs.next();
String wallet = rs.getString(1);
jLabel6.setText(wallet);
} catch(Exception e) {
JOptionPane.showMessageDialog(this,"Δεν υπάρχουν ακόμα κοινόχρηστα για τον τρέχον μήνα.");
this.dispose();
HomePage ob = new HomePage();
ob.setVisible(true);
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel2 = new javax.swing.JPanel();
jButton7 = new javax.swing.JButton();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jButton8 = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel2.setBackground(new java.awt.Color(204, 204, 204));
jButton7.setText("Αποσύνδεση");
jButton7.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton7ActionPerformed(evt);
}
});
jLabel5.setText("Διαθέσιμο υπόλοιπο χρήστη:");
jLabel6.setText(".");
jButton8.setText("Πίσω");
jButton8.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton8ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(14, 14, 14)
.addComponent(jLabel5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 22, Short.MAX_VALUE)
.addComponent(jButton8, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton7, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(14, 14, 14)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton7, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel5)
.addComponent(jLabel6)
.addComponent(jButton8, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jLabel1.setText(".");
jLabel2.setText(".");
jLabel3.setText("Κατάσταση:");
jLabel4.setText(".");
jButton1.setText("Πληρωμή");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
payUtilityBillsButton(evt);
}
});
jButton2.setText("Αναλυτικά");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
utilityBillsAnalysisButton(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addGap(16, 16, 16)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(123, 123, 123)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 219, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(46, 46, 46)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jLabel2))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(jLabel4))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jButton2))
.addGap(0, 154, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed
try
{
Statement stmt = connectdata();
stmt.execute("delete from LOGIN_STATUS where id = 1");
}
catch(Exception e)
{
JOptionPane.showMessageDialog(this,e);
}
this.dispose();
Welcome_Page ob = new Welcome_Page();
ob.setVisible(true);
}//GEN-LAST:event_jButton7ActionPerformed
private void payUtilityBillsButton(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_payUtilityBillsButton
try
{
Connection con=DBConnection.getConnection();
Statement st=con.createStatement();
Statement stmt = connectdata();
ResultSet rs = stmt.executeQuery("select user_id from login_status where id=1");
rs.next();
int user_id = Integer.valueOf(rs.getString(1));
rs = stmt.executeQuery("select utility_bills_apartment.apartment_amount, utility_bills_apartment.paid, utility_bills_apartment.id from utility_bills_apartment, apartment, user_has_apartment, utility_bills_building where '"+user_id+"'=user_has_apartment.user_id AND user_has_apartment.apartment_id=apartment.id AND apartment.id=utility_bills_apartment.apartment_id AND utility_bills_apartment.utility_bills_building_id=utility_bills_building.id AND month(curdate())=month(utility_bills_building.publish_date) ");
rs.next();
int utility_bills=Integer.valueOf(rs.getString(1));
String paid=rs.getString(2);
int bills_id = Integer.valueOf(rs.getString(3));
if (paid.equals("true")){
JOptionPane.showMessageDialog(this,"Έχετε πληρώσει ήδη τα κοινόχρηστα για αυτόν τον μήνα.");
} else{
rs = stmt.executeQuery("select wallet from user where '"+user_id+"'=id");
rs.next();
int wallet = Integer.valueOf(rs.getString(1));
if (wallet<utility_bills){
JOptionPane.showMessageDialog(this,"Δεν έχετε διαθέσιμο υπόλοιπο για να πραγματοποιήσετε αυτή την συναλλαγή.");
} else{
int result = JOptionPane.showConfirmDialog(this, "Θέλετε να πληρώσετε τα κοινόχρηστα για τον τρέχον μήνα;");
if (result == 0){
int new_wallet=wallet-utility_bills;
stmt.execute("UPDATE utility_bills_apartment SET paid = 'true' WHERE id='"+bills_id+"'");
stmt.execute("UPDATE user SET wallet = '"+new_wallet+"' WHERE id='"+user_id+"'");
JOptionPane.showMessageDialog(this,"Επιτυχής Πληρωμή Κοινοχρήστων.");
this.dispose();
UtilityBills ob = new UtilityBills();
ob.setVisible(true);
}
else if (result == 1){
JOptionPane.showMessageDialog(this,"Canceled");
}
else{
JOptionPane.showMessageDialog(this,"Canceled");
}
}
}
} catch(Exception e) {
JOptionPane.showMessageDialog(this,e);
}
}//GEN-LAST:event_payUtilityBillsButton
private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton8ActionPerformed
this.dispose();
HomePage ob = new HomePage();
ob.setVisible(true);
}//GEN-LAST:event_jButton8ActionPerformed
private void utilityBillsAnalysisButton(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_utilityBillsAnalysisButton
this.dispose();
UtilityBillsRev ob = new UtilityBillsRev();
ob.setVisible(true);
}//GEN-LAST:event_utilityBillsAnalysisButton
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(UtilityBills.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(UtilityBills.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(UtilityBills.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(UtilityBills.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new UtilityBills().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton7;
private javax.swing.JButton jButton8;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JPanel jPanel2;
// End of variables declaration//GEN-END:variables
}
| ChrisLoukas007/ApartEase | ApartEase/src/apartease/UtilityBills.java |
2,598 | public class HashTable {
int[] array;
int size;
int nItems; //(3 μον) οι μεταβλητές
public HashTable() { // Κάνουμε πάντα κενό constructor ακόμα και αν δε ζητείται! (1 μον)
array = new int[0];
size = 0;
nItems = 0;
}
public HashTable(int n) { // (1 μον)
array = new int[n];
size = n;
nItems = 0;
}
public int size() { // (1 μον)
return size;
}
public int numOfItems() { // Θα μπορούσαμε να μην έχουμε μεταβητή nItems. (3 μον)
return nItems;
}
public boolean isEmpty() { // παλι θα μπορουσα να μην εχω nItems (3 μον)
return nItems == 0;
}
public float tableFullness() { // (3 μον)
return 100 * (float)nItems / (float)size;
}
public void hash(int k, int m) { // Το m είναι τυχαίο
if (k <= 0 || m <= 0) {
System.out.println("Λάθος Είσοδος");
return; // Invalid arguments
}
int index = k % m;
while( array[index] != 0 ) {
index = (index+1) % size; // Προσοχή στην υπερχείλιση
}
array[index] = k;
nItems++;
if (tableFullness() > 75) {
int newSize = 2 * size;
int[] newArray = new int[newSize];
for (int i = 0; i < size; i++ ) {
newArray[i] = array[i];
}
array = newArray;
size = 2 * size;
}
}
}
| bugos/algo | AUTh Courses/Data Structures (Java)/Epanaliptiko Ergastirio/HashTable/src/HashTable.java |
2,601 | package com.ndn.itsapptoyou.activity;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.constraint.ConstraintLayout;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.GestureDetectorCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.ndn.itsapptoyou.CustomGestureListener;
import com.ndn.itsapptoyou.R;
import com.ndn.itsapptoyou.SoundPlayer;
import com.ndn.itsapptoyou.model.Gift;
import com.ndn.itsapptoyou.model.GiftLab;
import com.ndn.itsapptoyou.view.Wheel;
public class PlayActivity extends AppCompatActivity {
public static final String EXTRA_GIFT_INDEX = "key_gift_index";
public static final int DEFAULT_TRIES = 5;
private static final String FILENAME = "gifts.json";
private ConstraintLayout layout;
private Wheel wheel;
private TextView triesText;
private Button spinButton;
private ImageButton backButton;
private RelativeLayout tutorialDialog;
private int triesLeft;
private int giftIndex;
private Animation scaleAnimation;
private GestureDetectorCompat gestureDetector;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play);
scaleAnimation = AnimationUtils.loadAnimation(this, R.anim.bounce);
LinearInterpolator interpolator = new LinearInterpolator();
scaleAnimation.setDuration(400);
scaleAnimation.setInterpolator(interpolator);
loadTriesLeft();
initUI();
}
private void loadTriesLeft() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
triesLeft = prefs.getInt(getString(R.string.key_tries), DEFAULT_TRIES);
}
@SuppressLint("ClickableViewAccessibility")
private void initUI() {
tutorialDialog = findViewById(R.id.rl_tutorial);
tutorialDialog.startAnimation(scaleAnimation);
layout = findViewById(R.id.layout);
layout.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
hideTutorial();
return true;
}
});
wheel = findViewById(R.id.wheelView);
initGestureDetector();
wheel.setGestureDetector(gestureDetector);
wheel.setSpinListener(new Wheel.SpinListener() {
@Override
public void onSpinStart(float finalDegrees) {
SoundPlayer.get(PlayActivity.this)
.playWheelSound();
giftIndex = validateWinner(finalDegrees);
}
@Override
public void onSpinEnd(float degrees) {
spinButton.setEnabled(true);
if (lost(degrees)) {
SoundPlayer.get(PlayActivity.this)
.playLosingSound();
} else {
SoundPlayer.get(PlayActivity.this)
.playWinningSound();
showWinningScreen(giftIndex);
}
}
});
spinButton = findViewById(R.id.btn_spin);
spinButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onSpinClick();
}
});
triesText = findViewById(R.id.tv_tries);
updateTriesText(triesLeft);
backButton = findViewById(R.id.btn_back);
backButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onBackPressed();
}
});
}
private void initGestureDetector() {
gestureDetector = new GestureDetectorCompat(this, new CustomGestureListener(wheel) {
@Override
public boolean onSwipeRight() {
hideTutorial();
if (triesLeft == 0) {
showNoTriesLeftSnack();
return true;
}
//Do not let user spin while the wheel is moving.
spinButton.setEnabled(false);
triesLeft--;
updateTriesText(triesLeft);
wheel.spinRight();
return true;
}
@Override
public boolean onSwipeLeft() {
hideTutorial();
if (triesLeft == 0) {
showNoTriesLeftSnack();
return true;
}
//Do not let user spin while the wheel is moving.
spinButton.setEnabled(false);
triesLeft--;
updateTriesText(triesLeft);
wheel.spinLeft();
return true;
}
@Override
public boolean onTouch() {
hideTutorial();
return true;
}
});
}
private boolean lost(float finalDegrees) {
return ((finalDegrees % 360) / 30) % 3 == 0;
}
private void showWinningScreen(int giftIndex) {
Intent intent = new Intent(this, WinActivity.class);
intent.putExtra(EXTRA_GIFT_INDEX, giftIndex);
startActivity(intent);
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
}
private int validateWinner(float finalDegrees) {
int index = (12 - (int) ((finalDegrees % 360) / 30)) % 12;
if (lost(finalDegrees)) return 0;
GiftLab lab = GiftLab.get(this);
Gift gift = lab.getGiftsOfWheelArray()[index];
lab.addGift(gift);
return index;
}
private void onSpinClick() {
hideTutorial();
if (triesLeft == 0) {
showNoTriesLeftSnack();
return;
}
//Do not let user spin while the wheel is moving.
spinButton.setEnabled(false);
triesLeft--;
updateTriesText(triesLeft);
wheel.spinRight();
}
private void showNoTriesLeftSnack() {
Snackbar snackbar =
Snackbar.make(layout, R.string.toast_no_tries_left, Snackbar.LENGTH_LONG);
snackbar.getView().setBackgroundColor(ContextCompat.getColor(this, R.color.snack));
snackbar.show();
}
@Override
protected void onPause() {
super.onPause();
GiftLab.get(this).saveGifts();
SharedPreferences.Editor editor = PreferenceManager
.getDefaultSharedPreferences(this).edit();
if (triesLeft == 0) {
editor.putInt(getString(R.string.key_tries), DEFAULT_TRIES);
} else {
editor.putInt(getString(R.string.key_tries), triesLeft);
}
editor.apply();
}
private void updateTriesText(int triesLeft) {
if (triesLeft == 1) {
triesText.setText(Html.fromHtml("Έχεις ακόμα <b>1</b> προσπάθεια"));
} else {
triesText.setText(Html.fromHtml(getString(R.string.play_tries_left, String.valueOf(triesLeft))));
}
}
private void hideTutorial() {
if (tutorialDialog.getVisibility() == View.VISIBLE) {
tutorialDialog.setVisibility(View.GONE);
}
}
@Override
public void onBackPressed() {
super.onBackPressed();
SoundPlayer.get(this).pause();
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
}
}
| nrallakis/ItsAppToYou | app/src/main/java/com/ndn/itsapptoyou/activity/PlayActivity.java |
Subsets and Splits