J2ME key event handling - java

I have created a textfield that takes all characters from the user.. but i want to disable the space so that user cant enter space ...help??
pin = new TextField("Pin#","",4,TextField.PASSWORD);

If it's a PIN number then maybe you should replace the constraints parameter with TextField.NUMERIC | TextField.PASSWORD.

Implement the ItemStateListener interface. Then call this.setItemStateListener(this) in the Form constructor.
Implement the itemStateChanged method so that if the Item is the one you are interested in then get its content and test it if it contains spaces.

In my case I create a MIDlet and a Form which contains a TextField. And it works. I do not know why did you say that the solution I gave you did not work to you ! Here is a very simple example I give ( I created it and tested it ! ) :
package hello;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class HelloMIDlet extends MIDlet {
public Display display;
public HelloMIDlet() {
display = Display.getDisplay(this);
}
public void startApp() {
Form f = new F(display);
display.setCurrent(f);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
}
package hello;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Item;
import javax.microedition.lcdui.ItemStateListener;
import javax.microedition.lcdui.TextField;
public class F extends Form implements ItemStateListener {
private TextField pin = new TextField("PIN :","",4,TextField.PASSWORD);
private Alert alert;
private Display disp;
public F(Display d)
{
super("");
disp = d;
this.setItemStateListener(this);
this.append(pin);
}
public void itemStateChanged(Item item) {
if (item == pin)
{
for (int i=0; i<pin.getString().length(); i++)
{
if (String.valueOf(pin.getString().charAt(i)).equals(new String(" ")))
displayAlert();
}
}
}
private void displayAlert()
{
alert = new Alert("Info","No space please !",null, AlertType.ERROR);
disp.setCurrent(alert, this);
}
}

Related

Save the state of a JFileChooser

A user has asked that I preserve the state of the JFileChooser across application restarts. Specifically, he has asked that I preserve the state of the Details / List view type selection. Two applicable questions:
How can I start the JFileChooser in the Details view?
Start a JFileChooser with files ordered by date
These both show methods of starting the JFileChooser with specific default behavior. The piece that is missing is a way to determine what behavior the user had active (view type, sort order) when the JFileChooser window is closed, so that it can be saved and restored later. Any ideas?
You can use the Properties API or Preferences API to save/restore user data.
At start up you would read the users data and set the file chooser property.
To listener for user changes to the view type you can add a PropertyChangeListener to the file chooser and listen for the viewType event. Then you would update the user data with the new value.
You can add a RowSorterListener to the RowSorter to listen for changes in the sort order. You would then need to save the sort order. I don't know the best way to store the sort data.
Based on feedback, I have created the following class. I believe that this gives all the functionality I am looking for. This class depends on this SwingUtils class.
You will also need to update access restriction rules (at least in Eclipse) to allow access to sun/swing/FilePane as described in
Access restriction: Is not accessible due to restriction on required library ..\jre\lib\rt.jar
Edit: Cleanup resource leak
After coming back to work from a long vacation, I realized that the code I initially provided could leak JFileChooser instances, and so I have reworked it to provide an AutoCloseable entity that can be used in a try-with-resources statement. Sorry for the churn.
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.prefs.Preferences;
import javax.swing.Action;
import javax.swing.JFileChooser;
import javax.swing.JTable;
import javax.swing.RowSorter;
import javax.swing.RowSorter.SortKey;
import javax.swing.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.swing.FilePane;
import darrylbu.util.SwingUtils;
#SuppressWarnings("restriction")
public class JFileChooserPersisterFactory {
private static final String VIEW_TYPE_LIST = "viewTypeList"; //$NON-NLS-1$
private static final String VIEW_TYPE_DETAILS = "viewTypeDetails"; //$NON-NLS-1$
private static final String CHOOSER_CLOSING_PROPERTY = "JFileChooserDialogIsClosingProperty"; //$NON-NLS-1$
private static final String VIEW_TYPE_PROPERTY = "viewType"; //$NON-NLS-1$
private static final String IS_DETAILS = "isDetails"; //$NON-NLS-1$
private static final String SORT_ORDER = "sortOrder"; //$NON-NLS-1$
private JFileChooserPersisterFactory() {
}
public static JFileChooserPersister createJFileChooserPersister() {
JFileChooserPersisterImpl persister = new JFileChooserPersisterImpl();
persister.init();
return persister;
}
public interface JFileChooserPersister extends AutoCloseable {
JFileChooser getJFileChooser();
#Override
void close();
}
private static class JFileChooserPersisterImpl implements JFileChooserPersister {
private final Logger logger = LoggerFactory.getLogger(getClass());
private final Preferences persistentPrefs = Preferences.userNodeForPackage(getClass());
private final JFileChooser chooser;
private boolean isDetails;
private OnChooserClosing chooserClosingListener;
private FilePane filePane;
private OnViewTypeChanged viewTypeChangedListener;
public JFileChooserPersisterImpl() {
chooser = new JFileChooser();
}
public void init() {
restoreSettings();
registerForViewTypeChangeEvents();
chooserClosingListener = new OnChooserClosing();
chooser.addPropertyChangeListener(CHOOSER_CLOSING_PROPERTY, chooserClosingListener);
}
#Override
public JFileChooser getJFileChooser() {
return chooser;
}
private void persistSettings() {
persistentPrefs.putBoolean(IS_DETAILS, isDetails);
if (isDetails) persistSortOrder();
}
private void persistSortOrder() {
byte[] serializedSortOrder = serializeSortOrder();
if (serializedSortOrder != null)
persistentPrefs.putByteArray(SORT_ORDER, serializedSortOrder);
}
private byte[] serializeSortOrder() {
List<? extends SortKey> keys = getRowSorter().getSortKeys();
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
try (ObjectOutputStream out = new ObjectOutputStream(byteStream)) {
out.writeObject(new SortOrderInfo(keys));
return byteStream.toByteArray();
} catch (IOException e) {
logger.error("Could not serialize JFileChooser row sort order.", e); //$NON-NLS-1$
}
return null;
}
private void restoreSettings() {
isDetails = persistentPrefs.getBoolean(IS_DETAILS, false);
if (isDetails) {
setToDetailsView();
applyInitialSortOrder();
} else {
setToListView();
}
}
private void setToDetailsView() {
Action details = chooser.getActionMap().get(VIEW_TYPE_DETAILS);
details.actionPerformed(null);
}
private void setToListView() {
Action details = chooser.getActionMap().get(VIEW_TYPE_LIST);
details.actionPerformed(null);
}
private void applyInitialSortOrder() {
byte[] serializedSortOrder = persistentPrefs.getByteArray(SORT_ORDER, null);
if (serializedSortOrder == null) return;
ByteArrayInputStream byteStream = new ByteArrayInputStream(serializedSortOrder);
try (ObjectInputStream in = new ObjectInputStream(byteStream)) {
setSortInfo((SortOrderInfo) in.readObject());
} catch (IOException | ClassNotFoundException e) {
logger.error("Could not deserialize JFileChooser row sort order.", e); //$NON-NLS-1$
}
}
private void setSortInfo(SortOrderInfo info) {
info.setSortOrder(getRowSorter());
}
private RowSorter<?> getRowSorter() {
JTable table = SwingUtils.getDescendantsOfType(JTable.class, chooser).get(0);
RowSorter<?> rowSorter = table.getRowSorter();
return rowSorter;
}
private void registerForViewTypeChangeEvents() {
filePane = SwingUtils.getDescendantsOfType(FilePane.class, chooser).get(0);
viewTypeChangedListener = new OnViewTypeChanged();
filePane.addPropertyChangeListener(VIEW_TYPE_PROPERTY, viewTypeChangedListener);
}
private final class OnChooserClosing implements PropertyChangeListener {
#Override
public void propertyChange(PropertyChangeEvent evt) {
persistSettings();
}
}
private class OnViewTypeChanged implements PropertyChangeListener {
#Override
public void propertyChange(PropertyChangeEvent evt) {
isDetails = ((int) evt.getNewValue()) == FilePane.VIEWTYPE_DETAILS;
}
}
public static class SortOrderInfo implements Serializable {
private static final long serialVersionUID = -5393878644049680645L;
private final List<ColumnSortInfo> keyInfo = new ArrayList<>();
public SortOrderInfo(List<? extends SortKey> keys) {
for (SortKey sortKey : keys) {
keyInfo.add(new ColumnSortInfo(sortKey));
}
}
public void setSortOrder(RowSorter<?> rowSorter) {
rowSorter.setSortKeys(makeSortKeys());
}
private List<SortKey> makeSortKeys() {
List<SortKey> keys = new ArrayList<>();
for (ColumnSortInfo info : keyInfo) {
keys.add(info.makeSortKey());
}
return keys;
}
public static class ColumnSortInfo implements Serializable {
private static final long serialVersionUID = 5406885180955729893L;
private final SortOrder sortOrder;
private final int column;
public ColumnSortInfo(SortKey sortKey) {
column = sortKey.getColumn();
sortOrder = sortKey.getSortOrder();
}
public SortKey makeSortKey() {
return new SortKey(column, sortOrder);
}
}
}
#Override
public void close() {
chooser.removePropertyChangeListener(CHOOSER_CLOSING_PROPERTY, chooserClosingListener);
filePane.removePropertyChangeListener(VIEW_TYPE_PROPERTY, viewTypeChangedListener);
}
}
}

How to use org.hibernate.action.spi.AfterTransactionCompletionProcess?

I found this class that I really want to use:
org.hibernate.action.spi.AfterTransactionCompletionProcess -
http://docs.jboss.org/hibernate/orm/3.6/javadocs/org/hibernate/action/AfterTransactionCompletionProcess.html
Basically, I'd like some custom logic to happen after the transaction is committed. But I cannot for the life of me figure out how to use this thing.
Where do I specify this interface? Any examples would be awesome.
Found an example in the Hibernate 4.3's unit test code base:
org.hibernate.envers.test.integration.basic.RegisterUserEventListenersTest
Shows exactly what I was looking for:
package org.hibernate.envers.test.integration.basic;
import org.hibernate.Session;
import org.hibernate.action.spi.AfterTransactionCompletionProcess;
import org.hibernate.action.spi.BeforeTransactionCompletionProcess;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.envers.internal.tools.MutableInteger;
import org.hibernate.envers.test.BaseEnversFunctionalTestCase;
import org.hibernate.envers.test.entities.StrTestEntity;
import org.hibernate.event.service.spi.EventListenerRegistry;
import org.hibernate.event.spi.EventType;
import org.hibernate.event.spi.PostInsertEvent;
import org.hibernate.event.spi.PostInsertEventListener;
import org.hibernate.persister.entity.EntityPersister;
import org.junit.Assert;
import org.junit.Test;
import org.hibernate.testing.TestForIssue;
/**
* #author Lukasz Antoniak (lukasz dot antoniak at gmail dot com)
*/
public class RegisterUserEventListenersTest extends BaseEnversFunctionalTestCase {
#Override
protected Class<?>[] getAnnotatedClasses() {
return new Class<?>[] {StrTestEntity.class};
}
#Test
#TestForIssue(jiraKey = "HHH-7478")
public void testTransactionProcessSynchronization() {
final EventListenerRegistry registry = sessionFactory().getServiceRegistry()
.getService( EventListenerRegistry.class );
final CountingPostInsertTransactionBoundaryListener listener = new CountingPostInsertTransactionBoundaryListener();
registry.getEventListenerGroup( EventType.POST_INSERT ).appendListener( listener );
Session session = openSession();
session.getTransaction().begin();
StrTestEntity entity = new StrTestEntity( "str1" );
session.save( entity );
session.getTransaction().commit();
session.close();
// Post insert listener invoked three times - before/after insertion of original data,
// revision entity and audit row.
Assert.assertEquals( 3, listener.getBeforeCount() );
Assert.assertEquals( 3, listener.getAfterCount() );
}
private static class CountingPostInsertTransactionBoundaryListener implements PostInsertEventListener {
private final MutableInteger beforeCounter = new MutableInteger();
private final MutableInteger afterCounter = new MutableInteger();
#Override
public void onPostInsert(PostInsertEvent event) {
event.getSession().getActionQueue().registerProcess(
new BeforeTransactionCompletionProcess() {
#Override
public void doBeforeTransactionCompletion(SessionImplementor session) {
beforeCounter.increase();
}
}
);
event.getSession().getActionQueue().registerProcess(
new AfterTransactionCompletionProcess() {
#Override
public void doAfterTransactionCompletion(boolean success, SessionImplementor session) {
afterCounter.increase();
}
}
);
}
#Override
public boolean requiresPostCommitHanding(EntityPersister persister) {
return true;
}
public int getBeforeCount() {
return beforeCounter.get();
}
public int getAfterCount() {
return afterCounter.get();
}
}
}

Calling a method from another class in java

I am using BlueJ and i am trying to call a method from another class. To be more specific i am trying to complete the following.
When the download music button is pressed, if a suitable value has been entered for the display number:
The display number is used to get the gadget, cast as MP3, from the array list.
The method to download music in the MP3 class is called with the
download size entered.
Here is the gadgetshop class that builds the GUI and the place where i want to call the downloadMusic method. the method for the button is called downloadMusic.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.ArrayList;
public class GadgetShop implements ActionListener
{
//Array List
private ArrayList<Gadget>gadgets;
public void actionPerformed(ActionEvent event)
{
if (command.equals("Download Music"))
{
downloadMusic();
}
}
public void addMp3()
{
MP3 mp3 = new MP3(getWeight(), getPrice(), getModel(), getSize(), getMemory());
gadgets.add(mp3);
}
public void displayAll()
{
for(Gadget gadget : gadgets)
{
gadget.print();
System.out.println();
}
}
public void downloadMusic()
{
}
public int getDisplay()
{
int gadgetDisplay = 0;
try
{
gadgetDisplay = Integer.parseInt(displayText.getText());
if (gadgetDisplay<= 0)
{
JOptionPane.showMessageDialog
(frame, "Please enter a positive amount");
}
}
catch(NumberFormatException exception)
{
JOptionPane.showMessageDialog
(frame, "Please enter a positive amount");
}
return gadgetDisplay;
}
public String getDownload()
{
String gadgetDownload;
gadgetDownload = downloadText.getText();
return gadgetDownload;
}
}
This is the MP3 class
public class MP3 extends Gadget
{
private int memory;
public MP3(int theWeight, double thePrice, String theModel, String theSize, int theMemory)
{
super(theWeight,thePrice, theModel, theSize);
memory = theMemory;
}
public void downloadMusic(String music, int MusicSize)
{
if(MusicSize>memory)
//if statement saying if size is greater than memory then display the follwing statemnt saying there is not enough memory
{
System.out.println("Not Enough Memory");
}
else
// else statement opposite to the above statement saying if music size is less than or equal to the memory display the following statement
{
memory = memory - MusicSize;
System.out.println("Download Successfull. "+ "\nMusic Name: "+ music + "\nMemory Left: " + memory);
}
}
The "other class" (with the button) must have an instance of the class with the method you want to call. You could create an instance of MP3 in the constructor of GadgetShop and store it as an instance variable. Then in your button listener call
mp3Instance.downloadMusic("music", 42);

Is it possible to write your own objects that give out ActionEvents?

I've looked at the java tutorials online and they all seem concerned with catching ActionEvents given out by other components that are already written. Is it possible to write your own objects that have there own set of criteria that trigger actionEvents that can then be caught by other classes that have registered as listeners?
So for example: If I wanted an object that was counting sheep to send out an actionEvent when 100 sheep had been counted to all the sleeper objects that had registered as listeners.
Is there a way to do this are there any tutorials online?
Any help is greatly appreciated.
Yes, it's pretty straightforward, once someone shows you how to create your own listeners.
First, you create your own EventObject. Here's an example from one of my projects.
import gov.bop.rabid.datahandler.bean.InmateDataBean;
import java.util.EventObject;
public class InmatePhotoEventObject extends EventObject {
private static final long serialVersionUID = 1L;
protected InmateDataBean inmate;
public InmatePhotoEventObject(Object source) {
super(source);
}
public InmateDataBean getInmate() {
return inmate;
}
public void setInmate(InmateDataBean inmate) {
this.inmate = inmate;
}
}
There's nothing special about this class, other than it extends EventObject. Your constructor is defined by EventObject, but you can create any methods you want.
Second, you define an EventListener interface.
public interface EventListener {
public void handleEvent(InmatePhotoEventObject eo);
}
You would use the EventObject you created. You can use any method name or names that you want. This is the interface for the code that will be written as a response to the listener.
Third, you write a ListenerHandler. Here's mine from the same project.
import gov.bop.rabid.datahandler.bean.InmateDataBean;
import gov.bop.rabid.datahandler.main.EventListener;
import gov.bop.rabid.datahandler.main.InmatePhotoEventListener;
import gov.bop.rabid.datahandler.main.InmatePhotoEventObject;
import java.util.ArrayList;
import java.util.List;
public class InmatePhotoListenerHandler {
protected List<EventListener> listeners;
public InmatePhotoListenerHandler() {
listeners = new ArrayList<EventListener>();
}
public void addListener(EventListener listener) {
listeners.add(listener);
}
public void removeListener(EventListener listener) {
for (int i = listeners.size() - 1; i >= 0; i--) {
EventListener instance = listeners.get(i);
if (instance.equals(listener)) {
listeners.remove(i);
}
}
}
public void fireEvent(final InmatePhotoEventObject eo,
final InmateDataBean inmate) {
for (int i = 0; i < listeners.size(); i++) {
final EventListener instance = listeners.get(i);
Runnable runnable = new Runnable() {
public void run() {
eo.setInmate(inmate);
instance.handleEvent(eo);
}
};
new Thread(runnable).start();
}
}
public static void main(String[] args) {
System.out.println("This line goes in your DataHandlerMain class "
+ "constructor.");
InmatePhotoListenerHandler handler = new InmatePhotoListenerHandler();
System.out.println("I need you to put the commented method in "
+ "DataHandlerMain so I can use the handler instance.");
// public InmatePhotoListenerHandler getInmatePhotoListenerHandler() {
// return handler;
// }
System.out.println("This line goes in the GUI code.");
handler.addListener(new InmatePhotoEventListener());
System.out.println("Later, when you've received the response from "
+ "the web service...");
InmateDataBean inmate = new InmateDataBean();
inmate.setIntKey(23);
handler.fireEvent(new InmatePhotoEventObject(handler), inmate);
}
}
The main method in this class shows you how you use a ListenerHandler. The rest of the methods in the class are standard. You would use your own EventObject and EventListener.
Yes.
I suggest you look at the java API documentation for ActionEvent and EventListenerList.
I also suggest that you read about the Listener (also called Observer) pattern.

trying to create a switch using if in java

This is a HW problem. I keep getting the following error on screen related to my if(i==3) statement...
"Exception in thread "AWT-EventQueue-1" java.lang.NullPointerException
at ui.panels.ChoicePanel$1.itemStateChanged(ChoicePanel.java:31)"
...Can someone point me in the right direction? Here is my code. Thanks for your time.
package ui.panels;
import java.awt.Choice;
import java.awt.Panel;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import model.Model;
import interfaces.Resettable;
public class ChoicePanel extends Panel implements Resettable{
public int i = 0;
/**
*
*/
private static final long serialVersionUID = 1L;
Model model;
Choice selection;
public ChoicePanel(Model mdl) {
selection = new Choice();
for (String msg : Model.selections) {
selection.add(msg);
}
selection.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if(i==3) {//drop down clicked three times)
System.out.println("PING");
}else{
model.setMessage(selection.getSelectedItem());
//this line is what sends a value to shape that is drawn on screen
//NOT line 36 of GUIDemo.java
//
model.setCurrentShapeType(selection.getSelectedItem());
model.repaint();
++i;
}
}
});
this.add(selection);
}
public void resetComponents() {
//this resets the drop down list selection array to the first choice on the list
selection.select(0);
//this sets selected item in the selection array set in the above line
model.setMessage(selection.getSelectedItem());
//model.repaint();
}
}
I believe you are not initializing model, which would give a NullPointerException when it was first dereferenced.
You did not initialize model. If i is not 3 the else-block will get executed, which contains model.setMessage(...) - but model does not yet "exist".

Categories

Resources