ImageViewer image loop from json codenameone - java

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) {
}
}

Related

need TestNG run option in RCP application

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);
}
}
}

Serialization not working in my JFrames

I'm not sure why the albums aren't being serialized when the users are.
In the admin class, when I login, the userlist is populated in the JCombobox<String> userlist everytime I restart the program.
But the JComboBox<Album> comboBoxAlbumSelect isn't populated every time I restart the program.
Not sure why. Thanks.
Relevant code:
public class Admin extends JFrame implements ActionListener {
Backend backend = new Backend();
GuiCtrl ctrl = new GuiCtrl(backend);
private JComboBox<String> userlist = new JComboBox<String>();
public Admin() {
//same as login
userlist = new JComboBox<String>(getUserList());
}
public String[] getUserList() {
String[] ret = new String[backend.getUserList().size()];
int i = 0;
for (String s : backend.getUserList()) {
System.out.println(s);
ret[i++] = s;
}
return ret;
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == logout) {
this.dispose();
new Login();
}
else if (e.getSource() == add) {
try {
if (ctrl.adduser(idNumberTF.getText(), fullNameTF.getText())) {
userlist.addItem(idNumberTF.getText());
backend.storeData();
} catch (IOException|ClassNotFoundException i) {}
}
}
}
public class MainAlbumPanelv2 extends JFrame implements ActionListener {
JButton btnCreateAlbum = new JButton("Create");
JComboBox<Album> comboBoxAlbumSelect = new JComboBox<Album>();
Backend backend = new Backend();
GuiCtrl ctrl = new GuiCtrl(backend);
User loggedInUser;
public MainAlbumPanelv2(User id) {
loggedInUser = id;
comboBoxAlbumSelect = new JComboBox<Album>(getAlbumList());
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnCreateAlbum) {
if (ctrl.createAlbum(loggedInUser, textFieldCreateAlbum.getText())) {
Album newAlbum = new Album(textFieldCreateAlbum.getText());
comboBoxAlbumSelect.addItem(newAlbum);
}
try {
backend.storeData();
} catch (IOException i) {}
}
}
public Album[] getAlbumList() {
Album[] ret = new Album[loggedInUser.getAlbums().size()];
int i = 0;
for (Album a : loggedInUser.getAlbums()) {
System.out.println(a);
ret[i++] = a;
}
return ret;
}
}
-
public class GuiCtrl {
User loggedInUser;
Backend backend;
public GuiCtrl(Backend backend) {
this.backend = backend;
}
public boolean adduser(String user_id, String user_name) throws IOException, ClassNotFoundException {
if (backend.addUser(new User(user_id, user_name))) {
return true;
} else {
return false;
}
}
public boolean createAlbum(User user_id, String name) {
if (user_id.getAlbum(name) != null) {
return false;
} else {
user_id.addAlbum(name);
return true;
}
}
}
-
public class Backend {
private HashMap<String, User> userList = new HashMap<>();
StringTokenizer tokenizer;
public Backend() {
try {
populateList();
} catch (ClassNotFoundException | IOException e) {
throw new RuntimeException("Cannot read file");
}
}
public boolean addUser(User newUser)
{
String userId = newUser.getID();
if (userList.containsKey(userId)) {
return false;
}
userList.put(userId, newUser);
return true;
}
public void storeData() throws IOException
{
try
{
FileOutputStream file = new FileOutputStream("users.ser");
ObjectOutputStream out = new ObjectOutputStream(file);
out.writeObject(userList);
out.close();
file.close();
}
catch (IOException i)
{
i.printStackTrace();
}
}
public void populateList() throws IOException, ClassNotFoundException
{
try
{
FileInputStream file = new FileInputStream ("users.ser");
ObjectInputStream in = new ObjectInputStream(file);
userList = (HashMap<String, User>) in.readObject();
in.close();
file.close();
}
catch (IOException i)
{
i.printStackTrace();
userList = new HashMap();
}
}
}
public class Album implements Serializable{
private String name;
private ArrayList<Photo> photoList;
public Album(String name)
{
this.name = name;
photoList = new ArrayList<Photo>();
}
}
public class User implements Serializable{
private String id;
private String fullName;
private ArrayList<Album> albumList;
public User(String id, String fullName)
{
this.id = id;
this.fullName = fullName;
albumList = new ArrayList<Album>();
}
public int addAlbum(Album newAlbum)
{
Album currAlbum;
if (newAlbum == null)
{
return 0;
}
for (int x = 0; x < albumList.size(); x++)
{
currAlbum = albumList.get(x);
if (currAlbum.getName().equals(newAlbum.getName()))
{
return 0;
}
}
albumList.add(newAlbum);
return 1;
}
public ArrayList<Album> getAlbums()
{
return albumList;
}
}

using Adjacency list structure for directed graph java

I have problem to implement the transpose of a graph using only Adjacency List, without Edge List. Every vertex of the graph has a positional list that stores adjacent vertexes. When you have to transpose the graph, every element stored in a list of a vertex A, has to be removed and used as a source vertex. So if we have the situation
A -> B
B after its removal, add to its own adjacent list the old source Vertex A
We have as result:
B -> A
when I update the lists, i override the last information stored in, so I lose connection between vertexes.
public class Vertice implements Comparable<Vertice>{
public Vertice(int valore){
this.valore = valore;
this.color = Color.WHITE;
this.distanza = 0;
this.padre = null;
adiacenze = new NodePositionList<Vertice>();
}
public int getValore() {
return valore;
}
public void setValore(int valore) {
this.valore = valore;
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
public Position<Vertice> getPadre() {
return padre;
}
public void setPadre(Position<Vertice> padre) {
this.padre = padre;
}
public int getDistanza() {
return distanza;
}
public void setDistanza(int distanza) {
this.distanza = distanza;
}
public enum Color{
BLACK, WHITE, GREY;
}
public String toString(){
StringBuilder sb = new StringBuilder();
sb.append("v_" + valore );
return sb.toString();
}
public boolean equals(Vertice v){
return this.compareTo(v) == 0;
}
#Override
public int compareTo(Vertice o) {
return this.valore - o.getValore();
}
public int getFin() {
return fin;
}
public void setFin(int fin) {
this.fin = fin;
}
public Position<Vertice> getRiferimentoVertice() {
return riferimentoVertice;
}
public void setRiferimentoVertice(Position<Vertice> riferimentoVertice) {
this.riferimentoVertice = riferimentoVertice;
}
public Iterable<Vertice> getAdiacenze() {
return adiacenze;
}
public void setAdiacenze(NodePositionList<Vertice> adiacenze) {
this.adiacenze = adiacenze;
}
public Position<Vertice> addNodoAdiacente(Vertice v){
Position<Vertice> newVertice = adiacenze.addLast(v);
v.setRiferimentoAsAdiacenza(newVertice);
return newVertice;
}
public Position<Vertice> removeNodoAdiacente(Position<Vertice> v){
return adiacenze.remove(v);
}
public Position<Vertice> getRiferimentoAsAdiacenza() {
return riferimentoAsAdiacenza;
}
public void setRiferimentoAsAdiacenza(Position<Vertice> riferimentoAsAdiacenza) {
this.riferimentoAsAdiacenza = riferimentoAsAdiacenza;
}
public boolean hasAdiacent(){
return adiacenze.size() == 0;
}
public boolean hasRedEdge(){
return redEdge;
}
public void setHasRedEdge(boolean redEdge){
this.redEdge = redEdge;
}
private boolean redEdge;
private int valore;
private Color color;
private Position<Vertice> padre;
private int distanza;
private int fin;
private Position<Vertice> riferimentoVertice;
private Position<Vertice> riferimentoAsAdiacenza;
private NodePositionList<Vertice> adiacenze;
here the "Grafo.java" class
public class Grafo {
public Grafo(int numV){
verticiGrafo = new NodePositionList<Vertice>();
listaArchi = new NodePositionList<Arco>();
this.V = numV;
}
public Position<Vertice> addVertice(Vertice v){
Position<Vertice> newAdded = verticiGrafo.addLast(v);
v.setRiferimentoVertice(newAdded);
return newAdded;
}
public NodePositionList<Vertice> getVertici(){
return verticiGrafo;
}
public Position<Arco> addArco(Arco a){
a.getSorgente().element().addNodoAdiacente(a.getDestinazione().element());
Position<Arco> newAdded = listaArchi.addLast(a);
a.setRiferimentoArco(newAdded);
return newAdded;
}
public Position<Arco> connect(Position<Vertice> sorgente, Position<Vertice> destinazione){
Arco a = new Arco(sorgente, destinazione);
Vertice v_sorgente = sorgente.element();
Vertice v_destinazione = destinazione.element();
v_sorgente.addNodoAdiacente(v_destinazione);
Position<Arco> newAdded = listaArchi.addLast(a);
a.setRiferimentoArco(newAdded);
return newAdded;
}
public Position<Arco> removeArco(Position<Arco> a){
a.element().getSorgente().element().removeNodoAdiacente(a.element().getDestinazione());
return listaArchi.remove(a);
}
public Iterable<Arco> archi(){
return listaArchi;
}
public void invertiArco(Position<Arco> a){
Arco a1 = a.element();
Position<Vertice> temp = a1.getDestinazione();
a1.setDestinazione(a1.getSorgente());
a1.setSorgente(temp);
Vertice sorgente = a1.getSorgente().element();
Vertice destinatario = a1.getDestinazione().element();
sorgente.addNodoAdiacente(destinatario);
}
public Position<Arco> getArcoByVertici(Position<Vertice> sorgente, Position<Vertice> destinazione){
for(Arco a: listaArchi){
if(a.getColor() == EdgeColor.NONE){
Vertice dest = a.getDestinazione().element();
Vertice sorg = a.getSorgente().element();
if(sorg.equals(sorgente.element()) && dest.equals(destinazione.element())){
return a.getRiferimentoArco();
}
}
}
return null;
}
public void removeAllAdiacenze(){
for(Vertice v: this.getVertici()){
v.setAdiacenze( new NodePositionList<Vertice>());
}
}
public void setColorArco(Position<Arco> a, EdgeColor ec){
a.element().setColor(ec);
}
public NodePositionList<Arco> getListaArchi() {
return listaArchi;
}
public void setListaArchi(NodePositionList<Arco> listaArchi) {
this.listaArchi = listaArchi;
}
private NodePositionList<Vertice> verticiGrafo;
private NodePositionList<Arco> listaArchi; //lista archi uscenti
public final int V;
}
here the method on the "Ricerca.java" class that I'm trying to make
public static Grafo traspostaGrafo(Grafo g){
NodePositionList<Vertice> npl = g.getVertici();
Position<Vertice> u = npl.first();
while (u != npl.getTail()){
u.element().setColor(Color.WHITE);
NodePositionList<Vertice> adiacenti = g.getListaAdiacenti(u.element().getValore());
Position<Vertice> adiacente = adiacenti.first();
while (adiacente != adiacenti.getTail() && adiacente.element().getFlag() == 0){
g.addNodoAdiacente(adiacente.element(), u.element());
g.removeNodoAdiacente(adiacente);
adiacente = adiacenti.next(adiacente);
u.element().setFlag(1);
}
}
return g
}

Frame only appears some of the time java

For some reason (seemingly completely independent of code) the frame of my program will only appear some (maybe 20%) of the time. If I just continuously hit run I evently get the frame to show successfully, but it is never repeatable. has this ever happened to anyone else? I highly doubt this has to do with code but just in case
public class Trader{
public static Trader INSTANCE = new Trader();
JTextArea msgBox;
ApiController m_controller;
Connection connect;
Quotes quotes;
ArrayList<String> m_acctList = new ArrayList();
public static void main(String[] args) {
INSTANCE.run();
}
public void run(){
connect = new Connection();
}
public ArrayList<String> accountList() { return m_acctList; }
public ApiController controller() { return m_controller; }
public JFrame frame() { return connect.frame; }
}
next class
public class Connection implements IConnectionHandler{
static int port = 4001;
Quotes quotes;
JFrame frame;
CPanel panel;
boolean connected = false;
JTextArea logIn = new JTextArea();
JTextArea logOut = new JTextArea();
JTextArea msgBox = new JTextArea();
Logger loggerIn = new Logger(logIn);
Logger loggerOut = new Logger(logOut);
ApiController m_controller = new ApiController(this, loggerIn, loggerOut);
final ArrayList<String> m_acctList = new ArrayList<String>();
Connection(){
frame = new JFrame("Trader");
panel = new CPanel();
frame.add(panel);
frame.setSize(800,400);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
class CPanel extends JComponent{
Point frameLoc = frame.getLocation();
Dimension frameSize = frame.getSize();
JLabel text = new JLabel("Messages");
JScrollPane messages = new JScrollPane(msgBox);
CPanel(){
setLayout(null);
add(text);
text.setBounds(frameLoc.x+5, frameLoc.y+5,
text.getPreferredSize().width, text.getPreferredSize().height);
add(messages);
msgBox.setEditable(false);
msgBox.setLineWrap(true);
messages.setBounds(text.getLocation().x, text.getLocation().y+text.getSize().height+10,
720, 300);
m_controller.connect(null, port, 0);
}
}
#Override public void connected() {
show( "connected");
m_controller.reqCurrentTime( new ApiController.ITimeHandler() {
#Override public void currentTime(long time) {
show( "Server date/time is " + Formats.fmtDate(time * 1000) );
}
});
m_controller.reqBulletins( true, new ApiController.IBulletinHandler() {
#Override public void bulletin(int msgId, Types.NewsType newsType, String message, String exchange) {
String str = String.format( "Received bulletin: type=%s exchange=%s", newsType, exchange);
show( str);
show( message);
}
});
// Quotes quotes = new Quotes();
}
#Override public void disconnected() {
show( "disconnected");
}
#Override public void accountList(ArrayList<String> list) {
show( "Received account list");
m_acctList.clear();
m_acctList.addAll( list);
}
#Override public void error(Exception e) {
show( e.toString() );
}
#Override public void message(int id, int errorCode, String errorMsg) {
show( id + " " + errorCode + " " + errorMsg);
}
#Override public void show( final String str) {
SwingUtilities.invokeLater( new Runnable() {
#Override public void run() {
msgBox.append(str);
msgBox.append( "\n\n");
Dimension d = msgBox.getSize();
msgBox.scrollRectToVisible( new Rectangle( 0, d.height, 1, 1) );
}
});
}
private static class Logger implements ILogger{
final private JTextArea msgBox;
Logger(JTextArea area){
msgBox = area;
}
#Override public void log(final String str) {
SwingUtilities.invokeLater( new Runnable() {
#Override public void run() {
// m_area.append(str);
//
// Dimension d = m_area.getSize();
// m_area.scrollRectToVisible( new Rectangle( 0, d.height, 1, 1) );
}
});
}
}
}
and lastly
public class Quotes {
int numberOfStocks = 0;
JTextArea msgBox = Trader.INSTANCE.connect.msgBox;
String symbol;
File file = new File("/Users/spencerclayman/Desktop/IB_API/API_Data/stockList.txt");
ArrayList<quote> stockList = new ArrayList();
Quotes(){
msgBox.append("Getting stock quotes");
try(Scanner input = new Scanner(file);){
while(input.hasNextLine()){
symbol = input.nextLine();
newStock(newContract(symbol));
}
}
catch(Exception ex){msgBox.append("Error getting quotes");}
try{wait(10000);}catch(Exception ex){msgBox.append("error waiting - quote");}
for(int i = 0; i < numberOfStocks() -1 ; i++){
msgBox.append(stockList.get(i).m_description
+ " - " + stockList.get(i).m_last +"\n");
}
}
void newStock( NewContract contract) {
quote stock = new quote(contract.description());
stockList.add(stock);
Trader.INSTANCE.controller().reqTopMktData(contract, "", false, stock);
}
void newStock( quote stock) {
stockList.add(stock);
}
public void desubscribe() {
for (quote stock : stockList) {
Trader.INSTANCE.controller().cancelTopMktData(stock);
}
}
public int numberOfStocks(){
try(Scanner input = new Scanner(file);){
while(input.hasNextLine()){
numberOfStocks++;
input.nextLine();
}
}
catch(Exception ex){msgBox.append("Error getting symbols");}
return numberOfStocks;
}
static class quote extends TopMktDataAdapter{
String m_description;
double m_bid;
double m_ask;
double m_last;
long m_lastTime;
int m_bidSize;
int m_askSize;
double m_close;
int m_volume;
boolean m_frozen;
quote(String description){
m_description = description;
}
public String change() {
return m_close == 0 ? null : fmtPct( (m_last - m_close) / m_close);
}
#Override public void tickPrice( NewTickType tickType, double price, int canAutoExecute) {
switch( tickType) {
case BID:
m_bid = price;
break;
case ASK:
m_ask = price;
break;
case LAST:
m_last = price;
break;
case CLOSE:
m_close = price;
break;
}
}
#Override public void tickSize( NewTickType tickType, int size) {
switch( tickType) {
case BID_SIZE:
m_bidSize = size;
break;
case ASK_SIZE:
m_askSize = size;
break;
case VOLUME:
m_volume = size;
break;
}
}
#Override public void tickString(NewTickType tickType, String value) {
switch( tickType) {
case LAST_TIMESTAMP:
m_lastTime = Long.parseLong( value) * 1000;
break;
}
}
#Override public void marketDataType(Types.MktDataType marketDataType) {
m_frozen = marketDataType == Types.MktDataType.Frozen;
}
}
public NewContract newContract(String symbol){
NewContract c = new NewContract();
c.symbol(symbol);
c.secType(Types.SecType.STK);
c.exchange("SMART");
c.currency("USD");
return c;
}
}
again i am highly doubtful that code has anything to do with it. Im assumign its a problem with the IDE.

Customize listfield item on BlackBerry

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.

Categories