Cannot open website link in J2ME - java

I am working on a simple J2ME application and i have a StringItem linked to a terms and conditions page online.
I have the StringItem setup and it appears underlined (giving the feeling that it is linked); but when i click on it, it does not perform any action.
Find below my code:
public class mobiMidlet extends MIDlet implements CommandListener {
private Display display;
private TextField userName,password;
public Form form;
private Command login, register, forgot, terms, cancel;
private Image img_error, img_login, img_register, img_forgot, img_terms;
private String termsurl = "http://example.com/terms.php";
private StringItem termsItem;
public mobiMidlet() {
form = new Form("Welcome to My App");
termsItem = new StringItem("", "Terms and Conditions", Item.HYPERLINK);
termsItem.setDefaultCommand(new Command("terms", Command.ITEM, 1));
ItemCommandListener listener = new ItemCommandListener() {
public void commandAction(Command cmd, Item item) {
if(cmd==terms)
{
try {
platformRequest(termsurl);
} catch (Exception e) {
e.printStackTrace();
}
}
}
};
termsItem.setItemCommandListener(listener);
userName = new TextField("LoginID:", "", 30, TextField.ANY);
password = new TextField("Password:", "", 30, TextField.PASSWORD);
cancel = new Command("Cancel", Command.CANCEL, 2);
login = new Command("Login", Command.OK, 2);
try{
img_login = Image.createImage("/logo.jpg");
img_register = Image.createImage("/error2.png");
img_forgot = Image.createImage("/logo.jpg");
img_register = Image.createImage("/error2.png");
}catch(Exception e){
System.out.println(e.getMessage());
}
}
public void startApp() {
display = Display.getDisplay(this);
form.append(termsItem);
form.append(userName);
form.append(password);
form.addCommand(cancel);
form.addCommand(login);
form.setCommandListener(this);
display.setCurrent(form);
}
public void commandAction(Command c, Displayable d) {
String label = c.getLabel();
if(label.equals("Cancel")) {
destroyApp(true);
} else if(label.equals("Login")) {
validateUser(userName.getString(), password.getString());
}
}
}
How can I fix this so that when I click on the terms and conditions link, it opens the page on a browser?

You have not initialized variable terms, so it remains null. Therefore condition cmd==terms is always false and you never enter the if statement.
Separate line termsItem.setDefaultCommand(new Command("terms", Command.ITEM, 1)); to two:
terms = new Command("terms", Command.ITEM, 1);
termsItem.setDefaultCommand(terms);
Now you have a chance.
BTW why not to debug you program? Run it in emulator, put break point into commandAction and see what happens.

Related

Spring boot app with Vaadin UI constantly refreshing screen

I have a boot app that I am adding some crud screens to. I decided to use Vaadin and it seems to work great until I deploy it to a multi-nodal production environment.
Once in the prod environment the screens constantly refresh for no apparent reason. For example there is a grid in one screen that when a row is clicked a dialog pops up that shows item details. but as soon as the dialog pops up the page refreshes numerous times.
This forum thread here https://vaadin.com/forum/thread/17586129/routerlayout-causing-page-refresh is an example of the same layout I am using and describes a very similar issue.
I have a base abstract class that extends VerticalLayout and all of the concrete classes extend this base abstract class. Each concrete class defines its own route and use a common layout class.
I have reached out on gitter, vaadin forum and opened a bug in github but no one from Vaadin want to respond to anything as far as I can tell.
Here are the versions of everything I am using:
Vaadin Flow version: 14
Java version: 12.0.1+12
OS version: Mac 10.14.5
Browser version: Fire Fox 70.0.1, Chrome 78.0.3904.97
Code snippets from my implementation:
Main View
#Slf4j
#RoutePrefix("v1/crud")
#Theme(value = Material.class, variant = Material.DARK)
public class MainView extends Div implements RouterLayout {
private H1 h1 = new H1("Vaadin Crud UI");
private HorizontalLayout header = new HorizontalLayout(h1);
private Div content = new Div();
private ApplicationContext context;
#Inject
public MainView(ApplicationContext context) {
this.context = context;
setSizeFull();
h1.setWidthFull();
content.setWidthFull();
header.setWidthFull();
header.setAlignItems(FlexComponent.Alignment.CENTER);
VerticalLayout navigationBar = new VerticalLayout();
navigationBar.setWidth("25%");
navigationBar.add(createNavigationButton("Home", VaadinIcon.HOME, ReportTab.class));
navigationBar.add(createNavigationButton("Batch Search", VaadinIcon.SEARCH, BatchSearchTab.class));
... a bunch more buttons
HorizontalLayout layout = new HorizontalLayout(navigationBar, content);
layout.setWidthFull();
VerticalLayout page = new VerticalLayout(header, layout);
page.setWidthFull();
add(page);
}
#Override
public void showRouterLayoutContent(HasElement hasElement) {
if (hasElement != null) {
Element newElement = hasElement.getElement();
if (newElement != null) {
content.removeAll();
content.getElement().appendChild(newElement);
}
}
}
private Button createNavigationButton(String caption, VaadinIcon icon, Class<? extends BaseEditor> editor) {
Button button = new Button(caption, icon.create());
button.addClickListener(event -> UI.getCurrent().navigate(editor));
button.addThemeVariants(ButtonVariant.MATERIAL_CONTAINED);
button.getStyle().set("background-color", "#00819D");
button.setWidthFull();
return button;
}
}
Base Component:
#Slf4j
#Data
#SpringComponent
#UIScope
public abstract class BaseEditor<P, B> extends VerticalLayout {
private final RememberMeService rememberMe;
private final P businessProcess;
protected Binder<B> binder;
protected Dialog editDialog = new Dialog();
protected Button save = new Button("Save", VaadinIcon.CHECK.create());
protected Button close = new Button("Close", VaadinIcon.EXIT.create());
protected Button delete = new Button("Delete", VaadinIcon.TRASH.create());
protected B bean;
private ChangeHandler changeHandler;
private boolean proceed = true;
public BaseEditor(P businessProcess, RememberMeService rememberMe) {
this.rememberMe = rememberMe;
this.businessProcess = businessProcess;
save.addClickListener(e -> save());
delete.addClickListener(e -> delete());
}
public abstract void delete();
public abstract void save();
protected abstract Component getContent();
protected void edit(B e) {
bean = e;
editDialog.open();
getBinder().setBean(e);
}
protected void initEditorPanel(Component... components) {
HorizontalLayout actions = new HorizontalLayout(save, close, delete);
VerticalLayout data = new VerticalLayout(components);
data.add(actions);
editDialog.removeAll();
editDialog.add(data);
getBinder().bindInstanceFields(this);
close.addClickListener(e -> editDialog.close());
}
public interface ChangeHandler {
void onChange();
}
void setChangeHandler(ChangeHandler h) {
changeHandler = h;
}
void errorDialog(String message) {
final Button close = new Button("Close", VaadinIcon.CLOSE.create());
H3 h3 = new H3(message);
final Dialog errorDialog = new Dialog(h3, close);
errorDialog.open();
close.addClickListener(e -> errorDialog.close());
}
BaseEditor filter(Predicate<B> predicate) {
Objects.requireNonNull(predicate);
proceed = predicate.test(bean);
return this;
}
void buttonConsumer(Consumer<B> consumer) {
if (!proceed) {
proceed = true;
return;
}
try {
consumer.accept(bean);
} catch (Exception e) {
errorDialog(e.getMessage());
} finally {
editDialog.close();
getChangeHandler().onChange();
}
}
void either(Consumer<B> whenTrue, Consumer<B> whenFalse) {
try {
if (proceed) {
whenTrue.accept(bean);
} else {
whenFalse.accept(bean);
}
} catch (Exception e) {
errorDialog(e.getMessage());
} finally {
proceed = true;
editDialog.close();
getChangeHandler().onChange();
}
}
}
Concrete Component:
#Slf4j
#Route(value = "search/batch", layout = MainView.class)
public class BatchSearchTab extends BaseEditor<BatchService, Batch> {
private TextField searchField1;
private TextField searchField2;
public BatchSearchTab(BatchService businessProcess, RememberMeService rememberMe) {
super(businessProcess, rememberMe);
binder = new Binder<>(Batch.class);
save.setIcon(VaadinIcon.REPLY.create());
save.setText("Replay");
delete.setIcon(VaadinIcon.CLOSE.create());
delete.setText("Cancel");
getContent();
}
#Override
public void delete() {
buttonConsumer(b -> getBusinessProcess().cancelBatch(b.getBatchId(), b.getUserAgent()));
}
#Override
public void save() {
filter(b -> b.isReplayable()).buttonConsumer(b -> getBusinessProcess().buildAndSendFile((getBean())));
}
#Override
public void edit(Batch batch) {
HorizontalLayout actions = new HorizontalLayout();
H2 h2 = new H2();
if (batch.isReplayable()) {
h2.setText("Would you like to replay the following.");
actions.add(save, delete, close);
} else {
h2.setText("This record is not eligible for replay.");
actions.add(close);
}
Label batchId = new Label("Correlation Id: " + batch.getBatchId());
Label txnCount = new Label("Transaction Count: " + batch.getTotalTxns());
Label txnAmount = new Label("Total: " + batch.getTotalBatchAmount());
VerticalLayout data = new VerticalLayout(h2, batchId, txnCount, txnAmount, actions);
data.add(actions);
editDialog.removeAll();
editDialog.add(data);
close.addClickListener(e -> editDialog.close());
editDialog.open();
getBinder().setBean(batch);
}
#Override
protected Component getContent() {
final H2 h2 = new H2("Locate Batches");
searchField1 = new TextField("Batch Code");
searchField2 = new TextField("User Agent");
searchField2.addKeyPressListener(Key.ENTER, e -> keyPressListener());
Button searchBtn = new Button("Search", VaadinIcon.SEARCH.create());
HorizontalLayout search = new HorizontalLayout(searchField1, searchField2);
searchBtn.addClickListener(e -> {
search(searchField1.getValue(), searchField2.getValue());
});
add(h2, search, searchBtn);
return this;
}
private void search(String code, String userAgent) {
log.info("Searching {} and {}", code, userAgent);
List<Batch> batches =
getBusinessProcess().getBatchesForUserAgent(code, userAgent, 60);
log.info("Found {} batches", batches.size());
if (batches.size() > 0) {
buildGrid(batches, "BatchId", "totalTxns", "totalBatchAmount", "status");
} else {
errorDialog("No Records found for criteria");
}
}
private void keyPressListener() {
String code = StringUtils.isNotBlank(searchField1.getValue()) ? searchField1.getValue() : null;
if (StringUtils.isNotBlank(searchField2.getValue())) {
search(code, searchField2.getValue());
}
}
private void buildGrid(Collection<Batch> records, String... columns) {
Component result;
if (records.size() == 0) {
result = new Label("NO REPORT DATA AVAILABLE.");
} else {
final Grid<Batch> grid = new Grid<>(Batch.class);
grid.setHeightByRows(records.size() < 10);
grid.setColumns(columns);
grid.setItems(records);
grid.setWidthFull();
grid.asSingleSelect().addValueChangeListener(l -> Optional.ofNullable(l.getValue()).ifPresent(this::edit));
result = grid;
}
if (getComponentCount() < 3) {
add(result);
} else {
replace(getComponentAt(2), result);
}
}
private void loadData(String code, String userAgent) {
if (StringUtils.isNotBlank(code)) {
search(null, userAgent);
} else {
search(code, userAgent);
}
}
}
Disclaimer: some further fact finding happended via IRC
The answer to the question is related to OP running multiple instances of the application behind an round robin load ballancer. The clients hit random servers and therefor had no session running there.
The solution to this is having a shared session store and ideally have the load ballancer dispatch on existing session, so "hot" backend servers get hit.

One program, different on multiple computers

First of all, I want to ask you to ask as much information as possible to me to be able to help me out.
I've been creating an automatic reminder system which is able to create the reminder in PDF then automatically send it to the clients which you've chosen to be reminded.
The program is working perfectly fine, but once I try to start it on another computer, it does not work anymore. The following problems occur:
On one computer in Eclipse it does not even open the frame which handles the user input (telling the program which clients have to be reminded). The code is given below. An interesting point here is that I've tried to print a line if the actionPerformed method is running. It does NOT appear at all. So for some reason it is not listening to that whole method.
if(starter.getAccess().equals("admin") || starter.getAccess().equals("god")){
menu = new JMenu("Aanmaningen");
menu.setMnemonic(KeyEvent.VK_N);
menu.getAccessibleContext().setAccessibleDescription(
"Debiteuren aanmanen");
menuBar.add(menu);
menu.addSeparator();
ButtonGroup group2 = new ButtonGroup();
rbMenuItem = new JRadioButtonMenuItem("Pyxis Distribution B.V.");
rbMenuItem.setSelected(false);
rbMenuItem.setMnemonic(KeyEvent.VK_R);
group2.add(rbMenuItem);
menu.add(rbMenuItem);
rbMenuItem.addActionListener(new ActionListener() {
#SuppressWarnings("static-access")
#Override
public void actionPerformed(ActionEvent arg0) {
chosenComp = true;
f.getContentPane().add(new Main());
f.revalidate();
f.repaint();
Distrscherm obj = new Distrscherm();
obj.plannerJTable();
}
});
On the other computers it was jarred and did open the menu, but did the JComboBox did not automatically complete the searchterms. It neither sent the mail. When clicking on the button save and send it didn't do anything. The codes are shown below.
This is the code which handles automatic completion (pretty basic code)
public AutoComboBox() {
setModel(new DefaultComboBoxModel(myVector));
setSelectedIndex(-1);
setEditable(true);
JTextField text = (JTextField) this.getEditor().getEditorComponent();
text.setFocusable(true);
text.setText("");
text.addKeyListener(new ComboListener(this, myVector));
setMyVector();
}
/**
* set the item list of the AutoComboBox
* #param patternExamples an String array
*/
public static void setKeyWord(Object[] patternExamples) {
AutoComboBox.keyWord = patternExamples;
setMyVectorInitial();
}
private void setMyVector() {
int a;
for (a = 0; a < keyWord.length; a++) {
myVector.add(keyWord[a]);
}
}
private static void setMyVectorInitial() {
myVector.clear();
int a;
for (a = 0; a < keyWord.length; a++) {
myVector.add(keyWord[a]);
}
This is the code which handles the SAVE button
#Override
public void actionPerformed(ActionEvent e) {
#SuppressWarnings("unused")
Writer obj1 = new Writer(getTableData(table), "./planningdagelijks/week.csv");
for(int i =0; i < model.getRowCount(); i++) {
Datareader.Runner(model.getValueAt(i, 0));
internalfile obj2 = new internalfile();
obj2.intern();
try {
maildata.Reader((String)model.getValueAt(i, 0));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Pdfgenerator.Filegenerator((String)model.getValueAt(i, 0));
}
}
});

Drag Cursor not showing on OSX

We have a large Java app that is used on both Windows and OSX.
We do custom Drag and Drop between 2 of our JTables.
On Windows, this works perfectly. The custom cursor is displayed as you drag over the target JTable.
On the Mac, the custom cursor is never displayed. Instead a gray rectangle (border only) is displayed when you start dragging. This rectangle is the width of the table column, and the height of the table. Our logging is showing that the dragOver() and dropActionChanged() methods are getting called, and we are setting the custom cursor. It just never gets displayed.
If I disable our custom cursor code, the same box is displayed - but it has the Circle/slash icon in the middle as well.
I want to get rid of the weird box, and display the custom cursor.
Excerpts from the code:
private class FileTransferHandler extends TransferHandler {
private static final long serialVersionUID = 1L;
private final Logger log = LogManager.getLogger();
private final CursorDragSourceListener dragSourceListener = new CursorDragSourceListener();
// Left out the Drop handling code that was here
#Override
public int getSourceActions( final JComponent c) {
log.debug("FileTransferHandler.getSourceAction: ");
return COPY | MOVE;
}
#Override
protected Transferable createTransferable( final JComponent c) {
log.debug("FileTransferHandler.createTransferable:");
List<iFilePage> pages = new ArrayList<iFilePage>();
// Left out the code that builds the pages list
DragSource.getDefaultDragSource().addDragSourceListener(dragSourceListener);
dragSourceListener.setCursorChoice(pages.size() == 1);
return new FilePageTransferable(pages);
}
#Override
protected void exportDone( final JComponent c,
final Transferable t,
final int action) {
log.debug("FileTransferHandler.exportDone: {}", action, t);
tblFixed.getSelectionModel().clearSelection();
DragSource.getDefaultDragSource().removeDragSourceListener(dragSourceListener);
return;
}
}
private static class CursorDragSourceListener implements DragSourceListener {
private Cursor singlePage = null;
private Cursor multiPage = null;
private Cursor badSinglePage = null;
private Cursor useCursor = null;
private boolean useSingle = false;
public CursorDragSourceListener() {
Toolkit toolkit = Toolkit.getDefaultToolkit();
URL url;
String name;
Image img;
url = FileUtils.getResourceURL("/images/page.png");
name = "DragPage";
img = toolkit.createImage(url);
singlePage = toolkit.createCustomCursor(img, new Point(16, 16), name);
url = FileUtils.getResourceURL("/images/badpage_stack.png");
name = "DragBadPage";
img = toolkit.createImage(url);
badSinglePage = toolkit.createCustomCursor(img, new Point(16, 16), name);
url = FileUtils.getResourceURL("/images/page_stack.png");
name = "DragPageStack";
img = toolkit.createImage(url);
multiPage = toolkit.createCustomCursor(img, new Point(16, 16), name);
return;
}
public void setCursorChoice( final boolean single) {
log.debug("CursorDragSourceListener.setCursorChoice: {}", single);
useSingle = single;
if (useSingle) {
useCursor = singlePage;
} else {
useCursor = multiPage;
}
return;
}
#Override
public void dropActionChanged( final DragSourceDragEvent dsde) {
log.debug("CursorDragSourceListener.dropActionChanged: {}", dsde.getDropAction(), useSingle);
if (dsde.getDropAction() == 2) {
if (!useSingle) {
useCursor = badSinglePage;
} else {
useCursor = singlePage;
}
} else {
if (useSingle) {
useCursor = singlePage;
} else {
useCursor = multiPage;
}
}
dsde.getDragSourceContext().setCursor(useCursor);
return;
}
#Override
public void dragOver( final DragSourceDragEvent dsde) {
try {
Object x = dsde.getDragSourceContext().getTransferable()
.getTransferData(DataFlavor.javaFileListFlavor);
log.trace("CursorDragSourceListener.dragOver: {}", (x != null) ? x.getClass().getSimpleName() : "null");
if (x instanceof ArrayList) {
dsde.getDragSourceContext().setCursor(useCursor);
}
} catch (Exception e) {
log.error("CursorDragSourceListener.dragOver:", e);
}
}
#Override
public void dragExit( final DragSourceEvent dse) {
}
#Override
public void dragEnter( final DragSourceDragEvent dsde) {
}
#Override
public void dragDropEnd( final DragSourceDropEvent dsde) {
}
}
After a bunch more checking and analysis, it turns out that our Custom Selection Model was causing this problem on OSX.
We have a selection model that allows you to select multiple individual cells, not just whole rows.
So the getMinSelectionindex() and getMaxSelectionIndex() methods returned dummy data, since we never used them.
That works fine on MS Win, but apparently the OSX drag and drop for JTable uses those calls.
After modifying our code to return reasonable values, the selection box is no longer as tall as the table.
The custom cursors appear most of the time, but still randomly disappear for no apparent reason.

Event doesn't work in Java Jade

I have problem with event in Java. I have got two jade's class:
First class
import jade.core.Agent;
import jade.core.behaviours.*;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import jade.domain.DFService;
import jade.domain.FIPAException;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAAgentManagement.ServiceDescription;
import java.util.*;
public class BookSellerAgent extends Agent {
// The catalogue of books for sale (maps the title of a book to its price)
private Hashtable catalogue;
// The GUI by means of which the user can add books in the catalogue
private BookSellerGui myGui;
// Put agent initializations here
protected void setup() {
// Create the catalogue
catalogue = new Hashtable();
// Create and show the GUI
myGui = new BookSellerGui(this);
myGui.showGui();
if(myGui.var==true)
System.out.println("it is work");
// Register the book-selling service in the yellow pages
DFAgentDescription dfd = new DFAgentDescription();
dfd.setName(getAID());
ServiceDescription sd = new ServiceDescription();
sd.setType("book-selling");
sd.setName("JADE-book-trading");
dfd.addServices(sd);
try {
DFService.register(this, dfd);
}
catch (FIPAException fe) {
fe.printStackTrace();
}
// Add the behaviour serving queries from buyer agents
addBehaviour(new OfferRequestsServer());
// Add the behaviour serving purchase orders from buyer agents
addBehaviour(new PurchaseOrdersServer());
}
// Put agent clean-up operations here
protected void takeDown() {
// Deregister from the yellow pages
try {
DFService.deregister(this);
}
catch (FIPAException fe) {
fe.printStackTrace();
}
// Close the GUI
myGui.dispose();
// Printout a dismissal message
System.out.println("Seller-agent "+getAID().getName()+" terminating.");
}
/**
This is invoked by the GUI when the user adds a new book for sale
*/
public void updateCatalogue(final String title, final int price) {
addBehaviour(new OneShotBehaviour() {
public void action() {
catalogue.put(title, new Integer(price));
System.out.println(title+" inserted into catalogue. Price = "+price);
}
} );
}
/**
Inner class OfferRequestsServer.
This is the behaviour used by Book-seller agents to serve incoming requests
for offer from buyer agents.
If the requested book is in the local catalogue the seller agent replies
with a PROPOSE message specifying the price. Otherwise a REFUSE message is
sent back.
*/
private class OfferRequestsServer extends CyclicBehaviour {
public void action() {
MessageTemplate mt = MessageTemplate.MatchPerformative(ACLMessage.CFP);
ACLMessage msg = myAgent.receive(mt);
if (msg != null) {
// CFP Message received. Process it
String title = msg.getContent();
ACLMessage reply = msg.createReply();
Integer price = (Integer) catalogue.get(title);
if (price != null) {
// The requested book is available for sale. Reply with the price
reply.setPerformative(ACLMessage.PROPOSE);
reply.setContent(String.valueOf(price.intValue()));
}
else {
// The requested book is NOT available for sale.
reply.setPerformative(ACLMessage.REFUSE);
reply.setContent("not-available");
}
myAgent.send(reply);
}
else {
block();
}
}
} // End of inner class OfferRequestsServer
/**
Inner class PurchaseOrdersServer.
This is the behaviour used by Book-seller agents to serve incoming
offer acceptances (i.e. purchase orders) from buyer agents.
The seller agent removes the purchased book from its catalogue
and replies with an INFORM message to notify the buyer that the
purchase has been sucesfully completed.
*/
private class PurchaseOrdersServer extends CyclicBehaviour {
public void action() {
MessageTemplate mt = MessageTemplate.MatchPerformative(ACLMessage.ACCEPT_PROPOSAL);
ACLMessage msg = myAgent.receive(mt);
if (msg != null) {
// ACCEPT_PROPOSAL Message received. Process it
String title = msg.getContent();
ACLMessage reply = msg.createReply();
Integer price = (Integer) catalogue.remove(title);
if (price != null) {
reply.setPerformative(ACLMessage.INFORM);
System.out.println(title+" sold to agent "+msg.getSender().getName());
}
else {
// The requested book has been sold to another buyer in the meanwhile .
reply.setPerformative(ACLMessage.FAILURE);
reply.setContent("not-available");
}
myAgent.send(reply);
}
else {
block();
}
}
} // End of inner class OfferRequestsServer
}
Second class
import jade.core.AID;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
#author Giovanni Caire - TILAB
*/
class BookSellerGui extends JFrame {
private BookSellerAgent myAgent;
private JTextField titleField, priceField;
boolean var;
BookSellerGui(BookSellerAgent a) {
super(a.getLocalName());
myAgent = a;
JPanel p = new JPanel();
p.setLayout(new GridLayout(2, 2));
p.add(new JLabel("Book title:"));
titleField = new JTextField(15);
p.add(titleField);
p.add(new JLabel("Price:"));
priceField = new JTextField(15);
p.add(priceField);
getContentPane().add(p, BorderLayout.CENTER);
JButton addButton = new JButton("Add");
addButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent ev) {
try {
String title = titleField.getText().trim();
String price = priceField.getText().trim();
myAgent.updateCatalogue(title, Integer.parseInt(price));
titleField.setText("");
priceField.setText("");
var=true;
}
catch (Exception e) {
JOptionPane.showMessageDialog(BookSellerGui.this, "Invalid values. "+e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
}
} );
p = new JPanel();
p.add(addButton);
getContentPane().add(p, BorderLayout.SOUTH);
// Make the agent terminate when the user closes
// the GUI using the button on the upper right corner
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
myAgent.doDelete();
}
} );
setResizable(false);
}
public void showGui() {
pack();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int centerX = (int)screenSize.getWidth() / 2;
int centerY = (int)screenSize.getHeight() / 2;
setLocation(centerX - getWidth() / 2, centerY - getHeight() / 2);
super.setVisible(true);
}
}
Problem is that when I click Add in gui i want to view "it is work". Why it doesn't work?
I don't know Jade but in your code, var is set to true when the add button is clicked. If you put a System.out.println("something") after the line var=true in the second class you will see that it happens as expected when you click the button.
If you change the first class like this:
if(myGui.var==true)
System.out.println("it is work");
else
System.out.println("Add button has not been pressed yet");
you will also see that var is still false when that condition is tested because you have not had time to click the add button yet.
The proper way to handle this would be to have the first class listen to the second class so that it gets alerted when the button is clicked and runs something appropriate when that happens.

How can I ask the user for some numbers in Java ME?

I am very new to Java Me (first time). I want my program to ask the user for an IP addres. So four numbers that are between 0 and 255. It doesn't need to be difficult, but as I said, I'm new to Java Me.
How do you want the user to input the IP address? Do you want to use a TextField for example? You could do something like the following:
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;
public class GetIPAddress extends MIDlet implements CommandListener {
private Display display;
private Form form = new Form("IP Adress Input");
private Command submit = new Command("Submit", Command.SCREEN, 1);
private Command exit = new Command("Exit", Command.EXIT, 1);
private TextField textfield = new TextField("IP Address:", "", 30, TextField.ANY);
public GetIPAddress() {
display = Display.getDisplay(this);
form.addCommand(exit);
form.addCommand(submit);
form.append(textfield);
form.setCommandListener(this);
}
public void startApp() {
display.setCurrent(form);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void commandAction(Command command, Displayable displayable) {
if (command == submit) {
// Do the manipulation of the IP address here.
// You can retrieve it using textfield.getString();
form.removeCommand(submit);
} else if (command == exit) {
destroyApp(false);
notifyDestroyed();
}
}
}

Categories