I am trying to populate the tableView with the data that is in the observableList but it will not show up when i run the program.
Here are parts of my program:
private TableView<Crypto> tableView = new TableView<Crypto>();
private static ArrayList<Crypto> cryptoData = new ArrayList();
private static ObservableList<Crypto> data = FXCollections.observableArrayList(cryptoData);
//*******Crypto Class************
static class Crypto{
private SimpleStringProperty coinName,
coinsBought,
costPerCoin,
totalSpent,
currentPrice,
currentValue,
profit,
roi;
public String getcoinName() {
return coinName.get();
}
public String getCoinsBought() {
return coinsBought.get();
}
public String getCostPerCoin() {
return costPerCoin.get();
}
public String getTotalSpent() {
return totalSpent.get();
}
public String getCurrentPrice() {
return currentPrice.get();
}
public String getCurrentValue() {
return currentValue.get();
}
public String getProfit() {
return profit.get();
}
public String getRoi() {
return roi.get();
}
Crypto(String name, String numBought, String costPerCoin, String totalSpent, String curPrice, String curValue, String profit, String roi){
this.coinName = new SimpleStringProperty(name);
this.coinsBought = new SimpleStringProperty(numBought);
this.costPerCoin = new SimpleStringProperty(costPerCoin);
this.totalSpent = new SimpleStringProperty(totalSpent);
this.currentPrice = new SimpleStringProperty(curPrice);
this.currentValue = new SimpleStringProperty(curValue);
this.profit = new SimpleStringProperty(profit);
this.roi = new SimpleStringProperty(roi);
}
#Override
public String toString() {
return ("[" + coinName.get() + ", " + coinsBought.get() + ", " + costPerCoin.get() + ", " +
totalSpent.get() + ", " + currentPrice.get() + ", " + currentValue.get() + ", " +
profit.get() + ", " + roi.get() + "]");
}
}//*********END Crypto Class*************
#Override
public void start(Stage primaryStage) {
try {
GridPane root = new GridPane();
//title text
Text titleText = new Text();
titleText.setText("Crypto Portfolio");
titleText.setY(600);
titleText.setFont(Font.font("Veranda", FontWeight.BOLD, FontPosture.REGULAR,40));
//refresh button
Button refresh = new Button("Refresh Prices");
refresh.setOnAction(e -> {
//ADD button refresh
});
//total amount text
Text totalDollar = new Text();
totalDollar.setText(getTotalDollar());
//table columns
TableColumn coinColumn = new TableColumn("Coin");
coinColumn.setCellValueFactory(new PropertyValueFactory<>("coinName"));
TableColumn costColumn = new TableColumn("Cost");
costColumn.setCellValueFactory(new PropertyValueFactory<>("totalSpent"));
TableColumn coinBoughtColumn = new TableColumn("Coins Bought");
coinBoughtColumn.setCellValueFactory(new PropertyValueFactory<>("coinsBought"));
TableColumn costPerCoinColumn = new TableColumn("Cost per Coin");
costPerCoinColumn.setCellValueFactory(new PropertyValueFactory<>("costPerCoin"));
TableColumn currentPriceColumn = new TableColumn("Current Coin Price");
currentPriceColumn.setCellValueFactory(new PropertyValueFactory<>("currentPrice"));
TableColumn currentValueColumn = new TableColumn("Curren Value");
currentValueColumn.setCellValueFactory(new PropertyValueFactory<>("currentValue"));
TableColumn profitColumn = new TableColumn("Profit");
profitColumn.setCellValueFactory(new PropertyValueFactory<>("profit"));
TableColumn roiColumn = new TableColumn("ROI");
roiColumn.setCellValueFactory(new PropertyValueFactory<>("roi"));
tableView.setItems(data);
tableView.getColumns().addAll(coinColumn, costColumn, coinBoughtColumn, costPerCoinColumn, currentPriceColumn, currentValueColumn, profitColumn, roiColumn);
Scene scene = new Scene(root,1200,900);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
root.setHgap(10);
root.setVgap(10);
//sets gridLines visible for debug
root.setGridLinesVisible(true);
primaryStage.setScene(scene);
primaryStage.setTitle("Mike's Crypto Portfolio");
root.add(titleText, 0,0);
root.add(refresh, 3, 0);
root.add(tableView, 0, 1);
primaryStage.show();
new Thread () {
#Override
public void run() {
try {
readCSV("crypto.csv");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
}.start();
} catch(Exception e) {
e.printStackTrace();
}
}//*****************END Start***************************
}
I thought if I added this it would work but I get a WARNING: Can not retrieve property 'coinName' in PropertyValueFactory: javafx.scene.control.cell.PropertyValueFactory#2cc2c23 with provided class type: class application.Main$Crypto java.lang.IllegalStateException: Cannot read from unreadable property coinName
but for everything besides coinName the error also adds :java.lang.RuntimeException: java.lang.IllegalAccessException: class com.sun.javafx.reflect.Trampoline cannot access a member of class application.Main$Crypto with modifiers "public"
for(Crypto coin : cryptoData) {
data.add(coin);
}
Related
Treeitem is overwriting every time I add a new class. How to solve this?
While adding a new object treeitem should be dynamically increase tried:
adding without using the list
added using the list
tried to add using a loop
This is an example code sorry for naming errors.thanks in advance
marked the place of issue with --------
PanesClass.java
public class PanesClass extends Application {
ObservableList<Connections> cList = FXCollections.observableArrayList();
public static void main(String[] args) {
launch(args);
}
#SuppressWarnings("all")#Override
public void start(Stage primaryStage) throws Exception {
NewConnection newConnection = new NewConnection();
SplitPane root = new SplitPane();
AnchorPane first = new AnchorPane();
AnchorPane second = new AnchorPane();
TreeTableView activeConnections = new TreeTableView();
HBox buttonBox = new HBox();
BorderPane topBar = new BorderPane();
Button nConnection = new Button("+");
Button deleteConnection = new Button("X");
Button connect = new Button("Connect");
buttonBox.setSpacing(10);
buttonBox.getChildren().addAll(nConnection, deleteConnection, connect);
topBar.setTop(buttonBox);
TreeTableColumn<String, Connections > cNameColoumn = new TreeTableColumn<>("Name");
cNameColoumn.setCellValueFactory(new TreeItemPropertyValueFactory<>("cname"));
TreeTableColumn<String, Connections> cStatusColoumn = new TreeTableColumn<>("Status");
cStatusColoumn.setCellValueFactory(new TreeItemPropertyValueFactory<>("cstatus"));
activeConnections.getColumns().addAll(cNameColoumn, cStatusColoumn);
activeConnections.setLayoutX(20);
activeConnections.setLayoutY(40);
activeConnections.setColumnResizePolicy(TreeTableView.CONSTRAINED_RESIZE_POLICY);
first.getChildren().addAll(topBar, activeConnections);
root.getItems().addAll(first, second);
Scene sc = new Scene(root, 600, 480);
primaryStage.setScene(sc);
primaryStage.show();
nConnection.setOnAction(new EventHandler<ActionEvent>() {#Override
public void handle(ActionEvent event) {
newConnection.getConnection(activeConnections);
}
});
}
}
NewConnection.java
public class NewConnection {
Connections connection = null;
ObservableList<Connections> cList = FXCollections.observableArrayList();
PanesClass panesClass = new PanesClass();
TreeItem cItem = null;
TreeItem nItem = null;
public void getConnection(TreeTableView<Connections> activeConnections) {
Stage secondaryStage = new Stage();
VBox root = new VBox();
GridPane cDetails = new GridPane();
HBox actionButtons = new HBox();
Button connect = new Button("Connect");
Button save = new Button("Save");
Button cancel = new Button("Cancel");
actionButtons.getChildren().addAll(connect, save, cancel);
actionButtons.setSpacing(10);
Label name = new Label("Username : ");
cDetails.add(name, 0, 0);
TextField uName = new TextField();
cDetails.setHgrow(uName, Priority.ALWAYS);
cDetails.add(uName, 1, 0);
Label password = new Label("Password : ");
cDetails.add(password, 0, 1);
TextField pwd = new TextField();
cDetails.add(pwd, 1, 1);
Label urllink = new Label("URL : ");
cDetails.add(urllink, 0, 2);
TextField url = new TextField();
cDetails.add(url, 1, 2);
cDetails.setVgap(10);
cDetails.setStyle("-fx-padding: 10;" + "-fx-border-style: solid inside;" + "-fx-border-width: 1;" + "-fx-border-insets: 5;" + "-fx-border-radius: 5;" + "-fx-border-color: black;");
root.getChildren().addAll(cDetails, actionButtons);
Scene sc = new Scene(root, 500, 200);
secondaryStage.setScene(sc);
secondaryStage.initModality(Modality.APPLICATION_MODAL);
secondaryStage.show();
save.setOnAction(new EventHandler<ActionEvent>() {
//*-----------------------------------------------------------------------*
#Override
public void handle(ActionEvent event) {
cItem = getitem(cItem);
activeConnections.setRoot(cItem);
activeConnections.setShowRoot(false);
secondaryStage.close();
}
private TreeItem getitem(TreeItem cItem) {
cList.add(new Connections(uName.getText()));
System.out.println(cList);
for (Connections temp: cList) {
System.out.println(temp);
nItem = new TreeItem<Connections>(temp);
System.out.println(nItem);
cItem.getChildren().add(nItem);
}
return cItem;
}
});
System.out.println(cList);
}
}
Connections.java
public class Connections {
private String cname = null;
private String cstatus = null;
private String cpwd = null;
private String curl = null;
public Connections() {
}
public Connections(String cname, String cpwd, String curl) {
super();
this.cname = cname;
this.cpwd = cpwd;
this.curl = curl;
}
public Connections(String cname, String cstatus) {
super();
this.cname = cname;
this.cstatus = cstatus;
}
public String getCpwd() {
return cpwd;
}
public void setCpwd(String cpwd) {
this.cpwd = cpwd;
}
public String getCurl() {
return curl;
}
public void setCurl(String curl) {
this.curl = curl;
}
public String getCname() {
return cname;
}
public void setCname(String cname) {
this.cname = cname;
}
public String getCstatus() {
return cstatus;
}
public void setCstatus(String cstatus) {
this.cstatus = cstatus;
}
#Override
public String toString() {
return "Connections [cname=" + cname + ", cstatus=" + cstatus + ", cpwd=" + cpwd + ", curl=" + curl + "]";
}
}
You're not populating your tree, you're creating new items without adding them to your tree.
First thing, you need to create a root:
// Instead of this line
// TreeItem nItem = null;
TreeItem rootItem = new TreeItem();
Then:
activeConnections.setRoot(rootItem);
save.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
// clear old connections
rootItem.getChildren().clear();
// Add new connection
cList.add(new Connections(uName.getText(), pwd.getText(), url.getText()));
// create new items and add them to rootItem
for (Connections temp : cList) {
rootItem.getChildren().add(new TreeItem<Connections>(temp));
}
secondaryStage.close();
event.consume();
}
});
NOTE: If you don't have another reason to keep cList, you can remove it and add your new Items directly (no need to clear and regenerate items everytime):
save.setOnAction(event -> {
Connections newConnection = new Connections(uName.getText(), pwd.getText(), url.getText());
rootItem.getChildren().add(new TreeItem<>(newConnection));
secondaryStage.close();
event.consume();
});
I am trying to add a class for each course in the drop down menu on the right corner of the image, as shown in the code in the action Performed there is one class but the same class opens for all the courses so how can i make each one of them open a different class?
this part is confusing me im not sure if i need to do anything with it or not
for (String crse : course) {
courseList.addItem(crse);
}
courseList.setFont(fnt);
courseList.setMaximumSize(courseList.getPreferredSize());
courseList.addActionListener(this);
courseList.setActionCommand("Course");
menuBar.add(courseList);
the list of courses in the left corner works perfectly fine with me but my only problem is instead of the list on the left i want the list on the right to work and it has something to do with crse
public class CourseWork extends JFrame implements ActionListener, KeyListener {
CommonCode cc = new CommonCode();
JPanel pnl = new JPanel(new BorderLayout());
JTextArea txtNewNote = new JTextArea();
JTextArea txtDisplayNotes = new JTextArea();
JTextField search = new JTextField();
ArrayList<String> note = new ArrayList<>();
ArrayList<String> course = new ArrayList<>();
JComboBox courseList = new JComboBox();
String crse = "";
AllNotes allNotes = new AllNotes();
public static void main(String[] args) {
// This is required for the coursework.
//JOptionPane.showMessageDialog(null, "Racha Chaouby");
CourseWork prg = new CourseWork();
}
// Using MVC
public CourseWork() {
model();
view();
controller();
}
#Override
public void actionPerformed(ActionEvent ae) {
if ("Close".equals(ae.getActionCommand())) {
}
if ("Course".equals(ae.getActionCommand())) {
crse = courseList.getSelectedItem().toString();
COMP1752 cw = new COMP1752();
}
if ("Exit".equals(ae.getActionCommand())) {
System.exit(0);
}
if ("NewNote".equals(ae.getActionCommand())) {
addNote(txtNewNote.getText());
txtNewNote.setText("");
}
if ("SearchKeyword".equals(ae.getActionCommand())) {
String lyst = allNotes.searchAllNotesByKeyword("", 0, search.getText());
txtDisplayNotes.setText(lyst);
}
if ("Coursework".equals(ae.getActionCommand())) {
CWDetails cw = new CWDetails();
}
if ("Course1752".equals(ae.getActionCommand())) {
COMP1752 cw = new COMP1752();
}
if ("Course1753".equals(ae.getActionCommand())) {
COMP1753 cw = new COMP1753();
}
if ("Cours1110".equals(ae.getActionCommand())) {
MATH1110 cw = new MATH1110();
}
}
#Override
public void keyTyped(KeyEvent e) {
System.out.println("keyTyped not coded yet.");
}
#Override
public void keyPressed(KeyEvent e) {
System.out.println("keyPressed not coded yet.");
}
#Override
public void keyReleased(KeyEvent e) {
System.out.println("keyReleased not coded yet.");
}
private void model() {
course.add("COMP1752");
course.add("COMP1753");
course.add("MATH1110");
crse = course.get(0);
//Note nt = new Note();
//nt.noteID = 1;
//t.dayte = getDateAndTime();
//nt.course = crse;
//nt.note = "Arrays are of fixed length and are inflexible.";
//allNotes.allNotes.add(nt);
//nt = new Note();
//nt.noteID = 2;
//nt.dayte = getDateAndTime();
//nt.course = crse;
//nt.note = "ArraysList can be added to and items can be deleted.";
//allNotes.allNotes.add(nt);
}
private void view() {
Font fnt = new Font("Georgia", Font.PLAIN, 24);
JMenuBar menuBar = new JMenuBar();
JMenu kurs = new JMenu();
kurs = new JMenu("Courses");
kurs.setToolTipText("Course tasks");
kurs.setFont(fnt);
kurs.add(makeMenuItem("COMP1752", "Course1752", "Coursework requirments.", fnt));
kurs.add(makeMenuItem("COMP1753", "Course1753", "Coursework requirments.", fnt));
kurs.add(makeMenuItem("MATH1110", "Course1110", "Coursework requirments.", fnt));
menuBar.add(kurs);
JMenu note = new JMenu();
note = new JMenu("Note");
note.setToolTipText("Note tasks");
note.setFont(fnt);
note.add(makeMenuItem("New", "NewNote", "Create a new note.", fnt));
note.addSeparator();
note.add(makeMenuItem("Close", "Close", "Clear the current note.", fnt));
menuBar.add(note);
menuBar.add(makeMenuItem("Exit", "Exit", "Close this program", fnt));
// This will add each course to the combobox
for (String crse : course) {
courseList.addItem(crse);
}
courseList.setFont(fnt);
courseList.setMaximumSize(courseList.getPreferredSize());
courseList.addActionListener(this);
courseList.setActionCommand("Course");
menuBar.add(courseList);
this.setJMenuBar(menuBar);
JToolBar toolBar = new JToolBar();
// Setting up the ButtonBar
JButton button = null;
button = makeButton("Document", "Coursework",
"Open the coursework window.",
"Coursework");
toolBar.add(button);
button = makeButton("Create", "NewNote",
"Create a new note.",
"New");
toolBar.add(button);
button = makeButton("closed door", "Close",
"Close this note.",
"Close");
toolBar.add(button);
toolBar.addSeparator();
button = makeButton("exit button", "Exit",
"Exit from this program.",
"Exit");
toolBar.add(button);
toolBar.addSeparator();
// This forces anything after it to the right.
toolBar.add(Box.createHorizontalGlue());
search.setMaximumSize(new Dimension(6900, 30));
search.setFont(fnt);
toolBar.add(search);
toolBar.addSeparator();
button = makeButton("search", "SearchKeyword",
"Search for this text.",
"Search");
toolBar.add(button);
add(toolBar, BorderLayout.NORTH);
JPanel pnlWest = new JPanel();
pnlWest.setLayout(new BoxLayout(pnlWest, BoxLayout.Y_AXIS));
pnlWest.setBorder(BorderFactory.createLineBorder(Color.black));
txtNewNote.setFont(fnt);
pnlWest.add(txtNewNote);
JButton btnAddNote = new JButton("Add note");
btnAddNote.setActionCommand("NewNote");
btnAddNote.addActionListener(this);
pnlWest.add(btnAddNote);
add(pnlWest, BorderLayout.WEST);
JPanel cen = new JPanel();
cen.setLayout(new BoxLayout(cen, BoxLayout.Y_AXIS));
cen.setBorder(BorderFactory.createLineBorder(Color.black));
txtDisplayNotes.setFont(fnt);
cen.add(txtDisplayNotes);
add(cen, BorderLayout.CENTER);
setExtendedState(JFrame.MAXIMIZED_BOTH);
setTitle("Coursework");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true); // Needed to ensure that the items can be seen.
}
private void controller() {
addAllNotes();
}
protected JMenuItem makeMenuItem(
String txt,
String actionCommand,
String toolTipText,
Font fnt) {
JMenuItem mnuItem = new JMenuItem();
mnuItem.setText(txt);
mnuItem.setActionCommand(actionCommand);
mnuItem.setToolTipText(toolTipText);
mnuItem.setFont(fnt);
mnuItem.addActionListener(this);
return mnuItem;
}
protected JButton makeButton(
String imageName,
String actionCommand,
String toolTipText,
String altText) {
//Create and initialize the button.
JButton button = new JButton();
button.setToolTipText(toolTipText);
button.setActionCommand(actionCommand);
button.addActionListener(this);
//Look for the image.
String imgLocation = System.getProperty("user.dir")
+ "\\icons\\"
+ imageName
+ ".png";
File fyle = new File(imgLocation);
if (fyle.exists() && !fyle.isDirectory()) {
// image found
Icon img;
img = new ImageIcon(imgLocation);
button.setIcon(img);
} else {
// image NOT found
button.setText(altText);
System.err.println("Resource not found: " + imgLocation);
}
return button;
}
private void addNote(String text) {
allNotes.addNote(allNotes.getMaxID(), crse, text);
addAllNotes();
}
private void addAllNotes() {
String txtNotes = "";
for (Note n : allNotes.getAllNotes()) {
txtNotes += n.getNote() + "\n";
}
txtDisplayNotes.setText(txtNotes);
}
public String getDateAndTime() {
String UK_DATE_FORMAT_NOW = "dd-MM-yyyy HH:mm:ss";
String ukDateAndTime;
Calendar cal = Calendar.getInstance();
SimpleDateFormat uksdf = new SimpleDateFormat(UK_DATE_FORMAT_NOW);
ukDateAndTime = uksdf.format(cal.getTime());
return ukDateAndTime;
}
}
code snippet
this is the AllNotes class:
public class AllNotes extends CommonCode {
private ArrayList<Note> allNotes = new ArrayList<>();
private String crse = "";
private int maxID = 0;
AllNotes() {
readAllNotes();
}
public final int getMaxID() {
maxID++;
return maxID;
}
private void readAllNotes() {
ArrayList<String> readNotes = new ArrayList<>();
readNotes = readTextFile(appDir + fileSeparator + "Notes.txt");
System.out.println(readNotes.get(0));
if (!"File not found".equals(readNotes.get(0))) {
allNotes.clear();
for (String str : readNotes) {
String[] tmp = str.split("\t");
int nid = Integer.parseInt(tmp[0]);
Note n = new Note(nid, tmp[1], tmp[2], tmp[3]);
allNotes.add(n);
if (nid > maxID) {
maxID = nid;
}
}
}
maxID++;
}
public void addNote(int maxID, String course, String note) {
Note myNote = new Note(maxID, course, note);
allNotes.add(myNote);
writeAllNotes();
}
public ArrayList<Note> getAllNotes() {
return allNotes;
}
private void writeAllNotes() {
String path = appDir + fileSeparator +"Notes.txt";
ArrayList<String> writeNote = new ArrayList<>();
for (Note n : allNotes) {
String tmp = n.getNoteID() + "\t";
tmp += n.getCourse() + "\t";
tmp += n.getDayte() + "\t";
tmp += n.getNote();
writeNote.add(tmp);
}
try {
writeTextFile(path, writeNote);
} catch (IOException ex) {
System.out.println("Problem! " + path);
}
}
public String searchAllNotesByKeyword(String noteList, int i, String s) {
if (i == allNotes.size()) {
return noteList;
}
if (allNotes.get(i).getNote().contains(s)) {
noteList += allNotes.get(i).getNote() + "\n";
}
return searchAllNotesByKeyword(noteList, i + 1, s);
}
}
When you init your drop down of courses, set the action command to be the same value that you record in your file, this will make everything consistent when looking up notes from the file. so this way
kurs.add(makeMenuItem("Course 1752", "COMP1752", "Coursework requirments.", fnt));
kurs.add(makeMenuItem("Course 1753", "COMP1753", "Coursework requirments.", fnt));
kurs.add(makeMenuItem("Course 1110", "MATH1110", "Coursework requirments.", fnt));
Then change actionPerformed to store the selected value form the drop down to the crse attribute, and call addAllNotes() to refresh the notes list
#Override
public void actionPerformed(ActionEvent ae) {
System.out.println("actionPerformed: " + ae.getActionCommand());
if ("Close".equals(ae.getActionCommand())) {
} else if ("Course".equals(ae.getActionCommand())) {
// set the value of the selected element into the crse attribute
crse = courseList.getSelectedItem().toString();
// Refresh the text area
addAllNotes();
} else if ("Exit".equals(ae.getActionCommand())) {
System.exit(0);
} else if ("NewNote".equals(ae.getActionCommand())) {
addNote(txtNewNote.getText());
txtNewNote.setText("");
} else if ("SearchKeyword".equals(ae.getActionCommand())) {
String lyst = allNotes.searchAllNotesByKeyword("", 0, search.getText());
txtDisplayNotes.setText(lyst);
} else if ("Coursework".equals(ae.getActionCommand())) {
CWDetails cw = new CWDetails();
}
System.out.println("selectedCourse: " + crse);
}
in AllNotes, create a new method to return the notes for a specific course.
public ArrayList<Note> getAllNotesForCourse(String course) {
ArrayList<Note> notes = new ArrayList<>();
for(Note note : allNotes) {
if(course.equalsIgnoreCase(note.getCourse())) {
notes.add(note);
}
}
return notes;
}
then in the addAllNotes method, call getAllNotesForCourse, passing the selected course. This will update txtDisplayNotes with the notes from the selected course
private void addAllNotes() {
String txtNotes = "";
for (Note n : allNotes.getAllNotesForCourse(crse)) {
txtNotes += n.getNote() + "\n";
}
txtDisplayNotes.setText(txtNotes);
}
I think this is all I modified and it works for me.
I am trying to fetch facebook feed using graph api in Codename one but it only works with my own account, Whenever other user will try to fetch their feed using my app it throw an error.
Following is my code
public class Test {
private Form current;
private Resources theme;
Form facebook;
Toolbar tb;
Image user;
Label userLabel;
Label username;
Login loginfb;
String clientId = "158093724691158";
String redirectURI = "http://www.codenameone.com/";
String clientSecret = "4f5b275ae702f7b6fde9bc50bfe3b5e3";
Label proLabel;
Label fname;
Label fmail;
Label fgender;
Container container12;
public void init(Object context) {
theme = UIManager.initFirstTheme("/theme");
// Enable Toolbar on all Forms by default
Toolbar.setGlobalToolbar(true);
// Pro only feature, uncomment if you have a pro subscription
// Log.bindCrashProtection(true);
}
public void start() {
if(current != null){
current.show();
return;
}
try{
Splash spl = new Splash();
spl.show();
new java.util.Timer().schedule(
new java.util.TimerTask() {
#Override
public void run() {
facebook.show();
}
} , 4000);
}catch(IOException e){
e.printStackTrace();
}
facebook = new Form("Facebook", new BoxLayout(BoxLayout.Y_AXIS));
tb = new Toolbar();
facebook.setToolbar(tb);
user = theme.getImage("user.png");
userLabel = new Label(user);
username = new Label("Visitor");
Button facebooklogin = new Button("Login with Facebook");
Button linked = new Button("Login with LinkedIn");
//linked.setUIID("linkedButton");
linked.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
Oauth2 auth2 = new Oauth2("https://www.linkedin.com/oauth/v2/authorization?response_type=code",
"81lq3qpacjvkcu",
"https://www.codenameone.com","r_fullprofile%20r_emailaddress","https://www.linkedin.com/uas/oauth2/accessToken","vzwWfamZ3IUQsJQL");
Oauth2.setBackToParent(true);
auth2.showAuthentication(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (evt.getSource() instanceof String) {
String token = (String) evt.getSource();
String expires = Oauth2.getExpires();
System.out.println("Token=" +token + "Expires in " +expires );
} else {
Exception err = (Exception) evt.getSource();
err.printStackTrace();
Dialog.show("Error", "An error occurred while logging in: " + err, "OK", null);
}
}
});
}
});
facebooklogin.addActionListener((evt) -> {
Login fb = FacebookConnect.getInstance();
fb.setClientId(clientId);
fb.setRedirectURI(redirectURI);
fb.setClientSecret(clientSecret);
fb.setScope("user_birthday,user_religion_politics,user_relationships,user_relationship_details,user_hometown,user_location,user_likes,user_education_history,user_work_history,user_website,user_events,user_photos,user_videos,user_friends,user_about_me,user_status,user_games_activity,user_tagged_places,user_posts,rsvp_event,email,read_insights,publish_actions,read_audience_network_insights,read_custom_friendlists,user_action.books,user_action.music,user_action.video,user_action.news,user_action.fitness,user_managed_groups,manage_pages,pages_manage_cta,pages_manage_instant_articles,pages_show_list,publish_pages,read_page_mailboxes,ads_management,ads_read,business_management,pages_messaging,pages_messaging_phone_number,pages_messaging_subscriptions,pages_messaging_payments,public_profile");
loginfb = fb;
fb.setCallback(new LoginListener(LoginListener.FACEBOOK));
if(!fb.isUserLoggedIn()){
fb.doLogin();
}else{
showFacebookUser(fb.getAccessToken().getToken());
}
});
Container container1 = BoxLayout.encloseY(userLabel,username);
container1.setUIID("container1");
tb.addComponentToSideMenu(container1);
tb.addCommandToSideMenu("Home", FontImage.createMaterial(FontImage.MATERIAL_HOME, UIManager.getInstance().getComponentStyle("TitleCommand")), (evt) -> {
});
tb.addCommandToSideMenu("Shop by Category", FontImage.createMaterial(FontImage.MATERIAL_ADD_SHOPPING_CART, UIManager.getInstance().getComponentStyle("TitleCommand")), (evt) -> {
});
tb.addCommandToSideMenu("Todays Deals", FontImage.createMaterial(FontImage.MATERIAL_LOCAL_OFFER, UIManager.getInstance().getComponentStyle("TitleCommand")), (evt) -> {
});
tb.addCommandToSideMenu("Your Orders", FontImage.createMaterial(FontImage.MATERIAL_BOOKMARK_BORDER, UIManager.getInstance().getComponentStyle("TitleCommand")), (evt) -> {
});
tb.addCommandToSideMenu("Your Wish List", FontImage.createMaterial(FontImage.MATERIAL_LIST, UIManager.getInstance().getComponentStyle("TitleCommand")), (evt) -> {
});
tb.addCommandToSideMenu("Your Account", FontImage.createMaterial(FontImage.MATERIAL_ACCOUNT_BOX, UIManager.getInstance().getComponentStyle("TitleCommand")), (evt) -> {
});
tb.addCommandToSideMenu("Gift Cards", FontImage.createMaterial(FontImage.MATERIAL_CARD_GIFTCARD, UIManager.getInstance().getComponentStyle("TitleCommand")), (evt) -> {
});
tb.addCommandToSideMenu("Setting", FontImage.createMaterial(FontImage.MATERIAL_SETTINGS, UIManager.getInstance().getComponentStyle("TitleCommand")), (evt) -> {
});
tb.addCommandToSideMenu("Logout", FontImage.createMaterial(FontImage.MATERIAL_BACKSPACE, UIManager.getInstance().getComponentStyle("TitleCommand")), (evt) -> {
});
Tabs tab = new Tabs();
Style s = UIManager.getInstance().getComponentStyle("Tab");
FontImage icon1 = FontImage.createMaterial(FontImage.MATERIAL_VPN_KEY, s);
FontImage icon2 = FontImage.createMaterial(FontImage.MATERIAL_LIST, s);
FontImage icon3 = FontImage.createMaterial(FontImage.MATERIAL_ACCOUNT_BOX, s);
Container container11 = BoxLayout.encloseY(facebooklogin,linked);
container12 = BoxLayout.encloseY(new SpanLabel("Some text directly in the tab2"));
Image pro = theme.getImage("user.png");
proLabel = new Label(pro);
Label uname = new Label("Name: ");
fname = new Label("");
Label umail = new Label("Name: ");
fmail = new Label("");
Label ugender = new Label("Name: ");
fgender = new Label("");
Container profileContainer = TableLayout.encloseIn(2, uname,fname,umail,fmail,ugender,fgender);
Container container13 = BoxLayout.encloseY(proLabel,profileContainer);
tab.addTab("Log In",icon1,container11 );
tab.addTab("Wall",icon2, container12 );
tab.addTab("User Profile",icon3, container13);
facebook.add(tab);
}
public void showFacebookUser(String token){
ConnectionRequest conn = new ConnectionRequest(){
#Override
protected void readResponse(InputStream input) throws IOException {
JSONParser parser = new JSONParser();
Map<String, Object> parsed = parser.parseJSON(new InputStreamReader(input, "UTF-8"));
String email = null;
if(email == null){
email=" ";
}
email = (String) parsed.get("email");
String name = (String) parsed.get("name");
String first_name = (String) parsed.get("first_name");
String last_name = (String) parsed.get("last_name");
String gender = (String) parsed.get("gender");
String image = (String) ((Map) ((Map) parsed.get("picture")).get("data")).get("url").toString();
ArrayList<String> data_arr1= (ArrayList) ((Map) parsed.get("feed")).get("data");
JSONArray array = new JSONArray(data_arr1);
Log.p("First NAme : " + first_name);
Log.p("Last Name : " + last_name);
Log.p("Email : " + email);
Log.p("Full Name : " + name);
Log.p("Gender : " + gender);
Log.p("Picture : " +image);
username.setText(name);
userLabel.setIcon(URLImage.createToStorage((EncodedImage) user, "Small_"+image, image, URLImage.RESIZE_SCALE));
proLabel.setIcon(URLImage.createToStorage((EncodedImage) user, image, image, URLImage.RESIZE_SCALE));
fname.setText(name);
fmail.setText(email);
fgender.setText(gender);
ArrayList<String> arrayList = new ArrayList<>();
try{
JSONArray array2 = new JSONArray(array.toString());
for(int i =0; i<array2.length() ; i++){
JSONObject jsonobject = array2.getJSONObject(i);
String story = null;
if(story == null){
story=" ";
}
try {
story = jsonobject.getString("story");
} catch (Exception e) {
e.printStackTrace();
}
String msg = null;
if(msg == null){
msg=" ";
}
try {
msg = jsonobject.getString("message");
} catch (Exception e) {
e.printStackTrace();
}
String full_picture = null;
if(full_picture == null){
full_picture=" ";
}
try{
full_picture = jsonobject.getString("full_picture");
}
catch(Exception e){
e.printStackTrace();
}
Log.p(story);
Log.p(msg);
Log.p(full_picture);
Image wallimage = theme.getImage("blank.jpg");
Label wallimageLabel = new Label(wallimage);
wallimageLabel.setIcon(URLImage.createToStorage((EncodedImage) wallimage, full_picture, full_picture, URLImage.RESIZE_SCALE));
Label wallstory = new Label(story);
Label wallmessage = new Label(msg);
Container wallcontainer = BoxLayout.encloseY(wallmessage,wallstory,wallimageLabel);
container12.add(wallcontainer);
}
}catch(Exception e){
e.printStackTrace();
}
}
};
conn.setPost(false);
conn.setUrl("https://graph.facebook.com/v2.8/me");
conn.addArgumentNoEncoding("access_token", token); //this statement is used to patch access token with url
conn.addArgumentNoEncoding("fields", "email,name,first_name,last_name,gender,picture.width(512).height(512),feed{name,full_picture,message,story},posts");
//above statement is used to provide permission through url so server send data with respect ot permissions.
NetworkManager.getInstance().addToQueue(conn);
}
public void stop() {
current = Display.getInstance().getCurrent();
if(current instanceof Dialog) {
((Dialog)current).dispose();
current = Display.getInstance().getCurrent();
}
}
public void destroy() {
}
public class LoginListener extends LoginCallback {
public static final int FACEBOOK = 0;
private int loginType;
public LoginListener(int loginType) {
this.loginType = loginType;
}
public void loginSuccessful() {
try {
AccessToken token = loginfb.getAccessToken();
if (loginType == FACEBOOK) {
showFacebookUser(token.getToken());
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void loginFailed(String errorMessage) {
Dialog.show("Login Failed", errorMessage, "Ok", null);
}
}
}
And throws following error:
java.lang.NullPointerException
at com.grv.test.Test$3.readResponse(Test.java:220)
at com.codename1.io.ConnectionRequest.performOperation(ConnectionRequest.java:733)
at com.codename1.io.NetworkManager$NetworkThread.run(NetworkManager.java:282)
at com.codename1.impl.CodenameOneThread.run(CodenameOneThread.java:176)
java.lang.NullPointerException
at com.grv.test.Test$3.readResponse(Test.java:220)
at com.codename1.io.ConnectionRequest.performOperation(ConnectionRequest.java:733)
at com.codename1.io.NetworkManager$NetworkThread.run(NetworkManager.java:282)
at com.codename1.impl.CodenameOneThread.run(CodenameOneThread.java:176)
I just want to know that why this application not able to fetch facebook feed from other user account.
I have the following problem: I created a code to separate each variable of Euclid's algorithm and store in a Array or object . I can not think of a way to retrieve the data and populate a tableView so that , depending on the MDC (a, b ) if fore very large, the columns are added automatically.
In fact , it is a representation of the resolution of the MDC by successive divisions. I did a test , but I can not run it. Follows the code .
MDC
public List<Inteiros_old> listMdc(Inteiros_old inteiros) {
//List<Integer> lista_resto = new ArrayList<Integer>();
System.out.println(" Dividendo" + "\t" + " Divisor " + "\t" + " Quociente" + "\t" + " Resto ");
System.out.println("----------" + "\t" + "----------" + "\t" + "----------" + "\t" + "----------");
int max_inteiros = Math.max(inteiros.getDividendo(), inteiros.getDivisor());
int min_inteiros = Math.min(inteiros.getDividendo(), inteiros.getDivisor());
//System.out.println(k + "\t" + m);
List<Inteiros_old> lista = new ArrayList<Inteiros_old>();
while( min_inteiros != 0) {
inteiros.setResto(max_inteiros % min_inteiros);
inteiros.setQuociente(max_inteiros/min_inteiros);
System.out.println(max_inteiros + "\t\t " + min_inteiros + "\t\t " + inteiros.getQuociente() + "\t\t" + inteiros.getResto());
max_inteiros = min_inteiros;
min_inteiros = inteiros.getResto();
//lista.add(inteiros.getResto());
}
return lista;
}
JAVAFX
public class TabelaDinamica extends Application {
private TableView<Inteiros> table = new TableView<Inteiros>();
private final ObservableList<Inteiros> data = FXCollections.observableArrayList();
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage stage) {
// -------------------------------------------------------------------------
Scene scene = new Scene(new Group());
stage.setTitle("Table View Sample");
stage.setWidth(300);
stage.setHeight(500);
final Label label = new Label("Dynamic Table with autoColumns");
label.setFont(new Font("Arial", 16));
table.setEditable(true);
// -------------------------------------------------------------------------
int sizeColumns = 4;
for (int j = 0; j < sizeColumns; j++) {
data.add(new Inteiros(1,2,3,4));
String nome = new String("col"+j);
TableColumn col = new TableColumn();
col.setMinWidth(100);
col.setCellValueFactory(
new PropertyValueFactory<Inteiros, String>(nome));
//table.getColumns().add(j, col);
table.setItems(data);
table.getColumns().addAll(col);
}
// -------------------------------------------------------------------------
final VBox vbox = new VBox();
vbox.setSpacing(5);
vbox.setPadding(new Insets(10, 0, 0, 10));
vbox.getChildren().addAll(label, table);
((Group) scene.getRoot()).getChildren().addAll(vbox);
// -------------------------------------------------------------------------
stage.setScene(scene);
stage.show();
}
}
public class Inteiros {
private SimpleIntegerProperty dividendo; //dividen
private SimpleIntegerProperty divisor; //divisor
private SimpleIntegerProperty quociente; //quotient
private SimpleIntegerProperty resto; //rest
Inteiros(Integer dividendo, Integer divisor, Integer quociente, Integer resto) {
this.dividendo = new SimpleIntegerProperty(dividendo);
this.divisor = new SimpleIntegerProperty(divisor);
this.quociente = new SimpleIntegerProperty(quociente);
this.resto = new SimpleIntegerProperty(resto);
}
public Integer getDividendo() {
return dividendo.get();
}
public void setDividendo(Integer int_num) {
dividendo.set(int_num);
}
public Integer getDivisor() {
return divisor.get();
}
public void setDivisor(Integer int_num) {
divisor.set(int_num);
}
public Integer getQuociente() {
return quociente.get();
}
public void setQuociente(Integer int_num) {
quociente.set(int_num);
}
public Integer resto() {
return resto.get();
}
public void setResto(Integer int_num) {
resto.set(int_num);
}
try this
String[] nome = {"dividendo", "divisor", "quociente", "resto"}
int sizeColumns = 4;
for (int j = 0; j < sizeColumns; j++) {
data.add(new Inteiros(1,2,3,4));
TableColumn col = new TableColumn();
col.setMinWidth(100);
col.setCellValueFactory(new PropertyValueFactory<Inteiros, String>(nome[j]));
table.getColumns().addAll(col);
}
table.setItems(data);
because the value of String nome has to match with the name of the variable
I am new to SWT development and am trying to build an extremely simple GUI window (going by the online tutorials and examples). My little GUI takes a string and parses it (using a parsing lib) and displays the parsed data in fields in a group.
Thus far, it works for ONE PASS. I enter a string, hit "Parse It", and the string is parsed correctly, and the corresponding data fields are shown in the grouping below the entry text box and buttons. I have a "Clear All" button which clears these fields. If I hit "Parse It" again, the parsing logic does execute (as is evident from console output) BUT the UI does not display the fields. (So far I have only implemented for the fixed width radio option until I get around this).
The behavior is perplexing to me. I have tried multiple things such as putting the group re-creation code in the mouseUp on the clear button, as opposed to only disposing the group. I have tried putting the group re-creation in the parse it button action code. (I also had tried creating subclasses of MouseListener for each, passing in references as necessary, but for simplicity's sake have just put everything back into an anon inner class).
I use group.layout() and not redraw. What is this SWT newbie missing? Surely it must be something super simple. MTIA! (Apologies if the code is messy - been playing with it a lot.)
Code:
package com.mycompany.common.utility.messageparser.ui;
import java.beans.PropertyDescriptor;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.*;
import org.apache.commons.beanutils.PropertyUtils;
import org.eclipse.swt.widgets.*;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.events.*;
import com.mycompany.common.utility.MessageDefinitionFactory;
import com.mycompany.common.utility.FixedWidthMessageParserUtility;
import com.mycompany.messageutils.*;
public class MainWindow
{
private static Text messageInput;
public static Display display = null;
public static Shell windowShell = null;
public static Group group = null;
public static void main(String[] args)
{
Display display = Display.getDefault();
Shell shlMultiMessageParser= new Shell();
shlMultiMessageParser.setSize(460, 388);
shlMultiMessageParser.setText("Message Parser Utility");
shlMultiMessageParser.setLayout(new FormLayout());
final Composite composite = new Composite(shlMultiMessageParser, SWT.NONE);
FormData fd_composite = new FormData();
fd_composite.bottom = new FormAttachment(0, 351);
fd_composite.right = new FormAttachment(0, 442);
fd_composite.top = new FormAttachment(0, 10);
fd_composite.left = new FormAttachment(0, 10);
composite.setLayoutData(fd_composite);
composite.setLayout(new FormLayout());
group = new Group(composite, SWT.NONE);
FormData fd_group = new FormData();
fd_group.bottom = new FormAttachment(0, 331);
fd_group.right = new FormAttachment(0, 405);
fd_group.top = new FormAttachment(0, 79);
fd_group.left = new FormAttachment(0, 10);
group.setLayoutData(fd_group);
group.setLayout(new GridLayout(2, false));
Button btnFixedWidth= new Button(composite, SWT.RADIO);
FormData fd_btnFixedWidth= new FormData();
btnFixedWidth.setLayoutData(fd_btnFixedWidth);
btnFixedWidth.setText("FixedWidth");
Button btnDelimited = new Button(composite, SWT.RADIO);
fd_btnFixedWidth.top = new FormAttachment(btnDelimited, 0, SWT.TOP);
fd_btnFixedWidth.left = new FormAttachment(btnDelimited, 23);
FormData fd_btnDelimited = new FormData();
btnDelimited.setLayoutData(fd_btnDelimited);
btnDelimited.setText("DELIM");
Button btnGeneric = new Button(composite, SWT.RADIO);
fd_btnDelimited.left = new FormAttachment(btnGeneric, 17);
btnGeneric.setText("GENERIC");
btnGeneric.setLayoutData(new FormData());
messageInput = new Text(composite, SWT.BORDER);
messageInput.setSize(128, 12);
FormData fd_messageInput = new FormData();
fd_messageInput.top = new FormAttachment(0, 40);
fd_messageInput.left = new FormAttachment(0, 10);
messageInput.setLayoutData(fd_messageInput);
Button btnParseIt = new Button(composite, SWT.NONE);
fd_messageInput.right = new FormAttachment(btnParseIt, -6);
FormData fd_btnParseIt = new FormData();
fd_btnParseIt.top = new FormAttachment(0, 38);
fd_btnParseIt.right = new FormAttachment(100, -29);
fd_btnParseIt.left = new FormAttachment(0, 335);
btnParseIt.setLayoutData(fd_btnParseIt);
btnParseIt.setText("Parse it");
// btnParseIt.addMouseListener (new ParseItButtonAction(messageInput,
// group, btnFixedWidth, btnDelimited, btnGeneric));
// PARSE IT BUTTON ACTION
btnParseIt.addMouseListener(new MouseListener()
{
public void mouseUp(MouseEvent arg0)
{
String messageString = messageInput.getText();
if (null == messageString || messageString.isEmpty())
return;
// PARSE THE MESSAGE AND BUILD THE FORM!
String messageId = messageString.substring(0, 3);
MessageDefinition messageDefinition = null;
try
{
// Will need to pull the type from the radio buttons
messageDefinition = (MessageDefinition) (MessageDefinitionFactory.getMessageDefinition("FixedWidth", messageId)).newInstance();
}
catch (Exception e2)
{
System.out.println("CAUGHT " + e2.getClass().getName() + ": " + e2.getMessage());
e2.printStackTrace();
}
ArrayList<FieldDefinition> fields = messageDefinition.getFields();
Object messageBean = null;
// List of ALL the name value pairs to be displayed.
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
try
{
messageBean = MessageHelper.getObjectFromDefinition(messageString, messageDefinition, ClientMessageType.FixedWidth);
/**
* Get the properties of the bean and display their names
* and values
*/
nameValuePairs = getNameValuePairs(messageBean, fields, nameValuePairs);
for (NameValuePair nameValuePair : nameValuePairs)
{
Label lblNewLabel = new Label(group, SWT.NONE);
lblNewLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
lblNewLabel.setText(nameValuePair.name);
Text textField = new Text(group, SWT.BORDER);
textField.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
textField.setText(nameValuePair.value);
}
/**
* End iterate thru bean properties
*/
group.layout(true);
//windowShell.layout(true);
}
catch (MessageParsingException e1)
{
System.out.println("CAUGHT " + e1.getClass().getName() + ": " + e1.getMessage());
e1.printStackTrace();
}
}
#Override
public void mouseDown(MouseEvent arg0)
{
}
#Override
public void mouseDoubleClick(MouseEvent arg0)
{
}
public List getNameValuePairs(Object messageBean, List<FieldDefinition> fields, List<NameValuePair> list)
{
Object property = null;
if (fields == null)
{
Method[] objectMethods = messageBean.getClass().getDeclaredMethods();
String fieldName = "";
Object fieldValue = null;
for (Method thisMethod : objectMethods)
{
if (thisMethod.getName().contains("get"))
{
fieldName = thisMethod.getName().substring(3, thisMethod.getName().length());
System.out.println("ATTEMPTING TO INVOKE get" + fieldName + "() on " + messageBean.getClass().getName());
try
{
fieldValue = thisMethod.invoke(messageBean);
}
catch (Exception e)
{
System.out.println("CAUGHT TRYING TO GET " + fieldName + " From " + messageBean.getClass().getName() + "::" + e.getClass().getName() + ": " + e.getMessage());
e.printStackTrace();
}
list.add(new NameValuePair(fieldName, String.valueOf(fieldValue)));
}
}
}
else
{
for (FieldDefinition f : fields)
{
try
{
property = PropertyUtils.getProperty(messageBean, f.getPropertyName());
}
catch (Exception e)
{
System.out.println("CAUGHT " + e.getClass().getName() + ": " + e.getMessage());
e.printStackTrace();
}
if (property instanceof java.lang.String)
{
list.add(new NameValuePair(f.getPropertyName(), (String) property));
}
else if (property instanceof java.util.GregorianCalendar)
{
java.util.GregorianCalendar date = (java.util.GregorianCalendar) property;
Calendar cal = date;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
String value = dateFormat.format(cal.getTime());
list.add(new NameValuePair(f.getPropertyName(), value));
}
else if (property instanceof java.util.List)
{
for (Object thePropertyObject : (List) property)
{
System.out.println("Class type of property is " + thePropertyObject.getClass().getName());
list = getNameValuePairs(thePropertyObject, null, list);
}
}
else
// could be Integer or Long.
{
list.add(new NameValuePair(f.getPropertyName(), String.valueOf(property)));
}
}
} // END else fields not null
return list;
}
}); // END OF PARSE IT BUTTON MOUSE LISTENER
// CLEAR ALL BUTTON
Button btnClearAll = new Button(composite, SWT.NONE);
btnClearAll.addMouseListener(new MouseListener()
{
#Override
public void mouseUp(MouseEvent arg0)
{
System.out.println("CLEAR ALL MOUSE UP");
if ((group != null) && (! group.isDisposed()))
{
group.dispose();
}
// REFRESH THE GROUP
group = new Group(composite, SWT.NONE);
FormData fd_group = new FormData();
fd_group.bottom = new FormAttachment(0, 331);
fd_group.right = new FormAttachment(0, 405);
fd_group.top = new FormAttachment(0, 79);
fd_group.left = new FormAttachment(0, 10);
group.setLayoutData(fd_group);
group.setLayout(new GridLayout(2, false));
group.layout(true); }
#Override
public void mouseDown(MouseEvent arg0)
{
// TODO Auto-generated method stub
}
#Override
public void mouseDoubleClick(MouseEvent arg0)
{
// TODO Auto-generated method stub
}
});
Label lblNewLabel = new Label(composite, SWT.NONE);
FormData fd_lblNewLabel = new FormData();
fd_lblNewLabel.right = new FormAttachment(0, 167);
fd_lblNewLabel.top = new FormAttachment(0, 20);
fd_lblNewLabel.left = new FormAttachment(0, 10);
lblNewLabel.setLayoutData(fd_lblNewLabel);
lblNewLabel.setText("Paste message below:");
btnClearAll.setToolTipText("Click here to clear ALL fields.");
btnClearAll.setText("Clear All");
FormData fd_btnClearAll = new FormData();
fd_btnClearAll.right = new FormAttachment(btnParseIt, 68);
fd_btnClearAll.bottom = new FormAttachment(lblNewLabel, 0, SWT.BOTTOM);
fd_btnClearAll.left = new FormAttachment(btnParseIt, 0, SWT.LEFT);
btnClearAll.setLayoutData(fd_btnClearAll);
shlMultiMessageParser.open();
shlMultiMessageParser.layout();
while (!shlMultiMessageParser.isDisposed())
{
if (!display.readAndDispatch())
{
display.sleep();
}
}
}
}
class NameValuePair
{
public String name = "";
public String value = "";
public NameValuePair(String name, String value)
{
this.name = name;
this.value = value;
}
}
class ClearAllButtonAction extends MouseAdapter
{
Group group = null;
Composite composite = null;
public ClearAllButtonAction(Group group, Composite composite)
{
System.out.println("CLEAR ALL BUTTON CTOR");
this.group = group;
this.composite = composite;
}
public void mouseUp(MouseEvent e)
{
System.out.println("CLEAR ALL MOUSE UP");
group.dispose();
/*
* group = new Group(composite, SWT.NONE); FormData fd_group = new
* FormData(); fd_group.bottom = new FormAttachment(0, 331);
* fd_group.right = new FormAttachment(0, 405); fd_group.top = new
* FormAttachment(0, 79); fd_group.left = new FormAttachment(0, 10);
* group.setLayoutData(fd_group); group.setLayout(new GridLayout(2,
* false)); group.layout(true);
*/}
}
class ParseItButtonAction extends MouseAdapter
{
private Text messageInput = null;
private Group group = null;
private Button btnFixedWidth = null, btnDELIM = null;
public ParseItButtonAction(Text messageInput, Group group, Button btnFixedWidth, Button btnDELIM, Button btnGeneric)
{
this.messageInput = messageInput;
this.group = group;
this.btnFixedWidth = btnFixedWidth;
this.btnDELIM = btnDELIM;
}
public void mouseUp(MouseEvent e)
{
// PARSE THE MESSAGE AND BUILD THE FORM!
String messageString = messageInput.getText();
String messageId = messageString.substring(0, 3);
MessageDefinition messageDefinition = null;
try
{
// Will need to pull the type from the radio buttons
messageDefinition = (MessageDefinition) (MessageDefinitionFactory.getMessageDefinition("FixedWidth", messageId)).newInstance();
}
catch (Exception e2)
{
System.out.println("CAUGHT " + e2.getClass().getName() + ": " + e2.getMessage());
e2.printStackTrace();
}
ArrayList<FieldDefinition> fields = messageDefinition.getFields();
// If this were DELIM, it would be handling a BaseMessageBean type.
Object messageBean = null;
// List of ALL the name value pairs to be displayed.
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
try
{
messageBean = MessageHelper.getObjectFromDefinition(messageString, messageDefinition, ClientMessageType.FixedWidth);
/**
* Get the properties of the bean and display their names and values
*/
nameValuePairs = getNameValuePairs(messageBean, fields, nameValuePairs);
for (NameValuePair nameValuePair : nameValuePairs)
{
Label lblNewLabel = new Label(group, SWT.NONE);
lblNewLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
lblNewLabel.setText(nameValuePair.name);
Text textField = new Text(group, SWT.BORDER);
textField.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
textField.setText(nameValuePair.value);
}
/**
* End iterate thru bean properties
*/
group.layout();
}
catch (MessageParsingException e1)
{
System.out.println("CAUGHT " + e1.getClass().getName() + ": " + e1.getMessage());
e1.printStackTrace();
}
}
// The Object type should be converted into a type of messageBean superclass
public List getNameValuePairs(Object messageBean, List<FieldDefinition> fields, List<NameValuePair> list)
{
Object property = null;
// BECAUSE FixedWidth/GENERIC DO NOT SPECIFY TYPES FOR MESSAGE SUBSECTIONS
if (fields == null)
{
Method[] objectMethods = messageBean.getClass().getDeclaredMethods();
String fieldName = "";
Object fieldValue = null;
for (Method thisMethod : objectMethods)
{
if (thisMethod.getName().contains("get"))
{
fieldName = thisMethod.getName().substring(3, thisMethod.getName().length());
System.out.println("ATTEMPTING TO INVOKE get" + fieldName + "() on " + messageBean.getClass().getName());
try
{
fieldValue = thisMethod.invoke(messageBean);
}
catch (IllegalArgumentException e)
{
System.out.println("CAUGHT TRYING TO GET " + fieldName + " From " + messageBean.getClass().getName() + "::" + e.getClass().getName() + ": " + e.getMessage());
e.printStackTrace();
}
catch (IllegalAccessException e)
{
System.out.println("CAUGHT TRYING TO GET " + fieldName + " From " + messageBean.getClass().getName() + "::" + e.getClass().getName() + ": " + e.getMessage());
e.printStackTrace();
}
catch (InvocationTargetException e)
{
System.out.println("CAUGHT TRYING TO GET " + fieldName + " From " + messageBean.getClass().getName() + "::" + e.getClass().getName() + ": " + e.getMessage());
e.printStackTrace();
}
list.add(new NameValuePair(fieldName, String.valueOf(fieldValue)));
}
}
}
else
{
for (FieldDefinition f : fields)
{
try
{
property = PropertyUtils.getProperty(messageBean, f.getPropertyName());
}
catch (Exception e)
{
System.out.println("CAUGHT " + e.getClass().getName() + ": " + e.getMessage());
e.printStackTrace();
}
if (property instanceof java.lang.String)
{
list.add(new NameValuePair(f.getPropertyName(), (String) property));
}
else if (property instanceof java.util.GregorianCalendar)
{
java.util.GregorianCalendar date = (java.util.GregorianCalendar) property;
Calendar cal = date;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
String value = dateFormat.format(cal.getTime());
list.add(new NameValuePair(f.getPropertyName(), value));
}
else if (property instanceof java.util.List)
{
for (Object thePropertyObject : (List) property)
{
System.out.println("Class type of property is " + thePropertyObject.getClass().getName());
// Need to use the factory to get the message bean type
// for the subsections, but cannot
// DO THIS for SUBSECTIONS FOR FixedWidth/GENERIC, ONLY DELIM.
// ARGH.
// Add these types to the message factory, then do the
// lookup. for now just print the types.
list = getNameValuePairs(thePropertyObject, null, list);
}
}
else
// could be Integer or Long.
{
list.add(new NameValuePair(f.getPropertyName(), String.valueOf(property)));
}
}
} // END else fields not null
return list;
}
}
I genericized the code to show it below.
Found it. I need to dispose the children of the group, and not the group itself.
if ((group != null) && (! group.isDisposed()))
{
for (Control childWidget: group.getChildren())
{
childWidget.dispose();
}
}
messageInput.setText("");