I'm new to java and we were ask to make a program that will create multiple Jtextfields based on the size of my array, i tried this code but nothing displays in the JOption window
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
public class try3 {
public static void main(String[] args) throws IOException{
String maindish = "Main.txt";
String mainprice = "mainprice.txt";
FileReader menu1 = new FileReader(maindish);BufferedReader Menu1 = new BufferedReader(menu1);
FileReader price1 = new FileReader(mainprice);BufferedReader Price1 = new BufferedReader(price1);
String menu = null;
ArrayList MENU = new ArrayList();
for (int a = 0; (menu = Menu1.readLine()) != null; a++ )
MENU.add(menu);
Object[] arr = new Object[MENU.size()];
MENU.toArray(arr);
int control = arr.length;
JLabel[] label = new JLabel[arr.length];
JTextField[] text = new JTextField[arr.length];
JPanel panel = new JPanel(new BorderLayout());
for (int a = 0; a >= control; a++){
label[a] = new JLabel(arr[a].toString());
text[a] = new JTextField("Quantity");
panel.add(label[a],BorderLayout.WEST);
panel.add(text[a],BorderLayout.CENTER);}
JOptionPane.showConfirmDialog(null, panel, "Login", JOptionPane.OK_CANCEL_OPTION,JOptionPane.PLAIN_MESSAGE);
}
}
Related
I have trouble with my Java application. I'm writing a program that connects to public transport API and perform some operations, which includes showing map of Warsaw with bus stops. I want to add an EventHandler function that allows to tap on a bus stop on the map, which will result in showing a box with some informations about this bus stop. How can I do such a thing?
My application so far:
Main.java:
package gui;
import api.Api;
import com.gluonhq.charm.down.ServiceFactory;
import com.gluonhq.charm.down.Services;
import com.gluonhq.charm.down.plugins.StorageService;
import com.gluonhq.maps.MapPoint;
import com.gluonhq.maps.MapView;
import com.gluonhq.maps.demo.PoiLayer;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
import java.io.File;
import java.util.*;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import javax.swing.*;
public class Main extends Application{
private ContentType currentContent = ContentType.SCHEDULE;
private HashMap<ContentType, Pane> contentPaneMap;
private HBox buttonBox;
private Stage stage;
private Theme theme;
private final int height = 500;
private final int width = 800;
private final ToggleGroup menuButtonToggle = new ToggleGroup();
private String selectedStopId;
#Override
public void start(Stage primaryStage) {
this.stage = primaryStage;
theme = Theme.DARK;
buttonBox = new HBox();
buttonBox.getChildren().addAll(getMenuButtons());
initContentPanes();
getContentPaneAndResetStage();
primaryStage.show();
}
private void getContentPaneAndResetStage(){
Pane contentPane = contentPaneMap.get(currentContent);
VBox rootPane = new VBox();
rootPane.getChildren().addAll(buttonBox, contentPane);
Scene scene = new Scene(rootPane, width, height);
scene.getStylesheets().add(theme.cssFile);
stage.setScene(scene);
}
private List<ToggleButton> getMenuButtons(){
List<ToggleButton> buttonList = new ArrayList<>();
for(ContentType contentType:ContentType.values()){
ToggleButton button = new ToggleButton(contentType.buttonText);
button.setPrefWidth((double) width/4);
button.setOnAction(e -> {
Main.this.currentContent = contentType;
getContentPaneAndResetStage();
});
buttonList.add(button);
button.setToggleGroup(Main.this.menuButtonToggle);
}
return buttonList;
}
private void initContentPanes(){
contentPaneMap = new HashMap<>();
Api.saveLocalisationToCache();
contentPaneMap.put(ContentType.MAP, getMapPane());
contentPaneMap.put(ContentType.SCHEDULE, getSchedulePane());
contentPaneMap.put(ContentType.ROUTE, getRoutePane());
contentPaneMap.put(ContentType.SETTINGS, getSettingsPane());
}
private Pane getSchedulePane(){
VBox schedulePane = new VBox();
Label stopNameLabel = new Label("Nazwa przystanku: ");
stopNameLabel.setPadding(new Insets(5));
TextField stopName = new TextField();
stopName.setOnAction(e -> {
List<String> stopId = Api.getId(stopName.getText());
selectedStopId = null;
schedulePane.getChildren().remove(1);
schedulePane.getChildren().add(getContentForSchedulePane(stopId, stopName.getText()));
});
schedulePane.getChildren().add(new HBox(stopNameLabel, stopName));
if (selectedStopId == null) schedulePane.getChildren().add(new Pane(new Label("Nie znaleziono przystanku")));
else schedulePane.getChildren().add(new Label(selectedStopId));
return schedulePane;
}
private Pane getContentForSchedulePane(List<String> stopId, String stopName){
if (stopId.size() == 0) return new Pane(new Label("Nie znaleziono przystanku"));
if (stopId.size() == 1) {
String stop1id = stopId.get(0);
Label stopNameLabel = new Label("Przystanek " + stopName.toUpperCase() + " (id " + stop1id + ")");
stopNameLabel.setPadding(new Insets(5));
VBox newContentPane = new VBox(stopNameLabel);
ChoiceBox<String> busStopNr = new ChoiceBox<>(
FXCollections.observableArrayList(List.of(new String[]{"01", "02"})));
busStopNr.setValue("01");
ChoiceBox<String> lineChoice = new ChoiceBox<>(
FXCollections.observableArrayList(Api.getLines(stop1id, busStopNr.getValue())));
Label times = new Label();
lineChoice.setOnAction(
e -> times.setText(Api.getTimes(stop1id, busStopNr.getValue(), lineChoice.getValue()).toString()));
busStopNr.setOnAction(
e -> lineChoice.setItems(
FXCollections.observableArrayList(Api.getLines(stop1id, busStopNr.getValue()))));
newContentPane.getChildren().addAll(
new HBox(new Label("Nr słupka: "), busStopNr),
new HBox(new Label("Nr linii: "), lineChoice),
times);
return newContentPane;
}
GridPane newButtonPane = new GridPane();
int i = 1; int j = 0;
for (String id:stopId) {
Button b = new Button(id);
b.setOnAction(event -> {
selectedStopId = b.getText();
contentPaneMap.get(ContentType.SCHEDULE).getChildren().remove(1);
contentPaneMap.get(ContentType.SCHEDULE).getChildren()
.add(getContentForSchedulePane(Collections.singletonList(b.getText()), stopName));
});
((GridPane) newButtonPane).add(b, i, j);
i = (i+1)%4+1; j = i==1?j+1:j;
}
return newButtonPane;
}
private Pane getRoutePane(){return new VBox(new Circle(20, Color.BLUE));}
private Pane getMapPane(){
MapView mapView = new MapView();
PoiLayer poiLayer = new PoiLayer();
List<Map<String, String>> pointList = Api.getLocalization();
for (Map<String, String> stop: pointList){
MapPoint point = new MapPoint(Double.parseDouble(stop.get("szer_geo")), Double.parseDouble(stop.get("dlug_geo")));
poiLayer.addPoint(point, new Circle(3, Color.RED));
}
mapView.setCenter(new MapPoint(52.230926, 21.006701));
mapView.setZoom(13);
mapView.addLayer(poiLayer);
return new StackPane(mapView);
}
public void getInfo(){
}
private Pane getSettingsPane(){
GridPane settingsPane = new GridPane();
ChoiceBox<Theme> themeChoiceBox = new ChoiceBox<>(FXCollections.observableArrayList(Theme.values()));
themeChoiceBox.setOnAction(e -> {
Main.this.theme = themeChoiceBox.getValue();
getContentPaneAndResetStage();
});
Label themeLabel = new Label("Motyw: ");
themeLabel.setPadding(new Insets(5));
settingsPane.add(themeLabel, 1, 1);
settingsPane.add(themeChoiceBox, 2, 1);
settingsPane.setHgap(10);
settingsPane.setVgap(10);
settingsPane.setGridLinesVisible(false);
return settingsPane;
}
#Override
public void init() {
System.setProperty("javafx.platform", "Desktop");
System.setProperty("http.agent", "Gluon Mobile/1.0.1");
StorageService storageService = new StorageService() {
#Override
public Optional<File> getPrivateStorage() {
return Optional.of(new File(System.getProperty("user.home")));
}
#Override
public Optional<File> getPublicStorage(String s) {
return getPrivateStorage();
}
#Override
public boolean isExternalStorageWritable() {
return getPrivateStorage().isPresent() && getPrivateStorage().get().canWrite();
}
#Override
public boolean isExternalStorageReadable() {
return getPrivateStorage().isPresent() && getPrivateStorage().get().canRead();
}
};
ServiceFactory<StorageService> storageServiceServiceFactory = new ServiceFactory<>() {
#Override
public Class<StorageService> getServiceType() {
return StorageService.class;
}
#Override
public Optional<StorageService> getInstance() {
return Optional.of(storageService);
}
};
Services.registerServiceFactory(storageServiceServiceFactory);
}
}
api.java:
package api;
import javafx.application.Platform;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Api {
private static final String baseUrl = "https://api.um.warszawa.pl/api/action/";
private static final String apikey = "95904037-5fdc-48d5-bd7f-c9f8d0b28947";
private static final String pathToLocalisationCache = "./.cache/stop-localisation.json";
private static HttpURLConnection getConnection(String urlString){
URL url = null;
HttpURLConnection connection = null;
try {
url = new URL(urlString);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
assert url != null;
connection = (HttpURLConnection)url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
return connection;
}
//Współrzędne przystanków
public static List<Map<String,String>> getLocalization() {
File cacheFile = new File(pathToLocalisationCache);
String data;
if(!cacheFile.exists()){
String url = baseUrl+"dbstore_get?id=ab75c33d-3a26-4342-b36a-6e5fef0a3ac3&apikey="+apikey;
HttpURLConnection connection = Api.setParameters(getConnection(url));
data = Api.readData(connection);
} else{
data = readLocalisationFromCache();
}
List<Map<String,String>> list = new ArrayList<>();
assert data != null;
JSONObject obj = new JSONObject(data);
JSONArray arr = obj.getJSONArray("result");
for(int j=0; j<arr.length();j++){
JSONObject obj1 = arr.getJSONObject(j);
JSONArray arr1 = obj1.getJSONArray("values");
Map<String, String> map = new HashMap<>();
for(int i = 0; i < arr1.length();i++){
String value = arr1.getJSONObject(i).getString("value");
String key = arr1.getJSONObject(i).getString("key");
map.put(key, value);
}
list.add(map);
}
return list;
}
public static void saveLocalisationToCache(){
File file = new File(pathToLocalisationCache);
if (file.exists()) return;
try{
boolean fileCreated = true;
if (!file.getParentFile().exists()) fileCreated = file.getParentFile().mkdir();
if (!fileCreated) throw new IOException("Unable to create cache directory");
fileCreated = file.createNewFile();
if (!fileCreated) throw new IOException("Unable to create file");
String url = baseUrl+"dbstore_get?id=ab75c33d-3a26-4342-b36a-6e5fef0a3ac3&apikey="+apikey;
HttpURLConnection connection = setParameters(getConnection(url));
InputStreamReader in = new InputStreamReader(new BufferedInputStream(connection.getInputStream()), StandardCharsets.UTF_8.newDecoder());
OutputStreamWriter out = new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream(file)), StandardCharsets.UTF_8.newEncoder());
in.transferTo(out);
in.close(); out.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static String readLocalisationFromCache(){
try{
BufferedReader reader = new BufferedReader(new FileReader(pathToLocalisationCache));
StringBuilder dataSB = new StringBuilder();
reader.lines().forEach(dataSB::append);
reader.close();
return dataSB.toString();
} catch (IOException e){e.printStackTrace();}
return null;
}
//id przystanku po nazwie
public static List<String> getId(String n) {
StringBuilder name = new StringBuilder();
try {
String[] testStrings = {n};
for (String s : testStrings) {
String encodedString = URLEncoder.encode(s, StandardCharsets.UTF_8);
name.append(encodedString);
}
} catch(Exception e){e.printStackTrace();}
String url = baseUrl+"dbtimetable_get?id=b27f4c17-5c50-4a5b-89dd-236b282bc499&name="+name+"&apikey="+apikey;
HttpURLConnection connection = Api.setParameters(getConnection(url));
String data = Api.readData(connection);
assert data != null;
JSONObject json = new JSONObject(data);
Pattern integerPattern = Pattern.compile("-?\\d+");
Matcher matcher = integerPattern.matcher(json.toString());
List<String> linesList = new ArrayList<>();
while (matcher.find()) {
linesList.add(matcher.group());
}
return linesList;
}
// Zwraca liste linii dla konkretnego przystanku i nr slupka
public static List<String> getLines(String idPrzystanku, String nrSlupka) {
String url = baseUrl+"dbtimetable_get?id=88cd555f-6f31-43ca-9de4-66c479ad5942&busstopId="+
idPrzystanku+"&busstopNr="+nrSlupka+"&apikey="+apikey;
HttpURLConnection connection = Api.setParameters(getConnection(url));
String data = Api.readData(connection);
assert data != null;
JSONObject json = new JSONObject(data);
Pattern integerPattern = Pattern.compile("-?\\d+");
Matcher matcher = integerPattern.matcher(json.toString());
List<String> linesList = new ArrayList<>();
while (matcher.find()) {
linesList.add(matcher.group());
}
return linesList;
}
//Zwraca listę czas dla danego przystanku i linii
public static List<String> getTimes(String idPrzystanku, String nrSlupka, String line) {
String url = baseUrl+"dbtimetable_get?id=e923fa0e-d96c-43f9-ae6e-60518c9f3238&busstopId="+
idPrzystanku+"&busstopNr="+nrSlupka+"&line="+line+"&apikey="+apikey;
HttpURLConnection connection = Api.setParameters(getConnection(url));
String data = Api.readData(connection);
List<String> times = new ArrayList<>();
assert data != null;
JSONObject obj = new JSONObject(data);
JSONArray arr = obj.getJSONArray("result");
for(int j=0; j<arr.length();j++){
JSONObject obj1 = arr.getJSONObject(j);
JSONArray arr1 = obj1.getJSONArray("values");
JSONObject obj2 = arr1.getJSONObject(5);
times.add(obj2.getString("value"));
}
return times;
}
//Odczytuje dane
public static String readData(HttpURLConnection connection) {
InputStream inStream;
try {
inStream = new BufferedInputStream(connection.getInputStream());
} catch (IOException e) {
e.printStackTrace();
return null;
}
Scanner in = new Scanner(inStream, StandardCharsets.UTF_8);
StringBuilder sb = new StringBuilder();
while (in.hasNext()) {
sb.append(in.next());
}
return sb.toString();
}
//Ustala parametry połączenia
public static HttpURLConnection setParameters(HttpURLConnection
connection) {
try {
connection.setRequestMethod("GET");
connection.setDoInput(true);
} catch (ProtocolException e) {
e.printStackTrace();
}
connection.setRequestProperty("Authorization", "Token " + apikey);
try {
if (connection.getResponseCode() != 200) {
System.out.println("Response code: "
+ connection.getResponseCode() + " " + connection.getResponseMessage());
Platform.exit(); // ze względu na javafx
System.exit(0);
}
} catch (IOException e) {
e.printStackTrace();
}
return connection;
}
}
I have no idea how to do it and I will be very grateful if someone will help me.
Based on my work experience on map libraries with JavaFX, I can share an approach you can take here. You can simply add a Mouse click event handler on the MapView and in that event you can catch the coordinates/Point where the user clicks on the screen. Then you can compare that point clicked by the user with one of the location Map points you want your user to click and see if it matches (by checking a distance between the user click position and the map coordinate of the bus stop). I have applied this approach in a different map library but similar can be applied here with some tweaks and adjustments.
List<Map<String, String>> pointList = Api.getLocalization();
mapView.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent mouseEvent) {
Point2D clickedMapCoordinates = mapView.screenToLocal(new Point2D(mouseEvent.getX(), mouseEvent.getY()));
for (Map<String, String> stop: pointList){
MapPoint stopPoint = new MapPoint(Double.parseDouble(stop.get("szer_geo")), Double.parseDouble(stop.get("dlug_geo")));
Point2D mapStopPoint = new Point2D(stopPoint.getLongitude(), stopPoint.getLatitude());
// if user clicked on map near the position(lat,lng) of a stop
// then trigger the logic, you can change the distance threshold value according to your need
if(mapStopPoint.distance(clickedMapCoordinates) < 0.0001)
{
// perform your logic here about the stop point point...
}
}
}
});
Another approach which I suppose you can take is put a click event handler on the Circle object for the bus stop point and then check if the user's clicked circle matches the coordinates of a bus stop point.
Circle circle = new Circle(3, Color.RED);
circle.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent mouseEvent) {
if(mouseEvent.getSource() instanceof Circle)
{
Circle clickedCircle = (Circle) mouseEvent.getSource();
Point2D clickedPoint = mapView.screenToLocal(clickedCircle.getCenterX(), clickedCircle.getCenterY())
for (Map<String, String> stop: pointList){
MapPoint point = new MapPoint(Double.parseDouble(stop.get("szer_geo")), Double.parseDouble(stop.get("dlug_geo")));
if(clickedPoint.getX() == point.getLongitude() && clickedPoint.getY() == point.getLatitude())
{
// this is the clicked map point (bus stop point)
// perform your logic here
}
}
}
}
});
If the second approach doesn't work, try debugging and checking the clicked point and bus stop point coordinates values and adjust them. Hope this helps you in some way.
I have a servlet which is creating a PDF direct from mysql database. Everything works fine, but now I need to add header and footer in every page of that dynamically generated pdf. The header must show 'Page current_page_number of total_number_of_page' and footer must retrieve some data from mysql database and show in a table format. I really stuck in this problem for last couple of weeks.
I am using servlet 2.5 and itextpdf 5.5.4.
Here I am attaching my code:
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.net.URL;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Font.FontFamily;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.Image;
import com.itextpdf.text.Element;
import com.itextpdf.text.Phrase;
import java.io.DataOutputStream;
import com.itextpdf.text.pdf.PdfContentByte;
/**
* Servlet implementation class for Servlet: formPart11PDF
*
*/
public class formPart11PDF extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
static final long serialVersionUID = 1L;
private String dbURL = "jdbc:mysql://localhost:3306/test";
private String dbUser = "root";
private String dbPass = "admin";
/* (non-Java-doc)
* #see javax.servlet.http.HttpServlet#HttpServlet()
*/
public formPart11PDF() {
super();
}
/* (non-Java-doc)
* #see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletOutputStream os = response.getOutputStream();
response.setContentType("application/pdf");
DataOutputStream output = new DataOutputStream(os);
Document doc = new Document();
Font bf12 = new Font(FontFamily.TIMES_ROMAN, 12);
Font f = new Font(FontFamily.TIMES_ROMAN, 10, Font.NORMAL, BaseColor.GRAY);
Connection conn4 = null;
PreparedStatement pst4 = null;
String sql4 = null;
Connection conn0 = null;
PreparedStatement pst0 = null;
String sql0 = null;
try{
PdfWriter writer = PdfWriter.getInstance(doc, output);
doc.addAuthor("betterThanZero");
doc.addCreationDate();
doc.addProducer();
doc.addCreator("MMG");
doc.addTitle("DM-01");
doc.setPageSize(PageSize.A4);
doc.setMargins(65, 50, 70, 100);
doc.open();
PdfContentByte contentByte = writer.getDirectContent();
String p_ides=request.getParameter("p_ides");
String p_diofficer=request.getParameter("p_diofficer");
float[] columnWidths4 = {10f, 30f, 60f};
//create PDF table with the given widths
PdfPTable table4 = new PdfPTable(columnWidths4);
// set table width a percentage of the page width
table4.setWidthPercentage(100f);
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
conn4 = DriverManager.getConnection(dbURL, dbUser, dbPass);
sql4="select mmg_no,i_des,tg_dir " +
"from dm_011 where i_des=? and di_officer=?";
pst4 = conn4.prepareStatement(sql4);
pst4.setString(1, p_ides);
pst4.setString(2, p_diofficer);
ResultSet rs4 = pst4.executeQuery();
while(rs4.next()){
PdfPCell cell9 = new PdfPCell(new Phrase("1", bf12));
cell9.setRowspan(2);
table4.addCell(cell9);
PdfPCell cell10 = new PdfPCell(new Phrase("a) MMG Demand Control No:\n[to be entered by MMG only]", bf12));
table4.addCell(cell10);
PdfPCell cell11 = new PdfPCell(new Phrase(rs4.getString("mmg_no"), bf12));
table4.addCell(cell11);
PdfPCell cell12 = new PdfPCell(new Phrase("b) Brief description of\nStores/Services:\n[Title of File to be given by\nDemanding Officer]", bf12));
table4.addCell(cell12);
PdfPCell cell13 = new PdfPCell(new Phrase(rs4.getString("i_des"), bf12));
table4.addCell(cell13);
PdfPCell cell14 = new PdfPCell(new Phrase("2", bf12));
table4.addCell(cell14);
PdfPCell cell15 = new PdfPCell(new Phrase("a) Tech Dir / Group:", bf12));
table4.addCell(cell15);
PdfPCell cell16 = new PdfPCell(new Phrase(rs4.getString("tg_dir"), bf12));
table4.addCell(cell16);
}
rs4.close();
pst4.close();
pst4 = null;
conn4.close();
conn4 = null;
doc.add(table4);
doc.close();
int pageCount = writer.getPageNumber()-1;
writer.close();
String output1 = os.toString();
PdfReader reader = new PdfReader(output1);
//reset the output
os = response.getOutputStream();
output = new DataOutputStream(os);
doc = new Document();
writer = PdfWriter.getInstance(doc, output);
doc.open();
PdfStamper stamper = new PdfStamper(reader, os);
for (int i = 1; i <= pageCount; i++)
{
contentByte = stamper.getOverContent(i);
//header
float[] columnWidths9 = {10f, 10f};
PdfPTable table9 = new PdfPTable(columnWidths9);
table9.setHorizontalAlignment(Element.ALIGN_RIGHT);
table9.setWidthPercentage(160 / 5.23f);
PdfPCell cell127 = new PdfPCell(new Phrase(" DM-01 ", f));
cell127.setVerticalAlignment(Element.ALIGN_CENTER);
cell127.setHorizontalAlignment(Element.ALIGN_CENTER);
table9.addCell(cell127);
PdfPCell cell128 = new PdfPCell(new Phrase(String.format("Page "+ i + " of " + pageCount), f));
cell128.setVerticalAlignment(Element.ALIGN_CENTER);
cell128.setHorizontalAlignment(Element.ALIGN_CENTER);
table9.addCell(cell128);
doc.add(table9);
//footer
Connection conn0 = null;
PreparedStatement pst0 = null;
String sql0 = null;
float[] columnWidths0 = {70f, 30f};
PdfPTable table0 = new PdfPTable(columnWidths0);
table0.setWidthPercentage(100f);
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
conn0 = DriverManager.getConnection(dbURL, dbUser, dbPass);
sql0="select i_des,di_officer " +
"from dm_011 where i_des=? and di_officer=?";
pst0 = conn0.prepareStatement(sql0);
pst0.setString(1, p_ides);
pst0.setString(2, p_diofficer);
ResultSet rs0 = pst0.executeQuery();
while(rs0.next()){
PdfPCell cell48 = new PdfPCell(new Phrase("Demand for " + rs0.getString("i_des"), bf12));
cell48.setRowspan(2);
table0.addCell(cell48);
PdfPCell cell49 = new PdfPCell(new Phrase(Chunk.NEWLINE));
cell49.setPaddingBottom(15);
cell49.setPaddingTop(15);
table0.addCell(cell49);
PdfPCell cell50 = new PdfPCell(new Phrase("Sign of Demanding Officer\n(" + rs0.getString("di_officer") + ")", bf12));
table0.addCell(cell50);
}
rs0.close();
pst0.close();
pst0 = null;
conn0.close();
conn0 = null;
PdfPTable outertable = new PdfPTable(1);
outertable.setWidthPercentage(100f);
PdfPCell cellO1 = new PdfPCell();
cellO1.setMinimumHeight(doc.getPageSize().getHeight() -
(170f + table9.getTotalHeight()));
cellO1.setVerticalAlignment(Element.ALIGN_BOTTOM);
cellO1.setBorderColor(BaseColor.WHITE);
cellO1.addElement(table0);
outertable1.addCell(cellO1);
doc.add(outertable);
}
stamper.close();
doc.close();
}catch(DocumentException e){
e.printStackTrace();
}
catch(Exception e){
e.printStackTrace();
}
}
/* (non-Java-doc)
* #see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
The above code gives me the below error:
java.io.IOException: org.apache.catalina.connector.CoyoteOutputStream#10e18ba not found as file or resource.
at com.itextpdf.text.io.RandomAccessSourceFactory.createByReadingToMemory(RandomAccessSourceFactory.java:263)
at com.itextpdf.text.io.RandomAccessSourceFactory.createBestSource(RandomAccessSourceFactory.java:173)
at com.itextpdf.text.pdf.PdfReader.<init>(PdfReader.java:219)
at com.itextpdf.text.pdf.PdfReader.<init>(PdfReader.java:207)
at com.itextpdf.text.pdf.PdfReader.<init>(PdfReader.java:197)
at servlet_for_demand.formPart11PDF.doGet(formPart11PDF.java:737)
at servlet_for_demand.formPart11PDF.doPost(formPart11PDF.java:810)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Unknown Source)
Here I am attaching my database table creation code for developer to make solution easy.
create database test;
use test;
create table dm_011(mmg_no varchar(40),i_des varchar(40),tg_dir varchar(40));
insert into dm_011 values ('1','abcd','abcd1');
insert into dm_011 values ('2','efgh','efgh1');
Please help me, I can't find any solution.
I'm asking for your help.
I'm developing an application in JavaFX who "scan" Mp3 files to get ID3tag.
Here is my problem. I did a foreach loop of a list for every .mp3 found but I'd like to increment a label which inform the progression of the list.
Here is my code
private ArrayList checkMp3File(ArrayList<String> lsMp3file, String sDir) throws UnsupportedTagException, InvalidDataException, IOException
{
this.currentData = 1;
int size = lsMp3file.size();
ArrayList<DataSong> lsds = new ArrayList<>();
for(String mp3file : lsMp3file)
{
this.labelUpdate.setText(this.current++ + " of " + " size");
DataSong ds = new DataSong();
Mp3File mp3 = new Mp3File(mp3file);
ds.setLenghtOfMp3inSec(mp3.getLengthInSeconds());
ds.setBitRateOfMp3(mp3.getBitrate());
ds.setSampleRate(mp3.getSampleRate());
ds.setVbrOrCbr(mp3.isVbr());
}
Actually, when the loop progress my window interface is completely freeze.
And only when the loop is finished, the label updated.
Someone can explain why ?
I already thank you for your answers.
EDIT :
Here is my fully code
public class LaunchOption extends Pane {
private final HBox launchAndSend = new HBox();
private final HBox browseAndField = new HBox();
private final HBox jsonAndAdvance = new HBox();
private ArrayList<DataSong> lsWithData = new ArrayList<>();
private String sendJson;
private File selectedDirectory;
private User user;
private int currentData;
private final ProgressIndicator pi = new ProgressIndicator(0);
private final VBox containerElement = new VBox();
private final TextArea displayJson = new TextArea();
private final TextField pathDir = new TextField();
private final TextField nbrOfData = new TextField();
private final Button btnScan = new Button();
private final Button btnSend = new Button();
private final Button btnCheckJson = new Button();
private final Button btnDirectoryBrowser = new Button();
private final Label nbMp3 = new Label();
public Label listAdvance = new Label();
private final Stage home;
public LaunchOption(Stage home){
this.home = home;
configureBtnCheckJson();
configureBtnScan();
configureBtnSend();
configureLabelMp3();
configureBtnDirectoryBrowser();
configureTextAreaDisplayJson();
configureTextFieldPathDir();
configureTextFieldNbDataMp3();
configureHBoxlaunchSend();
configureHBoxBrowseAndField();
configureHBoxJsonAndAdvance();
configureContainer();
this.getChildren().addAll(containerElement,launchAndSend);
}
private void configureLabelMp3()
{
nbMp3.setText("MP3");
}
private void configureBtnScan(){
btnScan.setText("Scan");
btnScan.setOnAction(event->{
ArrayList<String> Mp3FileData;
Mp3FileData = mapFilesMp3(selectedDirectory.getAbsolutePath());
System.out.println("ListSize = " + Mp3FileData.size());
nbrOfData.setText(String.valueOf(Mp3FileData.size()));
try {
lsWithData = checkMp3File(Mp3FileData, selectedDirectory.getAbsolutePath());
} catch (UnsupportedTagException ex) {
Logger.getLogger(MusiScanMp3agic.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidDataException ex) {
Logger.getLogger(MusiScanMp3agic.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(MusiScanMp3agic.class.getName()).log(Level.SEVERE, null, ex);
}
pi.setProgress(1);
});
}
private void configureBtnDirectoryBrowser(){
btnDirectoryBrowser.setText("Browse ...");
btnDirectoryBrowser.getStyleClass().add("round-red");
btnDirectoryBrowser.setOnAction(event-> {
DirectoryChooser dc = new DirectoryChooser();
selectedDirectory = dc.showDialog(home);
pi.setProgress(0.35);
if(selectedDirectory == null)
{
pathDir.setText("No directory selected");
}
else
{
pathDir.setText(selectedDirectory.getAbsolutePath());
String Text = pathDir.getText();
System.out.println(Text.toString());
}
});
}
private static String regexMp3()
{
return "^.*\\.(mp3)$";
}
private ArrayList mapFilesMp3(String sDir){
ArrayList<String> ls = new ArrayList<>();
printFnames(sDir,ls);
return ls;
}
private static void printFnames(String sDir, ArrayList<String> ls)
{
File[] faFiles = new File(sDir).listFiles();
for(File file : faFiles)
{
if(file.getName().matches(regexMp3()))
{
// System.out.println(file.getAbsolutePath());
ls.add(file.getAbsolutePath());
}
if(file.isDirectory())
{
printFnames(file.getAbsolutePath(), ls);
}
}
}
private ArrayList checkMp3File(ArrayList<String> lsMp3file, String sDir) throws UnsupportedTagException, InvalidDataException, IOException
{
this.currentData = 1;
int size = lsMp3file.size();
ArrayList<DataSong> lsds = new ArrayList<>();
for(String mp3file : lsMp3file)
{
System.out.println(this.currentData++);
DataSong ds = new DataSong();
Mp3File mp3 = new Mp3File(mp3file);
ds.setLenghtOfMp3inSec(mp3.getLengthInSeconds());
ds.setBitRateOfMp3(mp3.getBitrate());
ds.setSampleRate(mp3.getSampleRate());
ds.setVbrOrCbr(mp3.isVbr());
if(mp3 != null){
ds.setAbsoluteLocation(mp3.getFilename());
ds.setLocation(removeSDir(mp3.getFilename(), sDir));
if(mp3.hasId3v2Tag())
{
ID3v2 id3v2Tag = mp3.getId3v2Tag();
if(!(id3v2Tag.getArtist() == null))
{
ds.setArtist(id3v2Tag.getAlbumArtist());
}
if(!(id3v2Tag.getAlbum() == null))
{
ds.setAlbum((id3v2Tag.getAlbum()));
}
if(!(id3v2Tag.getTitle() == null))
{
ds.setTitle(id3v2Tag.getTitle());
}
if(!(id3v2Tag.getTrack() == null))
{
ds.setTrackOnAlbum(id3v2Tag.getTrack());
}
if(!(id3v2Tag.getYear() == null) && !(id3v2Tag.getYear().isEmpty()))
{
ds.setYearReleased(id3v2Tag.getYear());
}
if(!(id3v2Tag.getGenreDescription() == null))
{
ds.setGenre(id3v2Tag.getGenreDescription());
}
if(!(id3v2Tag.getComposer() == null))
{
ds.setComposer(id3v2Tag.getComposer());
}
if(!(id3v2Tag.getPublisher() == null))
{
ds.setPublisher(id3v2Tag.getPublisher());
}
if(!(id3v2Tag.getOriginalArtist() == null))
{
ds.setOriginArtist(id3v2Tag.getOriginalArtist());
}
if(!(id3v2Tag.getAlbumArtist() == null))
{
ds.setAlbumArtString(id3v2Tag.getAlbumArtist());
}
if(!(id3v2Tag.getCopyright() == null))
{
ds.setCopyright(id3v2Tag.getCopyright());
}
if(!(id3v2Tag.getUrl() == null))
{
ds.setUrl(id3v2Tag.getUrl());
}
}
}
lsds.add(ds);
}
return lsds;
}
I presume that what I should do is to make my checkMp3File method into a Task method which will do a background thread ?
There is not enough code to be sure but I think you are probably calling your method on the JavaFX application thread which then blocks your UI.
You should read the documentation about concurrency in JavaFX.
https://docs.oracle.com/javase/8/javafx/interoperability-tutorial/concurrency.htm
I am developing a AES-128 bit symmetric key encryptor in JavaFX. Here is my doubt: The below attached class encrypt method is called when a person clicks on encrypt button. But when someone tries to decrypt the file using the given method it doesn't actually decrypt. It gives a file that's still encrypted.
The same thing when I performed for a console based program it worked flawlessly.
GUI class (Excerpt of the project which don't work !)
package application;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Arrays;
import javafx.application.Platform;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.spec.SecretKeySpec;
public class AESEncryption {
private final File toBeUsed;
private final String password;
public AESEncryption(String passkey, File given){
this.password = passkey;
this.toBeUsed = given;
}
public void encrypt(boolean toBeLocal){
Service<Void> encryption = new Service<Void>() {
#Override
protected Task<Void> createTask() {
return new Task<Void>(){
#Override
protected Void call() throws Exception {
if(toBeLocal) this.startEncryption();
this.success();
return null;
}
private void success() {
Platform.runLater(new Runnable() {
#Override
public void run() {
EncryptionSuccessController controller = (EncryptionSuccessController)new OfflineWindow("/fxml/encryption_success.fxml", "Success").getLoader().getController();
controller.setPath(toBeUsed.getAbsolutePath()+".enc");
}
});
}
private void startEncryption() throws Exception{
SecureRandom randomizer = new SecureRandom();
byte[] salt = new byte[16];
randomizer.nextBytes(salt);
byte key[] = (password+salt).getBytes("UTF-8");
MessageDigest sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16);
SecretKeySpec pass = new SecretKeySpec(key,"AES");
Cipher encrypt = Cipher.getInstance("AES");
encrypt.init(Cipher.ENCRYPT_MODE, pass);
FileOutputStream fos = new FileOutputStream(toBeUsed.getAbsolutePath() +".enc");
try(FileInputStream fis =new FileInputStream(toBeUsed.getAbsolutePath())){
try(CipherOutputStream cout=new CipherOutputStream(fos, encrypt)){
copy(fis,cout);
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void copy(InputStream is,OutputStream os) throws Exception{
byte buf[] = new byte[4096];
int read = 0;
while((read = is.read(buf)) != -1) os.write(buf,0,read);
}
};
};
};
encryption.start();
}
public void decrypt(boolean isLocallyEncrypted){
Service<Void> decryption = new Service<Void>() {
#Override
protected Task<Void> createTask() {
return new Task<Void>(){
#Override
protected Void call() throws Exception {
if(isLocallyEncrypted) this.startDecryption();
this.message();
return null;
}
private void message() {
Platform.runLater(new Runnable(){
#Override
public void run() {
DecryptionCompleteController controller = (DecryptionCompleteController)new OfflineWindow("/fxml/decryption_over.fxml", "Completed").getLoader().getController();
controller.setPath(toBeUsed.getAbsolutePath());
}
});
}
private void startDecryption() throws Exception{
SecureRandom randomizer = new SecureRandom();
byte[] salt = new byte[16];
randomizer.nextBytes(salt);
byte key[] = (password+salt).getBytes("UTF-8");
MessageDigest sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16);
SecretKeySpec pass = new SecretKeySpec(key,"AES");
Cipher decrypt = Cipher.getInstance("AES");
decrypt.init(Cipher.DECRYPT_MODE, pass);
FileInputStream fis = new FileInputStream(toBeUsed.getAbsolutePath());
try(CipherInputStream cin=new CipherInputStream(fis, decrypt)){
try(FileOutputStream fos =new FileOutputStream(toBeUsed.getAbsolutePath().substring(0,toBeUsed.getAbsolutePath().lastIndexOf(".")))){
copy(cin,fos);
}
}
}
private void copy(InputStream is,OutputStream os) throws Exception{
byte buf[] = new byte[4096];
int read = 0;
while((read = is.read(buf)) != -1) os.write(buf,0,read);
}
};
};
};
decryption.start();
}
}
Console based code:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.spec.SecretKeySpec;
public class AES {
private String algo;
private String path;
private String password;
public AES(String algo,String path, String password) {
this.algo = algo; //setting algo
this.path = path;//setting file path
this.password = password;
}
public void encrypt() throws Exception{
SecureRandom padding = new SecureRandom();
byte[] salt = new byte[16];
padding.nextBytes(salt);
//generating key
byte k[] = (password+salt).getBytes("UTF-8");
MessageDigest sha = MessageDigest.getInstance("SHA-1");
k = sha.digest(k);
k = Arrays.copyOf(k, 16);
for(int i=0;i<k.length;i++) System.out.print(k[i]);
SecretKeySpec key = new SecretKeySpec(k,algo);
//creating and initialising cipher and cipher streams
Cipher encrypt = Cipher.getInstance(algo);
encrypt.init(Cipher.ENCRYPT_MODE, key);
//opening streams
FileOutputStream fos =new FileOutputStream(path+".enc");
try(FileInputStream fis =new FileInputStream(path)){
try(CipherOutputStream cout=new CipherOutputStream(fos, encrypt)){
copy(fis,cout);
}
}
}
public void decrypt() throws Exception{
SecureRandom padding = new SecureRandom();
byte[] salt = new byte[16];
padding.nextBytes(salt);
//generating same key
byte k[] = (password+salt).getBytes("UTF-8");
MessageDigest sha = MessageDigest.getInstance("SHA-1");
k = sha.digest(k);
k = Arrays.copyOf(k, 16);
for(int i=0;i<k.length;i++) System.out.print(k[i]);
SecretKeySpec key = new SecretKeySpec(k,algo);
//creating and initialising cipher and cipher streams
Cipher decrypt = Cipher.getInstance(algo);
decrypt.init(Cipher.DECRYPT_MODE, key);
//opening streams
FileInputStream fis = new FileInputStream(path);
try(CipherInputStream cin=new CipherInputStream(fis, decrypt)){
try(FileOutputStream fos =new FileOutputStream(path.substring(0,path.lastIndexOf(".")))){
copy(cin,fos);
}
}
}
private void copy(InputStream is,OutputStream os) throws Exception{
byte buf[] = new byte[4096]; //4K buffer set
int read = 0;
while((read = is.read(buf)) != -1) //reading
os.write(buf,0,read); //writing
}
}
As always expecting a best answer from Stack Overflow's intelligent community.
It looks like the salt value in your GUI application is different between encrypt and decrypt. I'm not sure why it would be the same in your console application, but to get the same key using the method you're using, the salt should also be the same.
Your salt is random for both encryption and decryption; this will never work as the key is different each time (which you should have noted).
You cannot just concatenate a byte array to a string. Implicitly a toString() method is called, which just shows some information about the reference.
public class AES_GUI {
private String algo;
private String path;
private String password;
public AES_GUI(String algo, String path, String password) {
this.algo = algo; // setting algo
this.path = path;// setting file path
this.password = password;
}
public void encrypt() throws Exception {
SecureRandom padding = new SecureRandom();
byte[] salt = new byte[16];
padding.nextBytes(salt);
// generating key
byte k[] = password.getBytes("UTF-8");
MessageDigest sha = MessageDigest.getInstance("SHA-1");
sha.update(salt);
k = sha.digest(k);
k = Arrays.copyOf(k, 16);
for (int i = 0; i < k.length; i++)
System.out.print(k[i]);
System.out.println();
SecretKeySpec key = new SecretKeySpec(k, algo);
// creating and initialising cipher and cipher streams
Cipher encrypt = Cipher.getInstance(algo);
encrypt.init(Cipher.ENCRYPT_MODE, key);
// opening streams
FileOutputStream fos = new FileOutputStream(path + ".enc");
fos.write(salt);
try (FileInputStream fis = new FileInputStream(path)) {
try (CipherOutputStream cout = new CipherOutputStream(fos, encrypt)) {
copy(fis, cout);
}
}
}
public void decrypt() throws Exception {
BufferedInputStream fis = new BufferedInputStream(new FileInputStream(path + ".enc"), 16);
byte[] salt = new byte[16];
int read = fis.read(salt);
if (read != 16) {
throw new IllegalStateException();
}
// generating same key
byte k[] = password.getBytes("UTF-8");
MessageDigest sha = MessageDigest.getInstance("SHA-1");
sha.update(salt);
k = sha.digest(k);
k = Arrays.copyOf(k, 16);
for (int i = 0; i < k.length; i++)
System.out.print(k[i]);
System.out.println();
SecretKeySpec key = new SecretKeySpec(k, algo);
// creating and initialising cipher and cipher streams
Cipher decrypt = Cipher.getInstance(algo);
decrypt.init(Cipher.DECRYPT_MODE, key);
// opening streams
try (CipherInputStream cin = new CipherInputStream(fis, decrypt)) {
try (FileOutputStream fos = new FileOutputStream(path + ".dec")) {
copy(cin, fos);
}
}
}
private void copy(InputStream is, OutputStream os) throws Exception {
byte buf[] = new byte[4096]; // 4K buffer set
int read = 0;
while ((read = is.read(buf)) != -1)
// reading
os.write(buf, 0, read); // writing
}
}
Note that this code is not secure. You should try and use PBKDF2 for key derivation from a password and use a different mode of operation than ECB (which is the default for the SUN provider of Oracle. Also note that I slightly altered the code for testing purposes.
I'm doing an app with Xamarin iOS.
I put a UITableView on XCode, so that when I click on a button, it retrieves from the database and slot it in. I'm able to put it onto a row, but couldn't figure it out how to have multiple rows of data in it. This is my partial code from which I'm able to display a row of data.
cmd.CommandType = CommandType.Text;
dr = cmd.ExecuteReader();
while (dr.Read())
{
var table = new UITableView(this.retrieveData.Frame);
string[] tableItems = new String[] {dr["admin_num"] + ", " + dr["name"]};
table.Source = new TableSource(tableItems);
Add (table);
}
You are creating a completely new TableView for each row in your data. Instead, you should loop through your data and create a data structure (List, array, etc) containing ALL of the data you want to display, and then pass that data to your TableView/Source.
cmd.CommandType = CommandType.Text;
dr = cmd.ExecuteReader();
// you will need a class mydata with Num and Name properties
List<mydata> data = new List<mydata>();
while (dr.Read())
{
data.Add(new mydata { Num = dr["admin_num"], Name = dr["name"] });
}
dr.Close();
var table = new UITableView(this.retrieveData.Frame);
table.Source = new TableSource(data);
Add (table);
What you need to do is this:
public List<DemoClass> getDemoClassList()
{
List<DemoClass> lstDemoClass;
DemoClass objDemoClass;
try
{
String strCommandText;
strCommandText = "SELECT * FROM DemoClass ";
command = new SqliteCommand(strCommandText, connection);
lstDemoClass = new List<DemoClass>();
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
objDemoClass = new Homes(false);
objDemoClass.ID = Convert.ToInt32(reader[0]);
objDemoClass.Name = Convert.ToString(reader[1]);
lstDemoClass.Add(objDemoClass);
}
}
return lstDemoClass;
}
catch (Exception ex)
{
throw ex;
}
finally
{
command.Dispose();
command = null;
lstDemoClass = null;
objDemoClass = null;
}
}
public void BindList()
{
List<DemoClass> lstDemoClass = new List<DemoClass>();
DemoClass hm = new DemoClass();
lstDemoClass = (List<DemoClass>)hm.getDemoClassList();
TableViewDataSource tdatasource = new TableViewDataSource(this, lstDemoClass);
table.Hidden = false;
table.DataSource = tdatasource;
table.Delegate = new TableViewDelegate(this, table, lstDemoClass);
table.ReloadData();
}
The getDemoClassList() will give the retrieved list from SQLite table, and later you can bind the list to the table datasource.
UPDATE:
As per your request I have updated my comment with the code for datasource and its delegate classes.
Now in this same class you need to add the following subclasses:
#region TableDelegate
public class TableViewDelegate : UITableViewDelegate
{
private DemoPageViewController _Controller;
private List<DemoClass> lst;
public TableViewDelegate(DemoPageViewController controller ,UITableView tableView, List<DemoClass> tblList)
{
try
{
this._Controller = controller;
this.lst = tblList;
}
catch(Exception ex)
{
}
}
public override void RowSelected (UITableView tableView, NSIndexPath indexPath)
{
try
{
//This loads the activity spinner till the selection code is completed
_Controller._loadPop = new LoadingOverlay (new System.Drawing.RectangleF(0,0,_Controller.View.Frame.Width,_Controller.View.Frame.Height),"Loading...");
_Controller.View.Add ( _Controller._loadPop );
// spin up a new thread to do some long running work using StartNew
Task.Factory.StartNew (
// tasks allow you to use the lambda syntax to pass work
() => {
InvokeOnMainThread(delegate{
DemoClass f = lst[indexPath.Row];
//Add your code here, usually some navigation or showing a popup
});
}).ContinueWith(t => InvokeOnMainThread(() => {
//Hide the activity spinner
_Controller._loadPop.Hide();
}));
}
catch(Exception ex)
{
}
finally
{
}
}
}
#endregion
#region TableDataSource
private class TableViewDataSource : UITableViewDataSource
{
static NSString kCellIdentifier = new NSString("MyIdentifier");
private List<DemoClass> lst;
private DemoPageViewController controller;
public TableViewDataSource (DemoPageViewController controller ,List<DemoClass> tblLst)
{
this.controller = controller;
this.lst = tblLst;
}
public override int NumberOfSections (UITableView tableView)
{
return 1;
}
public override int RowsInSection (UITableView tableView, int section)
{
return lst.Count;
}
// Override to support conditional editing of the table view.
public override bool CanEditRow (UITableView tableView, MonoTouch.Foundation.NSIndexPath indexPath)
{
// Return false if you do not want the specified item to be editable.
return false;
}
public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
{
try
{
UITableViewCell cell = tableView.DequeueReusableCell (kCellIdentifier);
if (cell == null)
{
cell = new UITableViewCell (UITableViewCellStyle.Subtitle, kCellIdentifier);
cell.Tag = Environment.TickCount;
}
DemoClass objDemo = lst[indexPath.Row];
cell.Accessory = UITableViewCellAccessory.DisclosureIndicator;
cell.ImageView.Image = UIImage.FromFile("Images/CameraImg.png");
cell.DetailTextLabel.Text = "Show some detail: " + objDemo.DemoDescription.ToString();
cell.TextLabel.Text = "Some Title: " + objDemo.DemoTitle.ToString();
return cell;
}
catch(Exception ex)
{
return null;
}
finally
{
}
}
}
#endregion
Hope it helps.