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("");
Related
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);
}
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.
Hello all I am building a java application where i want to select a users from a list of users and create a new JFrame to chat with(for example a new user-to-user chatbox). I have created the new JFrame into a thread i called it ChatGUI.
I am working with Smack so each of my ChatGUI object should have a MessageListener. When i exit a chatGUI thread it should delete everyting the thread created(for example the MessegeListener) and exit without interrupting any of the other threads(with their own MessegeListeners).
public class ChatGUI extends Thread {
volatile String remoteEndJID, remoteEndName, localEndJID, localEndName;
JFrame newFrame = new JFrame();
JButton sendMessage;
JTextField messageBox;
JTextPane chatBox;
Chat chat;
ChatMessageListener cMsgListener;
XMPPConnection connection;
StyleContext sContext;
volatile LinkedList<String> msgList;
DefaultStyledDocument sDoc;
public ChatGUI(String remoteEndJID, String remoteEndName, String localEndJID, String localEndName,
XMPPConnection connection, Chat chat, boolean createdLocaly, LinkedList<String> msgList) {
this.localEndName = localEndName;
this.remoteEndJID = remoteEndJID;
this.remoteEndName = remoteEndName;
this.localEndJID = localEndJID;
this.connection = connection;
this.chat = chat;
this.msgList = msgList;
if(createdLocaly==true)
cMsgListener = new ChatMessageListener();
start();
}
public void run() {
// Set title
newFrame.setTitle(remoteEndName);
newFrame.addWindowListener( new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
JFrame frame = (JFrame)e.getSource();
stop();
}
});
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
JPanel southPanel = new JPanel();
southPanel.setLayout(new GridBagLayout());
messageBox = new JTextField(30);
messageBox.requestFocusInWindow();
sendMessage = new JButton("Invia");
sendMessage.addActionListener(new sendMessageButtonListener());
sendMessage.setContentAreaFilled(false);
newFrame.getRootPane().setDefaultButton(sendMessage);
sContext = new StyleContext();
sDoc = new DefaultStyledDocument(sContext);
chatBox = new JTextPane(sDoc);
chatBox.setEditable(false);
mainPanel.add(new JScrollPane(chatBox), BorderLayout.CENTER);
GridBagConstraints left = new GridBagConstraints();
left.anchor = GridBagConstraints.LINE_START;
left.fill = GridBagConstraints.HORIZONTAL;
left.weightx = 512.0D;
left.weighty = 1.0D;
GridBagConstraints right = new GridBagConstraints();
right.insets = new Insets(0, 10, 0, 0);
right.anchor = GridBagConstraints.LINE_END;
right.fill = GridBagConstraints.NONE;
right.weightx = 1.0D;
right.weighty = 1.0D;
southPanel.add(messageBox, left);
southPanel.add(sendMessage, right);
mainPanel.add(BorderLayout.SOUTH, southPanel);
newFrame.add(mainPanel);
newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
newFrame.setSize(470, 300);
newFrame.setVisible(true);
if(msgList != null) {
startMessageManager();
}
// Start the actual XMPP conversation
if (cMsgListener != null)
chat = connection.getChatManager().createChat(remoteEndJID, cMsgListener);
System.out.println("New chat created : " + chat.getThreadID() + " " + chat.getParticipant());
}
class sendMessageButtonListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
if (messageBox.getText().length() < 1) {
// Do nothing
} else if (messageBox.getText().equals(".clear")) {
chatBox.setText("Cleared all messages\n");
messageBox.setText("");
} else {
addMessage(new ChatMessage(localEndName, remoteEndName, messageBox.getText(), true));
}
messageBox.requestFocusInWindow();
}
}
public void addMessage(ChatMessage message) {
Style style = sContext.getStyle(StyleContext.DEFAULT_STYLE);
if (message.isMine == true) {
// StyleConstants.setAlignment(style, StyleConstants.ALIGN_RIGHT);
StyleConstants.setFontSize(style, 14);
StyleConstants.setSpaceAbove(style, 4);
StyleConstants.setSpaceBelow(style, 4);
StyleConstants.setForeground(style, Color.BLUE);
try {
sDoc.insertString(sDoc.getLength(),
"(" + message.Time + ") " + message.senderName + ": " + message.body + "\n", style);
} catch (BadLocationException e1) {
e1.printStackTrace();
}
// Send the msg to the RemoteEnd
try {
chat.sendMessage(message.body);
} catch (XMPPException e) {
e.printStackTrace();
}
messageBox.setText("");
}
if (message.isMine == false) {
// StyleConstants.setAlignment(lStyle, StyleConstants.ALIGN_LEFT);
StyleConstants.setFontSize(style, 14);
StyleConstants.setSpaceAbove(style, 4);
StyleConstants.setSpaceBelow(style, 4);
StyleConstants.setForeground(style, Color.RED);
try {
sDoc.insertString(sDoc.getLength(),
"(" + message.Time + ") " + message.senderName + ": " + message.body + "\n", style);
} catch (BadLocationException e) {
e.printStackTrace();
}
}
}
class ChatMessageListener implements MessageListener {
#Override
public void processMessage(Chat chat, Message msg) {
if (msg.getType() == Message.Type.chat) {
addMessage(new ChatMessage(remoteEndName, localEndName, msg.getBody(), false));
System.out.println("The chat with threadID " + chat.getThreadID()
+ " recevied a message from the remoteEnd " + " " + chat.getParticipant());
}
}
}
public void startMessageManager() {
Thread t = new Thread() {
public void run() {
while(true){
if(msgList.size() > 0) {
for(int i=0; i<msgList.size();i++)
addMessage(new ChatMessage(remoteEndName, localEndName, msgList.removeFirst(), false));
}
}
}
};
t.setPriority(Thread.NORM_PRIORITY);
t.start();
}
}
Problem: For now i can create a new ChatGUI for each user but when i click exit in any of the created chatGUI-threads it closes the main process and all other chatGUIs.
Apologize for bad English.
I found the solution:
Since I am using Smack 3.2.2 it does not have the capability to stop a Chat.
My JFrame exited well after using newFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); instead of using newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
My program uses dates to check when an engineer has visited a machine. The only problem with this is that the date does not remain up to date. The date and time that the machine displays is the exact time that the machine was started. Not when the button was clicked. Any assistance would be helpful.
Code:
package com.perisic.beds.peripherals;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.lang.management.ManagementFactory;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Vector;
import javax.swing.*;
import org.apache.xmlrpc.WebServer;
import org.apache.xmlrpc.XmlRpcClient;
import com.perisic.beds.machine.CustomerPanel;
/**
* A Simple Graphical User Interface for the Recycling Machine.
* #author Group M
*
*/
public class RecyclingGUI extends JFrame implements ActionListener {
/**
*
*/
private static final long serialVersionUID = -5772727482959492839L;
//CustomerPanel myCustomerPanel = new CustomerPanel(new Display());
Display myDisplay = new Display();
ReceiptPrinter printer = new ReceiptPrinter();
ReceiptPrinter printer2 = new ReceiptPrinter();
CustomerPanel myCustomerPanel = new CustomerPanel(myDisplay);
CustomerPanel machineScreen = new CustomerPanel(printer2);
CustomerPanel theConsole = new CustomerPanel(printer);
CustomerPanel thePanel = new CustomerPanel(myDisplay);
private String storedPasswd = "123"; // needs some thinking with encryption etc
private String storedCookie = null; // some random string to be used for authentication
private String sessionCookie = "";
private int numberOfVisits;
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm");
Date date = new Date();
Date storedDate = date;
/**
* Web service to provide number of items in the machine.
* #param myCookie
* #return
*/
public int numberOfItems(String myCookie) {
if( storedCookie == null ) {
return -1;
} else if( myCookie.equals(storedCookie)) {
return myCustomerPanel.getNumberOfItems();
}
else {
return -1;
}
}
public int empty (String myCookie){
if(storedCookie == null){
return -1;
}else if(myCookie.equals(storedCookie)){
return myCustomerPanel.empty();
}else{
return -1;
}
}
/**
* Web service to authenticate the user with proper password.
* #param passwd
* #return
*/
public String login(String passwd) {
if( passwd.equals(storedPasswd)) {
storedCookie = "MC"+Math.random();
System.out.println("Engineer has logged in on: " + dateFormat.format(date));
storedDate = date;
numberOfVisits ++;
return storedCookie;
} else {
return "Incorrect Password";
}
}
public String visits(String myCookie){
if(numberOfVisits == 0){
return "Engineer has not visited this machine";
}else if(myCookie.equals(storedCookie)){
for(int i = 0; i < numberOfVisits; i++){
System.out.println("Engineer has visited on these dates: " + dateFormat.format(storedDate));
}
return storedCookie;
}else{
return "Engineer has visited on these date: " + dateFormat.format(storedDate);
}
}
/**
* Web service to logout from the system.
*/
public String logout(String myCookie ) {
if( storedCookie == null ) {
return "(no cookie set)";
} else if( myCookie.equals(storedCookie)) {
System.out.println("Engineer has logged out on: " + dateFormat.format(date));
storedCookie = null;
return "cookie deleted: OK";
}
else {
return "could not delete anything; authentication missing";
}
}
public static final String SUN_JAVA_COMMAND = "sun.java.command";
//This method is used to restart the application.
//It uses code that basically stores all of the necessary code it will need to successfully restart the application.
//Rather then just using System.exit(0) which, by itself would simply close the entire application.
//Using dispose() and new RecyclingGUI also doesn't work as it does not reload the JPanel upon restarting.
public void restartApplication(Runnable runBeforeRestart) throws IOException{
try {
String java = System.getProperty("java.home") + "/bin/java";
List<String> vmArguments = ManagementFactory.getRuntimeMXBean().getInputArguments();
StringBuffer vmArgsOneLine = new StringBuffer();
for (String arg : vmArguments) {
if (!arg.contains("-agentlib")) {
vmArgsOneLine.append(arg);
vmArgsOneLine.append(" ");
}
}
final StringBuffer cmd = new StringBuffer("\"" + java + "\" " + vmArgsOneLine);
String[] mainCommand = System.getProperty(SUN_JAVA_COMMAND).split(" ");
if (mainCommand[0].endsWith(".jar")) {
cmd.append("-jar " + new File(mainCommand[0]).getPath());
} else {
cmd.append("-cp \"" + System.getProperty("java.class.path") + "\" " + mainCommand[0]);
}
for (int i = 1; i < mainCommand.length; i++) {
cmd.append(" ");
cmd.append(mainCommand[i]);
}
Runtime.getRuntime().addShutdownHook(new Thread() {
#Override
public void run() {
try {
Runtime.getRuntime().exec(cmd.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
});
if (runBeforeRestart!= null) {
runBeforeRestart.run();
}
System.exit(0);
} catch (Exception e) {
throw new IOException("Error while trying to restart the machine", e);
}
}
public void actionPerformed(ActionEvent e) {
/* Differentiate between the different buttons pressed and initiate appropriate
* actions
*/
try{
XmlRpcClient server = new XmlRpcClient("http://localhost:100");
//This code allows the engineer to login to the machine and when they do it reveals new buttons that only the engineer can use.
if (e.getSource().equals(login)){
String message;
boolean loginSuccess = false;
while(loginSuccess == false && (message = JOptionPane.showInputDialog("Login please"))!= null){
Vector parms1 = new Vector();
parms1.add(message);
Object result3 = server.execute("recycling.login", parms1);
String loginRequest = result3.toString();
if(loginRequest.equals("Wrong password")){
System.out.println("Wrong Password. Try Again!");
} else {
sessionCookie = loginRequest;
System.out.println("You are now logged in");
login.setVisible(false);
logout.setVisible(true);
reset.setVisible(true);
empty.setVisible(true);
items.setVisible(true);
loginSuccess = true;
}
}
}else if(e.getSource().equals(visits)){
Vector params = new Vector();
params.add(sessionCookie);
Object result = server.execute("recycling.visits", params);
System.out.println(result);
//This logs the engineer out of the machine and hides some of the buttons
}else if( e.getSource().equals(logout)) {
Vector params = new Vector();
params.add(sessionCookie);
Object result = server.execute("recycling.logout", params );
System.out.println("Logout: "+result);
reset.setVisible(false);
empty.setVisible(false);
items.setVisible(false);
login.setVisible(true);
logout.setVisible(false);
//This code tells the engineer how many items are currently in the machine.
}else if(e.getSource().equals(items)){
Vector params = new Vector();
params.add(sessionCookie);
Object result = server.execute("recycling.numberOfItems", params );
int resultInt = new Integer(result.toString());
if( resultInt == -1 ) {
System.out.println("Sorry no authentication there.");
} else {
System.out.println("There are "+resultInt+" items in the machine");
}
//This if statement empties all items that have been put into the machine thus far and sets the item number property to 0
}else if(e.getSource().equals(empty)){
Vector params = new Vector();
params.add(sessionCookie);
Object result = server.execute("recycling.empty", params);
int resultInt = new Integer(result.toString());
if(resultInt == -1){
System.out.println("Sorry no authentication there.");
}else{
System.out.println("The machine has been emptied.");
}
//This method coded above is called here.
}else if(e.getSource().equals(reset)){
restartApplication(null);
}else if(e.getSource().equals(slot1)) {
myCustomerPanel.itemReceived(1);
}else if(e.getSource().equals(slot2)) {
myCustomerPanel.itemReceived(2);
}else if(e.getSource().equals(slot3)) {
myCustomerPanel.itemReceived(3);
}else if(e.getSource().equals(slot4)) {
myCustomerPanel.itemReceived(4);
}else if(e.getSource().equals(receipt)) {
myCustomerPanel.printReceipt();
}else if(e.getSource().equals(display)) {
this.myCustomerPanel = thePanel;
}else if(e.getSource().equals(console)){
myCustomerPanel = theConsole;
}else if(e.getSource().equals(onScreen)){
//once this button is clicked all output is linked back into the GUI
myCustomerPanel = machineScreen;
redirectSystemStreams();
}
}catch (Exception exception) {
System.err.println("JavaClient: " + exception);
}
// System.out.println("Received: e.getActionCommand()="+e.getActionCommand()+
// " e.getSource()="+e.getSource().toString() );
}
//This Adds the controls (buttons) to the GUI
JButton slot1 = new JButton("Can");
JButton slot2 = new JButton("Bottle");
JButton slot3 = new JButton("Crate");
JButton slot4 = new JButton("Paper Bag");
JButton receipt = new JButton("Print Receipt");
JButton login = new JButton("Login");
JButton logout = new JButton("Logout");
JButton reset = new JButton("Reset");
JButton empty = new JButton("Empty");
JButton items = new JButton("#Items");
JButton visits = new JButton("visits");
JTextArea textArea = new JTextArea(20,30);
JScrollPane scroll = new JScrollPane(textArea);
JButton display = new JButton("Print to Display");
JButton console = new JButton("Print to GUI/Console");
JButton onScreen = new JButton("Show On Screen");
/** This creates the GUI using the controls above and
* adds the actions and listeners. this area of code also
* Contains the panel settings for size and some behaviours.
*/
public RecyclingGUI() {
super();
setSize(500, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.add(slot1);
panel.add(slot2);
panel.add(slot3);
panel.add(slot4);
slot1.addActionListener(this);
slot2.addActionListener(this);
slot3.addActionListener(this);
slot4.addActionListener(this);
panel.add(receipt);
receipt.addActionListener(this);
panel.add(display);
display.addActionListener(this);
panel.add(console);
console.addActionListener(this);
panel.add(onScreen);
onScreen.addActionListener(this);
/**Text Area controls for size, font style, font size
* the text area also has a scroll bar just in case the user enters
* a large number of items
*/
panel.add(scroll);
textArea.setLineWrap(true);
textArea.setEditable(false);
textArea.setFont(new Font("Ariel",Font.PLAIN, 14));
scroll.setPreferredSize(new Dimension(450, 450));
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
panel.add(login);
login.addActionListener(this);
panel.add(logout);
logout.setVisible(false);
logout.addActionListener(this);
panel.add(reset);
reset.setVisible(false);
reset.addActionListener(this);
panel.add(items);
items.setVisible(false);
items.addActionListener(this);
panel.add(empty);
empty.setVisible(false);
empty.addActionListener(this);
panel.add(visits);
visits.addActionListener(this);
getContentPane().add(panel);
panel.repaint();
}
public static void main(String [] args ) {
RecyclingGUI myGUI = new RecyclingGUI();
myGUI.setVisible(true);
try {
System.out.println("Starting the Recycling Server...");
WebServer server = new WebServer(100);
server.addHandler("recycling", myGUI);
server.start();
} catch (Exception exception) {
System.err.println("JavaServer: " + exception);
}
}
/** This is the code that redirects where the code is displayed
* from the console to the textArea of the GUI. it does this by
* creating a new set of output streams (for text and errors) which
* are set as default when the redirectSystemStream method is called.
* (from a previous piece of work i did in my FDg, source = from a tutorial)
*/
public void updateTextArea(final String text) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
textArea.append(text);
}
});
}
public void redirectSystemStreams() {
OutputStream out = new OutputStream() {
#Override
public void write(int b) throws IOException {
updateTextArea(String.valueOf((char) b));
}
#Override
public void write(byte[] b, int off, int len) throws IOException {
updateTextArea(new String(b, off, len));
}
#Override
public void write(byte[] b) throws IOException {
write(b, 0, b.length);
}
};
System.setOut(new PrintStream(out, true));
System.setErr(new PrintStream(out, true));
}
public void print(String str) {
System.out.println(str);
}
}
You never re-initialize date, you're just updating storedDate with the existing date in login. You could change this line in login
storedDate = date;
to
storedDate = new Date();
And then (I think) you can remove date.
Date does not keep a persistent current time. Date is backed by a long that is set when the Date is instantiated and is never changed.
You can either make a new Date() in your logon method, so it would be created when the user logs on, or just use System.currentTimeMillis() to get the current time as a long.