I have have implementaed a plugin project and want to use TestNG tab for runner purpose in this application. I have a solution for JUnit but in TestNG still I am stuck. Please help out from this situation. Kindly find the JUnit configuration tab code in below:
public void createTabs(ILaunchConfigurationDialog dialog, String mode) {
ILaunchConfigurationTab[] tabs = new ILaunchConfigurationTab[] {
new JUnitLaunchConfigurationTab(),
new JavaArgumentsTab(),
new JavaClasspathTab(),
new JavaJRETab(),
new SourceLookupTab(),
new EnvironmentTab(),
new CommonTab()
};
setTabs(tabs);
}
Please suggest.
****First create TestTab.java class by extend AbstractLaunchConfigurationTab******
private ILaunchConfigurationDialog fLaunchConfigurationDialog;
private final TestNGMainTab testngLaunchTab;
private Button runInUIThread;
/**
* Constructor to create a new junit test tab
*/
public TestTab() {
this.testngLaunchTab = new TestNGMainTab();
}
public void createControl(Composite parent) {
testngLaunchTab.createControl(parent);
Composite composite = (Composite) getControl();
createSpacer(composite);
createRunInUIThreadGroup(composite);
}
private void createRunInUIThreadGroup(Composite comp) {
runInUIThread = new Button(comp, SWT.CHECK);
runInUIThread.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
updateLaunchConfigurationDialog();
}
});
runInUIThread.setText(PDEUIMessages.PDEJUnitLaunchConfigurationTab_Run_Tests_In_UI_Thread);
GridDataFactory.fillDefaults().span(2, 0).grab(true, false).applyTo(runInUIThread);
}
private void createSpacer(Composite comp) {
Label label = new Label(comp, SWT.NONE);
GridDataFactory.fillDefaults().span(3, 0).applyTo(label);
}
public void initializeFrom(ILaunchConfiguration config) {
testngLaunchTab.initializeFrom(config);
updateRunInUIThreadGroup(config);
}
private void updateRunInUIThreadGroup(ILaunchConfiguration config) {
boolean shouldRunInUIThread = true;
try {
shouldRunInUIThread = config.getAttribute(IPDELauncherConstants.RUN_IN_UI_THREAD, true);
} catch (CoreException ce) {
}
runInUIThread.setSelection(shouldRunInUIThread);
}
public void performApply(ILaunchConfigurationWorkingCopy config) {
testngLaunchTab.performApply(config);
boolean selection = runInUIThread.getSelection();
config.setAttribute(IPDELauncherConstants.RUN_IN_UI_THREAD, selection);
}
#Override
public String getId() {
return IPDELauncherConstants.TAB_TEST_ID;
}
#Override
public void activated(ILaunchConfigurationWorkingCopy workingCopy) {
testngLaunchTab.activated(workingCopy);
}
#Override
public boolean canSave() {
return testngLaunchTab.canSave();
}
#Override
public void deactivated(ILaunchConfigurationWorkingCopy workingCopy) {
testngLaunchTab.deactivated(workingCopy);
}
#Override
public void dispose() {
testngLaunchTab.dispose();
}
#Override
public String getErrorMessage() {
return testngLaunchTab.getErrorMessage();
}
#Override
public Image getImage() {
return testngLaunchTab.getImage();
}
#Override
public String getMessage() {
return testngLaunchTab.getMessage();
}
public String getName() {
return testngLaunchTab.getName();
}
#Override
public boolean isValid(ILaunchConfiguration config) {
return testngLaunchTab.isValid(config);
}
public void setDefaults(ILaunchConfigurationWorkingCopy config) {
testngLaunchTab.setDefaults(config);
}
#Override
public void setLaunchConfigurationDialog(ILaunchConfigurationDialog dialog) {
testngLaunchTab.setLaunchConfigurationDialog(dialog);
this.fLaunchConfigurationDialog = dialog;
}
*** create Interface ITestNGPluginLauncherConstants*****
public interface ITestNGPluginLauncherConstants {
String LEGACY_UI_TEST_APPLICATION =
"org.testng.eclipse.runtime.legacytestapplication";
String NON_UI_THREAD_APPLICATION =
"org.testng.eclipse.runtime.nonuithreadtestapplication";
String UI_TEST_APPLICATION =
"org.testng.eclipse.runtime.uitestapplication";
String CORE_TEST_APPLICATION =
"org.testng.eclipse.runtime.coretestapplication";
String TestNGProgramBlock_headless = "No application [Headless]";
String TAB_PLUGIN_TESTNG_MAIN_ID =
"org.testng.eclipse.plugin.launch.tab.main";
}
****create class PluginTestNGMainTab.java*****
public class TestNGPluginTabGroup extends
AbstractLaunchConfigurationTabGroup {
public TestNGPluginTabGroup() {
}
public void createTabs(ILaunchConfigurationDialog dialog, String mode) {
ILaunchConfigurationTab[] tabs = new ILaunchConfigurationTab[] {
new TestTab(),
new PluginTestNGMainTab(),
new JavaArgumentsTab(),
new PluginsTab(false),
new JavaArgumentsTab(),
new PluginsTab(),
new TracingTab(),
new ConfigurationTab(true),
new TracingTab(),
new EnvironmentTab(),
new CommonTab()
};
setTabs(tabs);
}
}
**** create class TestNGProgramBlock.java extends ProgramBlock*****
public TestNGProgramBlock(AbstractLauncherTab tab) {
super(tab);
}
public void setDefaults(ILaunchConfigurationWorkingCopy config) {
if (!LauncherUtils.requiresUI(config))
config.setAttribute(IPDELauncherConstants.APPLICATION,
ITestNGPluginLauncherConstants.CORE_TEST_APPLICATION);
else
super.setDefaults(config);
}
protected String[] getApplicationNames() {
TreeSet result = new TreeSet();
result.add(ITestNGPluginLauncherConstants.TestNGProgramBlock_headless);
String[] appNames = super.getApplicationNames();
for (int i = 0; i < appNames.length; i++) {
result.add(appNames[i]);
}
return appNames;
}
protected void initializeApplicationSection(ILaunchConfiguration config)
throws CoreException {
String application =
config.getAttribute(IPDELauncherConstants.APPLICATION, (String)null);
if(ITestNGPluginLauncherConstants.CORE_TEST_APPLICATION.
equals(application))
fApplicationCombo.setText(ITestNGPluginLauncherConstants.
TestNGProgramBlock_headless);
else
super.initializeApplicationSection(config);
}
protected void saveApplicationSection(ILaunchConfigurationWorkingCopy config)
{
if(fApplicationCombo.getText().equals(ITestNGPluginLauncherConstants.
TestNGPogramBlock_headless)){
String appName = fApplicationCombo.isEnabled() ?
ITestNGPluginLauncherConstants.CORE_TEST_APPLICATION : null;
config.setAttribute(IPDELauncherConstants.APPLICATION, appName);
config.setAttribute(IPDELauncherConstants.APP_TO_TEST, (String)null);
}
}
}
Related
I have edited the question as your suggestions but null pointer exception is caught.I used connectionRequest instead of multipartRequest since i dont need to upload(just need to read the value frm json). All my codes below, please have a look.
Edited: exception
java.lang.NullPointerException
at userclasses.StateMachine$16.readResponse(StateMachine.java:1834)
at com.codename1.io.ConnectionRequest.performOperation(ConnectionRequest.java:438)
at com.codename1.io.NetworkManager$NetworkThread.run(NetworkManager.java:263)
at com.codename1.impl.CodenameOneThread.run(CodenameOneThread.java:176)
Code:
#Override
protected void beforeImgGallery(Form f) {
int iter = 0;
GridLayout gr = new GridLayout(1, 1);
Container grid = new Container(gr);
gr.setAutoFit(true);
grid.setScrollableY(true);
grid.addComponent(new InfiniteProgress());
f.addComponent(BorderLayout.CENTER, grid);
f.removeAllCommands();
f.setBackCommand(null);
createPictureCommand(grid);
}
private static boolean animating;
private Vector<Map<String, Object>> responsesgallery;
String galleryPhotoUrl;
private void createPictureCommand(final Container grid) {
ConnectionRequest mp = new ConnectionRequest(){
#Override
protected void readResponse(InputStream input) throws IOException {
JSONParser p = new JSONParser();
results = p.parse(new InputStreamReader(input));
responsesgallery = (Vector<Map<String, Object>>) results.get("data");
//i've kept this for loop in postResponse but same error
for (int i = 0; i < responsesgallery.size(); i++) {
//null pointer exception in this line
final Button btn = createImageButton(i, grid, imageList.getSize());
//if i simply create a btn like below, it works
// final Button btn = new Button((URLImage.createToStorage(placeholder, token, galleryPhotoUrl, URLImage.RESIZE_SCALE_TO_FILL)));
imageList.addImageId(i);
grid.addComponent(i, btn);
Hashtable hm = (Hashtable) responsesgallery.get(i);
String galleryImgId = (String) hm.get("news_id");
galleryPhotoUrl = (String) hm.get("photo");
}
}
};
mp.setUrl("http://capitaleyedevelopment.com/~admin/traffic/api/news/getLatestNews");
NetworkManager.getInstance().addToQueueAndWait(mp);
}
ImageList imageList;
Button createImageButton(final int imageId, final Container grid, final int offset) {
final Button btn = new Button(URLImage.createToStorage(placeholder, token, galleryPhotoUrl, URLImage.RESIZE_SCALE_TO_FILL));
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
imageList.setSelectedIndex(offset);
final Container viewerParent = new Container(new LayeredLayout());
ImageViewer viewer = new ImageViewer(imageList.getItemAt(offset));
viewerParent.addComponent(viewer);
Container parent = new Container(new BorderLayout());
viewerParent.addComponent(parent);
viewer.setImageList(imageList);
grid.getParent().replace(grid, viewerParent, CommonTransitions.createSlide(CommonTransitions.SLIDE_HORIZONTAL, false, 300));
Display.getInstance().getCurrent().setBackCommand(createBackCommand(viewerParent, grid));
}
});
return btn;
}
public static final String SERVER_URL = "http://capitaleyedevelopment.com/~admin/traffic/api/news/getLatestNews";
class ImageList implements ListModel<Image> {
private int selection;
private long[] imageIds;
private EncodedImage[] images;
private EventDispatcher listeners = new EventDispatcher();
public void addImageId(int id) {
long[] n = new long[imageIds.length + 1];
EncodedImage[] nImages = new EncodedImage[n.length];
System.arraycopy(imageIds, 0, n, 0, imageIds.length);
System.arraycopy(images, 0, nImages, 0, images.length);
n[imageIds.length] = id;
imageIds = n;
images = nImages;
listeners.fireDataChangeEvent(-1, DataChangedListener.ADDED);
}
public long getSelectedImageId() {
return imageIds[selection];
}
public ImageList(long[] images) {
this.imageIds = images;
this.images = new EncodedImage[images.length];
}
public Image getItemAt(final int index) {
if (images[index] == null) {
images[index] = placeholder;
Util.downloadUrlToStorageInBackground(IMAGE_URL_PREFIX + imageIds[index], "FullImage_" + imageIds[index], new ActionListener() {
public void actionPerformed(ActionEvent evt) {
try {
images[index] = EncodedImage.create(Storage.getInstance().createInputStream("FullImage_" + imageIds[index]));
listeners.fireDataChangeEvent(index, DataChangedListener.CHANGED);
} catch (IOException err) {
err.printStackTrace();
}
}
});
}
return images[index];
}
public int getSize() {
return imageIds.length;
}
public int getSelectedIndex() {
return selection;
}
public void setSelectedIndex(int index) {
WebServiceProxy.getPhotoLikesAsync(imageIds[selection], new Callback<Integer>() {
public void onSucess(Integer value) {
}
public void onError(Object sender, Throwable err, int errorCode, String errorMessage) {
}
});
selection = index;
}
public void addDataChangedListener(DataChangedListener l) {
listeners.addListener(l);
}
public void removeDataChangedListener(DataChangedListener l) {
listeners.removeListener(l);
}
public void addSelectionListener(SelectionListener l) {
}
public void removeSelectionListener(SelectionListener l) {
}
public void addItem(Image item) {
}
public void removeItem(int index) {
}
}
In the Photo Share demo (that's on github) I demonstrate something pretty similar. I used a custom list model that fetches the images to the ImageViewer dynamically.
The interesting bit is this list model where the images are downloaded dynamically as needed:
class ImageList implements ListModel<Image> {
private int selection;
private long[] imageIds;
private EncodedImage[] images;
private EventDispatcher listeners = new EventDispatcher();
public void addImageId(long id) {
long[] n = new long[imageIds.length + 1];
EncodedImage[] nImages = new EncodedImage[n.length];
System.arraycopy(imageIds, 0, n, 0, imageIds.length);
System.arraycopy(images, 0, nImages, 0, images.length);
n[imageIds.length] = id;
imageIds = n;
images = nImages;
listeners.fireDataChangeEvent(-1, DataChangedListener.ADDED);
}
public long getSelectedImageId() {
return imageIds[selection];
}
public ImageList(long[] images) {
this.imageIds = images;
this.images = new EncodedImage[images.length];
}
public Image getItemAt(final int index) {
if(images[index] == null) {
images[index] = placeholder;
Util.downloadUrlToStorageInBackground(IMAGE_URL_PREFIX + imageIds[index], "FullImage_" + imageIds[index], new ActionListener() {
public void actionPerformed(ActionEvent evt) {
try {
images[index] = EncodedImage.create(Storage.getInstance().createInputStream("FullImage_" + imageIds[index]));
listeners.fireDataChangeEvent(index, DataChangedListener.CHANGED);
} catch(IOException err) {
err.printStackTrace();
}
}
});
}
return images[index];
}
public int getSize() {
return imageIds.length;
}
public int getSelectedIndex() {
return selection;
}
public void setSelectedIndex(int index) {
WebServiceProxy.getPhotoLikesAsync(imageIds[selection], new Callback<Integer>() {
public void onSucess(Integer value) {
if(likeCount != null) {
likeCount.setText("" + value);
likeCount.getParent().revalidate();
}
}
public void onError(Object sender, Throwable err, int errorCode, String errorMessage) {
}
});
selection = index;
}
public void addDataChangedListener(DataChangedListener l) {
listeners.addListener(l);
}
public void removeDataChangedListener(DataChangedListener l) {
listeners.removeListener(l);
}
public void addSelectionListener(SelectionListener l) {
}
public void removeSelectionListener(SelectionListener l) {
}
public void addItem(Image item) {
}
public void removeItem(int index) {
}
}
Here is my code:
public APJMenu createMenu(String menuLabel, String[] menuItems) {
// create menu item with passed in title
APJMenu menu = new APJMenu(menuLabel, getSoundFileName(menuLabel),
this.audioSourceType);
APJMenuItem menuItem;
for (int i = 0; i < menuItems.length; i++) {
menuItem = new APJMenuItem(menuItems[i],
getSoundFileName(menuItems[i]), audioSourceType);
menuItem.setEnabled(true);
menuItem.addActionListener(this);
menuItem.addMenuKeyListener(this);
menuItem.setActionCommand(menuItems[i]);
menu.add(menuItem);
}
return menu;
}
This is what the Main program basically does. This is where all of the audio files are added to the menus which enables audio playback. However, there is also a referenced JAR file that communicates with the program and that actually reads in the text and makes the calls to play the corresponding audio file. If you run the program, you will generate a menu that plays audio as you navigate the item list.
APJMenuItem class
// Referenced classes of package enhancedWidgets: APComponent, APComponentGenerics, APJFrame
public class APJMenuItem extends JMenuItem
implements APComponent, MouseListener, MenuKeyListener {
public APJMenuItem(String label) {
super(label);
type = DEFAULT_SOUND_TYPE;
visuals_enabled = true;
init(soundTypes.Sound.SoundType.Spearcon, label, null);
}
public APJMenuItem(String label, String filename, soundTypes.Sound.SoundType type) {
super(label);
this.type = DEFAULT_SOUND_TYPE;
visuals_enabled = true;
init(type, label, filename);
}
private void init(soundTypes.Sound.SoundType type, String label, String filename) {
this.type = type;
switch($SWITCH_TABLE$soundTypes$Sound$SoundType()[type.ordinal()]) {
case 5: // '\005'
sound = new Spearcon(label, null);
break;
case 1: // '\001'
case 3: // '\003'
sound = new AuditoryIcon(new File(filename));
break;
case 2: // '\002'
case 4: // '\004'
default:
sound = null;
break;
}
addMouseListener(this);
addMenuKeyListener(this);
}
public void setText(String text) {
super.setText(text);
if(type == null)
type = DEFAULT_SOUND_TYPE;
init(type, text, null);
}
public void setFile(String filename) {
init(soundTypes.Sound.SoundType.SoundFile, getText(), filename);
}
public void findSoundListener() {
APComponentGenerics.findSoundListener(listener, this);
sound.setSoundListener(listener);
}
public void updateSoundListener(APJFrame frame) {
listener = APComponentGenerics.updateSoundListener(frame);
sound.setSoundListener(listener);
}
public boolean hasSoundListener() {
return APComponentGenerics.hasSoundListener(listener);
}
public APComponent.ComponentType getComponentType() {
return APComponent.ComponentType.menuitem;
}
public boolean isAPComponent() {
return true;
}
public void mouseClicked(MouseEvent mouseevent) {
}
public void mousePressed(MouseEvent mouseevent) {
}
public void mouseReleased(MouseEvent mouseevent) {
}
public void mouseExited(MouseEvent e) {
sound.stop();
}
public void mouseEntered(MouseEvent e) {
if(!hasSoundListener())
findSoundListener();
(new Thread(sound)).start();
}
public void menuKeyPressed(MenuKeyEvent e) {
if(isArmed() && !sound.isStopped())
sound.stop();
}
public void menuKeyReleased(MenuKeyEvent e) {
if(isArmed()) {
if(!hasSoundListener())
findSoundListener();
(new Thread(sound)).start();
}
}
public void menuKeyTyped(MenuKeyEvent menukeyevent) {
}
public void setVisualsEnabled(boolean enabled) {
visuals_enabled = enabled;
}
public boolean isVisualsEnabled() {
return visuals_enabled;
}
protected void paintComponent(Graphics g) {
if(isVisualsEnabled())
super.paintComponent(g);
}
static int[] $SWITCH_TABLE$soundTypes$Sound$SoundType() {
$SWITCH_TABLE$soundTypes$Sound$SoundType;
if($SWITCH_TABLE$soundTypes$Sound$SoundType == null) goto _L2; else goto _L1
_L1:
return;
_L2:
JVM INSTR pop ;
int ai[] = new int[soundTypes.Sound.SoundType.values().length];
try {
ai[soundTypes.Sound.SoundType.AuditoryIcon.ordinal()] = 1;
}
catch(NoSuchFieldError _ex) { }
try {
ai[soundTypes.Sound.SoundType.Earcon.ordinal()] = 2;
}
catch(NoSuchFieldError _ex) { }
try {
ai[soundTypes.Sound.SoundType.Other.ordinal()] = 6;
}
catch(NoSuchFieldError _ex) { }
try {
ai[soundTypes.Sound.SoundType.SoundFile.ordinal()] = 3;
}
catch(NoSuchFieldError _ex) { }
try {
ai[soundTypes.Sound.SoundType.SoundScape.ordinal()] = 4;
}
catch(NoSuchFieldError _ex) { }
try {
ai[soundTypes.Sound.SoundType.Spearcon.ordinal()] = 5;
}
catch(NoSuchFieldError _ex) { }
return $SWITCH_TABLE$soundTypes$Sound$SoundType = ai;
}
private static final long serialVersionUID = 0x77c71df3L;
Sound sound;
SoundListener listener;
private static soundTypes.Sound.SoundType DEFAULT_SOUND_TYPE;
soundTypes.Sound.SoundType type;
private boolean visuals_enabled;
private static int $SWITCH_TABLE$soundTypes$Sound$SoundType[];
static {
DEFAULT_SOUND_TYPE = soundTypes.Sound.SoundType.Spearcon;
}
}
APJMenu class
// Referenced classes of package enhancedWidgets:
// APComponent, APComponentGenerics, APJMenuItem, APJFrame
public class APJMenu extends JMenu
implements MouseListener, MenuListener, APComponent, MenuKeyListener {
public APJMenu(String label) {
super(label);
listener = null;
frame = null;
visuals_enabled = true;
init(soundTypes.Sound.SoundType.Spearcon, label, null);
}
public APJMenu(String label, String filename, soundTypes.Sound.SoundType type) {
super(label);
listener = null;
frame = null;
visuals_enabled = true;
init(type, label, filename);
}
private void init(soundTypes.Sound.SoundType type, String label, String filename) {
this.type = type;
switch($SWITCH_TABLE$soundTypes$Sound$SoundType()[type.ordinal()]) {
case 5: // '\005'
sound = new Spearcon(label, null);
break;
case 1: // '\001'
case 3: // '\003'
sound = new AuditoryIcon(new File(filename));
break;
case 2: // '\002'
case 4: // '\004'
default:
sound = null;
break;
}
addMouseListener(this);
addMenuListener(this);
}
public void findSoundListener() {
APComponentGenerics.findSoundListener(listener, this);
sound.setSoundListener(listener);
}
public void updateSoundListener() {
findSoundListener();
}
public boolean hasSoundListener() {
return APComponentGenerics.hasSoundListener(listener);
}
public void updateSoundListener(APJFrame frame) {
listener = APComponentGenerics.updateSoundListener(frame);
this.frame = frame;
sound.setSoundListener(listener);
}
public void add(APJMenuItem menuItem) {
super.add(menuItem);
menuItem.updateSoundListener(frame);
menuItem.addMenuKeyListener(this);
}
public void add(APJMenu menu) {
super.add(menu);
menu.updateSoundListener(frame);
}
public APComponent.ComponentType getComponentType() {
return APComponent.ComponentType.menu;
}
public boolean isAPComponent() {
return true;
}
public void menuCanceled(MenuEvent e) {
if(!sound.isStopped())
sound.stop();
}
public void menuDeselected(MenuEvent e) {
if(!sound.isStopped())
sound.stop();
}
public void menuSelected(MenuEvent e) {
if(!hasSoundListener())
findSoundListener();
if(!sound.isStopped())
sound.stop();
(new Thread(sound)).start();
(new Thread(sound)).start();
}
public void mouseClicked(MouseEvent mouseevent) {
}
public void mousePressed(MouseEvent mouseevent) {
}
public void mouseReleased(MouseEvent mouseevent) {
}
public void mouseExited(MouseEvent e) {
sound.stop();
}
public void mouseEntered(MouseEvent e) {
if(!hasSoundListener())
findSoundListener();
(new Thread(sound)).start();
}
public void menuKeyPressed(MenuKeyEvent e) {
if(!sound.isStopped())
sound.stop();
}
public void menuKeyReleased(MenuKeyEvent menukeyevent) {
}
public void menuKeyTyped(MenuKeyEvent menukeyevent) {
}
public void setVisualsEnabled(boolean enabled) {
visuals_enabled = enabled;
}
public boolean isVisualsEnabled() {
return visuals_enabled;
}
protected void paintComponent(Graphics g) {
if(isVisualsEnabled())
super.paintComponent(g);
}
static int[] $SWITCH_TABLE$soundTypes$Sound$SoundType() {
$SWITCH_TABLE$soundTypes$Sound$SoundType;
if($SWITCH_TABLE$soundTypes$Sound$SoundType == null) goto _L2; else goto _L1
_L1:
return;
_L2:
JVM INSTR pop ;
int ai[] = new int[soundTypes.Sound.SoundType.values().length];
try {
ai[soundTypes.Sound.SoundType.AuditoryIcon.ordinal()] = 1;
}
catch(NoSuchFieldError _ex) { }
try {
ai[soundTypes.Sound.SoundType.Earcon.ordinal()] = 2;
}
catch(NoSuchFieldError _ex) { }
try {
ai[soundTypes.Sound.SoundType.Other.ordinal()] = 6;
}
catch(NoSuchFieldError _ex) { }
try {
ai[soundTypes.Sound.SoundType.SoundFile.ordinal()] = 3;
}
catch(NoSuchFieldError _ex) { }
try {
ai[soundTypes.Sound.SoundType.SoundScape.ordinal()] = 4;
}
catch(NoSuchFieldError _ex) { }
try {
ai[soundTypes.Sound.SoundType.Spearcon.ordinal()] = 5;
}
catch(NoSuchFieldError _ex) { }
return $SWITCH_TABLE$soundTypes$Sound$SoundType = ai;
}
private static final long serialVersionUID = 0xf123a728L;
Sound sound;
SoundListener listener;
APJFrame frame;
soundTypes.Sound.SoundType type;
private boolean visuals_enabled;
private static int $SWITCH_TABLE$soundTypes$Sound$SoundType[];
}
Sound class
package soundTypes;
import soundServer.SoundListener;
public abstract class Sound
implements Runnable {
/* member class not found */
class SoundType {}
public Sound() {
}
public abstract void play();
public abstract void stop();
public abstract SoundType getSoundType();
public boolean isAuditoryIcon() {
return false;
}
public boolean isEarcon() {
return false;
}
public boolean isSoundFile() {
return false;
}
public boolean isSoundScape() {
return false;
}
public boolean isSpearcon() {
return false;
}
public boolean isOther() {
return false;
}
public abstract boolean isStopped();
public boolean isMenuSound(Sound s) {
return s.isAuditoryIcon() || s.isEarcon() || s.isSpearcon();
}
public void setSoundListener(SoundListener listener) {
this.listener = listener;
}
protected SoundListener listener;
}
SoundFile class
package soundTypes;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import javax.sound.sampled.*;
import soundServer.StopWatch;
// Referenced classes of package soundTypes:
// Sound
public class SoundFile extends Sound {
public SoundFile(File file) {
stopped = true;
continuous = false;
gainControl = null;
playFrequency = 1.0D;
this.file = null;
volume = 0.0D;
second = false;
initialize(file);
}
private void initialize(File file) {
this.file = file;
try {
stream = AudioSystem.getAudioInputStream(file);
AudioFormat format = stream.getFormat();
if(format.getEncoding() != javax.sound.sampled.AudioFormat.Encoding.PCM_SIGNED) {
format = new AudioFormat(javax.sound.sampled.AudioFormat.Encoding.PCM_SIGNED, format.getSampleRate(), format.getSampleSizeInBits(), format.getChannels(), format.getFrameSize(), format.getFrameRate(), true);
stream = AudioSystem.getAudioInputStream(format, stream);
}
javax.sound.sampled.DataLine.Info info = new javax.sound.sampled.DataLine.Info(javax/sound/sampled/Clip, stream.getFormat(), (int)stream.getFrameLength() * format.getFrameSize());
clip = (Clip)AudioSystem.getLine(info);
try {
gainControl = (FloatControl)clip.getControl(javax.sound.sampled.FloatControl.Type.MASTER_GAIN);
}
catch(IllegalArgumentException exception) {
gainControl = null;
}
}
catch(MalformedURLException e) {
e.printStackTrace();
}
catch(IOException e) {
e.printStackTrace();
}
catch(LineUnavailableException e) {
e.printStackTrace();
}
catch(UnsupportedAudioFileException e) {
e.printStackTrace();
}
}
public long getClipLengthMS() {
boolean wasOpen = clip.isOpen();
if(!wasOpen)
try {
clip.open(stream);
}
catch(LineUnavailableException e) {
e.printStackTrace();
}
catch(IOException e) {
e.printStackTrace();
}
long length = clip.getMicrosecondLength();
if(!wasOpen)
clip.close();
return length;
}
public void setVolume(double percent) {
if(gainControl == null) {
return;
} else {
volume = percent;
float dB = (float)((Math.log(percent) / Math.log(10D)) * 20D);
gainControl.setValue(dB);
return;
}
}
public void setContiuous(boolean continuous) {
this.continuous = continuous;
if(this.continuous)
clip.loop(-1);
else
clip.loop(0);
}
public void play() {
second = !second;
if(!second)
return;
stopped = false;
try {
clip.stop();
clip.close();
initialize(file);
clip.open(stream);
clip.start();
}
catch(LineUnavailableException e) {
e.printStackTrace();
}
catch(IOException e) {
e.printStackTrace();
}
StopWatch watch = new StopWatch();
watch.start();
while(!stopped) ;
clip.stop();
}
public void stop() {
stopped = true;
}
public void run() {
play();
}
public double getPlayFrequency() {
return playFrequency;
}
public void setPlayFrequency(double playFrequency) {
this.playFrequency = playFrequency;
}
public boolean isStopped() {
return stopped;
}
public SoundFile clone() {
SoundFile clone = new SoundFile(getFile());
clone.setContiuous(continuous);
clone.setPlayFrequency(playFrequency);
clone.setVolume(volume);
return clone;
}
public File getFile() {
return file;
}
public Sound.SoundType getSoundType() {
return Sound.SoundType.SoundFile;
}
public boolean isSoundFile() {
return true;
}
public volatile Object clone()
throws CloneNotSupportedException {
return clone();
}
boolean stopped;
boolean continuous;
FloatControl gainControl;
Clip clip;
AudioInputStream stream;
double playFrequency;
File file;
double volume;
boolean second;
}
The issue I am having is whenever you go to the next item (audio file) in the menu, the previous audio file doesn't stop (I NEED IT TO STOP!). I literally have no idea how to fix this as I cannot edit the files inside the jar.
I have uploaded all of the files here: https://drive.google.com/file/d/0Bz9A-abBN69HSG1yRjFrWFNxQXc/view?usp=sharing
so that you can see what I'm talking about.
-
KEY INFORMATION:
In order to run the Main program, you need to:
Run the file named "MenuDriver_SPT"
To navigate the menu system within the application:
On a Mac - Hold down OPTION and press SPACE BAR
On a Windows - Hold down ALT and press SPACE BAR
You then navigate the menu using the arrow keys
If you import the file system into eclipse, it should run without any problems.
Again the files are here: https://drive.google.com/file/d/0Bz9A-abBN69HSG1yRjFrWFNxQXc/view?usp=sharing
I am using swingworker to run a method in the background and periodically update the gui with information, but from what I've found publish can't be called from another class. Here's where my Swingworker is called:
private void start() {
worker = new SwingWorker <Void, String>() {
#Override
protected Void doInBackground() throws Exception {
navigator.navigator();
return null;
}
#Override
protected void process(List<String> chunks) {
for (String line : chunks) {
txtrHello.append(line);
txtrHello.append("\n");
}
}
#Override
protected void done() {
}
};
worker.execute();
}
And now from the navigator method I want to call publish(String);, how would I do this? Moving all of my methods into doInBackground() would be impossible.
Possible solution is to add an observer to your Navigator object, the key being to somehow allow the Navigator to communicate with any listener (here the SwingWorker) that its state has changed:
Give Navigator a PropertyChangeSupport object as well as an addPropertyChangeListener(PropertyChangeListener listener) method that adds the passed in listener to the support object.
Give Navigator some type of "bound" property, a field that when its state is changed, often in a setXxxx(...) type method, notifies the support object of this change.
Then in your SwingWorker constructor, add a PropertyChangeListener to your Navigator object.
In this listener, call the publish method with the new data from your Navigator object.
For example:
import java.awt.event.ActionEvent;
import java.beans.*;
import java.util.List;
import javax.swing.*;
#SuppressWarnings("serial")
public class PropChangeSupportEg extends JPanel {
private MyNavigator myNavigator = new MyNavigator();
private JTextField textField = new JTextField(10);
public PropChangeSupportEg() {
textField.setFocusable(false);
add(textField);
add(new JButton(new StartAction("Start")));
add(new JButton(new StopAction("Stop")));
}
private class StartAction extends AbstractAction {
public StartAction(String name) {
super(name);
}
#Override
public void actionPerformed(ActionEvent e) {
if (myNavigator.isUpdatingText()) {
return; // it's already running
}
MyWorker worker = new MyWorker();
worker.execute();
}
}
private class StopAction extends AbstractAction {
public StopAction(String name) {
super(name);
}
#Override
public void actionPerformed(ActionEvent e) {
myNavigator.stop();
}
}
private class MyWorker extends SwingWorker<Void, String> {
#Override
protected Void doInBackground() throws Exception {
if (myNavigator.isUpdatingText()) {
return null;
}
myNavigator.addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent evt) {
if (MyNavigator.BOUND_PROPERTY_TEXT.equals(evt.getPropertyName())) {
publish(evt.getNewValue().toString());
}
}
});
myNavigator.start();
return null;
}
#Override
protected void process(List<String> chunks) {
for (String chunk : chunks) {
textField.setText(chunk);
}
}
}
private static void createAndShowGui() {
PropChangeSupportEg mainPanel = new PropChangeSupportEg();
JFrame frame = new JFrame("Prop Change Eg");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class MyNavigator {
public static final String BOUND_PROPERTY_TEXT = "bound property text";
public static final String UPDATING_TEXT = "updating text";
private static final long SLEEP_TIME = 1000;
private PropertyChangeSupport pcSupport = new PropertyChangeSupport(this);
private String boundPropertyText = "";
private String[] textArray = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};
private int textArrayIndex = 0;
private volatile boolean updatingText = false;
public void start() {
if (updatingText) {
return;
}
updatingText = true;
while (updatingText) {
textArrayIndex++;
textArrayIndex %= textArray.length;
setBoundPropertyText(textArray[textArrayIndex]);
try {
Thread.sleep(SLEEP_TIME);
} catch (InterruptedException e) {}
}
}
public void stop() {
setUpdatingText(false);
}
public String getBoundPropertyText() {
return boundPropertyText;
}
public boolean isUpdatingText() {
return updatingText;
}
public void setUpdatingText(boolean updatingText) {
boolean oldValue = this.updatingText;
boolean newValue = updatingText;
this.updatingText = updatingText;
pcSupport.firePropertyChange(UPDATING_TEXT, oldValue, newValue);
}
public void setBoundPropertyText(String boundPropertyText) {
String oldValue = this.boundPropertyText;
String newValue = boundPropertyText;
this.boundPropertyText = boundPropertyText;
pcSupport.firePropertyChange(BOUND_PROPERTY_TEXT, oldValue, newValue);
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
pcSupport.addPropertyChangeListener(listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
pcSupport.removePropertyChangeListener(listener);
}
}
I am trying to build a simple Java application with SWT using the MVC pattern. I would like to be able to automatically update the view when something happens in the background so I am trying to use the Observer/Observable pattern, but it looks like my Observer is never notified when my Observable changes.
Here is the code:
Launcher.java (main class)
public class Launcher {
public static void main(String[] args) {
Application app = new Application();
PenguinView v = new PenguinView(app);
Controller api = new Controller(app, v);
}
}
Application.java (The background application)
public class Application {
private Penguin _myPenguin;
public Application() {
_myPenguin = new Penguin();
new Thread(_myPenguin).start();
}
public Penguin getPenguin() {
return _myPenguin;
}
}
Penguin.java (The model, my Observable)
public class Penguin extends Observable implements Runnable {
private String _color;
private boolean _isHappy;
private int _myRocks;
public Penguin() {
_color = "Black";
_isHappy = true;
_myRocks = 0;
}
public void paint(String color) {
_color = color;
System.out.println("My new color is " + _color);
setChanged();
notifyObservers();
}
public String getColor() {
return _color;
}
public void upset() {
_isHappy = false;
setChanged();
notifyObservers();
}
public void cheerUp() {
_isHappy = true;
setChanged();
notifyObservers();
}
public boolean isHappy() {
return _isHappy;
}
public void run() {
// Penguin starts walking and find rocks!
while(true) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
iFoundRock();
}
}
private void iFoundRock() {
_myRocks++;
System.out.println("I now have " + _myRocks + " rocks");
setChanged();
notifyObservers();
}
}
PenguinView.java (The SWT View, my observer)
public class PenguinView implements Observer {
private Application _app;
private Display _d;
private Shell _s;
private Label _penguinColor;
private Label _penguinHumor;
private Label _penguinRocks;
private Button _upset;
private Button _cheerUp;
private Text _newColor;
private Button _paint;
public PenguinView(Application app) {
_app = app;
_d = new Display();
_s = new Shell();
RowLayout rl = new RowLayout();
rl.marginWidth = 12;
rl.marginHeight = 12;
_s.setLayout(rl);
new Label(_s, SWT.BORDER).setText("Penguin Color: ");
_penguinColor = new Label(_s, SWT.BORDER);
_penguinColor.setText(_app.getPenguin().getColor());
new Label(_s, SWT.BORDER).setText(" Humor: ");
_penguinHumor = new Label(_s, SWT.BORDER);
String humor = _app.getPenguin().isHappy() ? "Happy" : "Sad";
_penguinHumor.setText(humor);
new Label(_s, SWT.BORDER).setText(" Rocks: ");
_penguinRocks = new Label(_s, SWT.BORDER);
_penguinRocks.setText(String.valueOf(_app.getPenguin().howManyRocks()));
_upset = new Button(_s, SWT.PUSH);
_upset.setText(":(");
_upset.addListener(SWT.Selection, new Listener(){
public void handleEvent(Event e) {
_penguinHumor.setText("Sad");
}
});
_cheerUp = new Button(_s, SWT.PUSH);
_cheerUp.setText(":)");
_cheerUp.addListener(SWT.Selection, new Listener(){
public void handleEvent(Event e) {
_penguinHumor.setText("Happy");
}
});
_newColor = new Text(_s, SWT.BORDER);
_paint = new Button(_s, SWT.PUSH);
_paint.setText("Paint!");
_paint.addListener(SWT.Selection, new Listener(){
public void handleEvent(Event e) {
//_penguinColor.setText(_newColor.getText());
_app.getPenguin().paint(_newColor.getText());
}
});
_s.pack();
_s.open();
while (!_d.isDisposed()) {
if (!_d.readAndDispatch()) {
_d.sleep();
}
}
}
public void update(Observable obs, Object obj) {
System.out.println("I go here!");
_penguinRocks.setText(String.valueOf(((Penguin)obs).howManyRocks()));
if(obs.equals(_app.getPenguin())) {
_penguinRocks.setText(String.valueOf(((Penguin)obs).howManyRocks()));
}
}
public void update(Observable obs) {
System.out.println("I go there!");
}
Controller.java (The controller)
public class Controller {
Application _app;
PenguinView _v;
public Controller(Application app, PenguinView v) {
_app = app;
_v = v;
// Set observer
_app.getPenguin().addObserver(_v);
}
}
The output:
I now have 1 rocks
I now have 2 rocks
My new color is Blue
I now have 3 rocks
I now have 4 rocks
Do you have any idea of what I am doing wrong?
Thanks!
From what I can tell, the while loop in the PenguinView constructor is blocking your main thread, so the Controller never gets instantiated and the observer is never added.
I have a simple list field class which shows the default menu when I select a particular listitem. I want to customize the listfield item, so that when an item is selected a new screen is pushed onto the stack. I am overridding trackwheeel() method, but am not able to make it work.
import net.rim.device.api.system.*;
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.container.*;
import java.util.Vector;
public class TeamListScreen extends UiApplication
{
public static void main(String[] args)
{
TeamListScreen theApp = new TeamListScreen();
theApp.enterEventDispatcher();
}
public TeamListScreen()
{
pushScreen(new ListFieldScreen());
}
}
class ListFieldScreen extends MainScreen
{
private ListField _listField;
private Vector _listElements;
int listFieldIndex = -1;
public ListFieldScreen()
{
setTitle("List Field Sample");
_listElements = new Vector();
_listField = new ListField();
ListCallback _callback = new ListCallback();
_listField.setCallback(_callback);
_listField.setRowHeight(45);
//_listField.setChangeListener(this);
add(_listField);
initializeList();
_listField = new ListField(_listElements.size()) {
protected void drawFocus(Graphics graphics, boolean on) {
}
protected boolean trackwheelClick(int status, int time) {
listFieldIndex = _listField.getSelectedIndex();
if (listFieldIndex < 0) {
listFieldIndex = 0;
}
try {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
UiApplication.getUiApplication().pushScreen(new LiveScreen());
// UiApplication.getUiApplication().popScreen(getActiveScreen());
}
});
} catch (Exception e) {
}
return true;
}
};
}
private void initializeList()
{
String itemOne = "List item one";
String itemTwo = "List item two";
_listElements.addElement(itemOne);
_listElements.addElement(itemTwo);
reloadList();
}
private void reloadList()
{
_listField.setSize(_listElements.size());
}
private class ListCallback implements ListFieldCallback
{
public void drawListRow(ListField list, Graphics g, int index, int y, int w)
{
String text = (String)_listElements.elementAt(index);
g.drawText(text, 0, y, 0, w);
}
public Object get(ListField list, int index)
{
return _listElements.elementAt(index);
}
public int indexOfList(ListField list, String prefix, int string)
{
return _listElements.indexOf(prefix, string);
}
public int getPreferredWidth(ListField list)
{
return Display.getWidth();
}
}
}
trackwheelClick() function is deprecated, you should use navigationClick() instead.
BTW, you don't need to use UiApplication.getUiApplication().invokeLater, because it is already running in the event queue.