Frame only appears some of the time java - 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.

Related

Problems with redirecting console input in java

I am having trouble redirecting input from the console to a GUI in Java.
I have received an assignment, to build a Java command based game. That game includes i.e. the Parser and Console classes. The Parser is used to recognize commands, and Console is a graphical representation of a console.
The Parser class are using System.in and Scanner() to read the commands.
The Console class are redirecting the input from a jTextArea object by using System.setIn().
The Parser works fine with Intellij console and Windows cmd, but the Parser does not receive the text line when I redirect the input. What am I doing wrong?
The code in a test version.
Just run the Console class to open the console window. In the window type a word and press Enter. If it works, you will see your word repeated twice in the window below your word. If it doesn't work, your word will only be repeated once below your word.
Console:
import javax.swing.*;
import javax.swing.text.DefaultHighlighter.DefaultHighlightPainter;
import javax.swing.text.Highlighter.HighlightPainter;
import java.awt.*;
import java.awt.event.*;
import java.io.ByteArrayInputStream;
import java.util.Scanner;
public class Console implements KeyListener, ActionListener {
final String title = "World of Plastic";
final int width = 1380;
final int height = 750;
final String font = "Consolas";
final int fontSize = 12;
final int fontStyle = Font.PLAIN;
final JTextArea jta;
final HighlightPainter painter = new DefaultHighlightPainter(Color.gray);
int initialCaretPosition = 0;
// key codes
final int BACKSPACE = 8;
final int ENTER = 10;
final int PG_UP = 33;
final int PG_DN = 34;
final int END = 35;
final int HOME = 36;
final int LEFT_ARROW = 37;
final int UP_ARROW = 38;
final int RIGHT_ARROW = 39;
final int DOWN_ARROW = 40;
final int A = 65;
final int H = 72;
public Console() {
JFrame jf = this.frame();
//*** JTextArea ***//
this.jta = this.textArea("", 1, 1, false);
this.jta.addKeyListener(this);
// remove all mouse listeners
for (MouseListener listener : this.jta.getMouseListeners()) {
this.jta.removeMouseListener(listener);
}
// remove all mouse motion listeners
for (MouseMotionListener listener : this.jta.getMouseMotionListeners()) {
this.jta.removeMouseMotionListener(listener);
}
// remove all mouse wheel listeners
for (MouseWheelListener listener : this.jta.getMouseWheelListeners()) {
this.jta.removeMouseWheelListener(listener);
}
//*** Scrollable JTextArea ***//
jf.add(this.scrolls(15, 15, this.width - 45, this.height - 70));
jf.setVisible(true);
System.setOut(new Interceptor(System.out, this));
}
public static void main(String[] args) {
Console cfjp = new Console();
//new Game().play();
// A simpel parser
while (true) {
System.out.println();
System.out.print("> ");
Scanner reader = new Scanner(System.in);
System.out.println("parser " + reader.nextLine());
}
}
public void actionPerformed(ActionEvent ae) {
System.out.println("actionPerformed");
}
public void keyTyped(KeyEvent ke) {
}
public void keyReleased(KeyEvent ke) {
}
public void keyPressed(KeyEvent ke) {
int keyCode = ke.getKeyCode();
if (keyCode == PG_UP || keyCode == PG_DN || keyCode == UP_ARROW || keyCode == DOWN_ARROW) {
ke.consume();
} else if (keyCode == A && ke.getModifiersEx() == InputEvent.CTRL_DOWN_MASK) {
//this.highlightText(this.getStartCaretPosition(), this.getEndCaretPosition());
ke.consume();
} else if (keyCode == HOME) {
this.setCaretPosition(this.getStartCaretPosition());
ke.consume();
} else if (keyCode == END) {
this.setCaretPosition(this.getEndCaretPosition());
ke.consume();
} else if (keyCode == RIGHT_ARROW || keyCode == LEFT_ARROW || keyCode == BACKSPACE ||
(keyCode == H && ke.getModifiersEx() == InputEvent.CTRL_DOWN_MASK)) {
int pos = this.getCaretPosition();
if (pos <= this.getStartCaretPosition() || pos >= this.getEndCaretPosition()) {
ke.consume();
}
} else if (keyCode == ENTER) {
int from = this.getStartCaretPosition();
int to = this.getEndCaretPosition();
this.setStartCaretPosition(to);
try {
String inputFromUser = this.jta.getText(from, to - from);
System.out.println("\ninputFromUser " + inputFromUser.trim());
ByteArrayInputStream bais = new ByteArrayInputStream((inputFromUser).getBytes());
System.setIn(bais);
//System.setIn(new ByteArrayInputStream("5".getBytes()));
//System.setIn(new ByteArrayInputStream(inputFromUser.getBytes(StandardCharsets.UTF_8)));
} catch (Exception ignored) {
}
} else if (this.getCaretPosition() < this.getStartCaretPosition()) {
this.setCaretPosition(this.getEndCaretPosition());
}
}
public int getCaretPosition() {
return this.jta.getCaretPosition();
}
public void setCaretPosition(int position) {
this.jta.setCaretPosition(position);
}
public int getStartCaretPosition() {
return this.initialCaretPosition;
}
public void setStartCaretPosition(int position) {
this.setCaretPosition(position);
this.initialCaretPosition = position;
}
public int getEndCaretPosition() {
return this.jta.getDocument().getLength();
}
public void print(String text) {
this.jta.append(text);
this.setStartCaretPosition(this.getEndCaretPosition());
}
public JFrame frame() {
JFrame tmpJF = new JFrame(this.title);
tmpJF.setSize(this.width, this.height);
tmpJF.setLocationRelativeTo(null);
tmpJF.setLayout(null);
tmpJF.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
tmpJF.setResizable(false);
return tmpJF;
}
public JTextArea textArea(String text, int rows, int columns, boolean lineWrap) {
JTextArea tmpJTA = new JTextArea(text, rows, columns);
tmpJTA.setEditable(true);
tmpJTA.setLineWrap(lineWrap);
tmpJTA.setWrapStyleWord(true);
tmpJTA.setFont(new Font(this.font, this.fontStyle, this.fontSize));
tmpJTA.setForeground(Color.WHITE);
tmpJTA.setBackground(Color.black);
return tmpJTA;
}
public JScrollPane scrolls(int xpos, int ypos, int width, int height) {
JScrollPane tmpJSP = new JScrollPane(this.jta);
tmpJSP.setBounds(xpos, ypos, width, height);
tmpJSP.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
tmpJSP.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
return tmpJSP;
}
}
Interceptor:
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Arrays;
public class Interceptor extends PrintStream {
private final Console obj;
public Interceptor(OutputStream out, Console obj) {
super(out, true);
this.obj = obj;
}
#Override
public void print(boolean b) {
this.obj.print(String.valueOf(b));
}
#Override
public void print(char c) {
this.obj.print(String.valueOf(c));
}
#Override
public void print(char[] s) {
this.obj.print(Arrays.toString(s));
}
#Override
public void print(double d) {
this.obj.print(String.valueOf(d));
}
#Override
public void print(float f) {
this.obj.print(String.valueOf(f));
}
#Override
public void print(int i) {
this.obj.print(String.valueOf(i));
}
#Override
public void print(long l) {
this.obj.print(String.valueOf(l));
}
#Override
public void print(Object obj) {
if (obj != null) {
this.obj.print(obj.toString());
}
this.obj.print("null");
}
#Override
public void print(String s) {
this.obj.print(String.valueOf(s));
}
#Override
public void println() {
this.obj.print("\n");
}
#Override
public void println(boolean x) {
this.obj.print(x + "\n");
}
#Override
public void println(char x) {
this.obj.print(x + "\n");
}
#Override
public void println(char[] x) {
this.obj.print(Arrays.toString(x) + "\n");
}
#Override
public void println(double x) {
this.obj.print(x + "\n");
}
#Override
public void println(float x) {
this.obj.print(x + "\n");
}
#Override
public void println(int x) {
this.obj.print(x + "\n");
}
#Override
public void println(long x) {
this.obj.print(x + "\n");
}
#Override
public void println(Object x) {
if (x != null) {
this.obj.print(x.toString() + "\n");
}
this.obj.print("null\n");
}
#Override
public void println(String x) {
this.obj.print(x + "\n");
}
}
The problem is that with
ByteArrayInputStream bais = new ByteArrayInputStream((inputFromUser).getBytes());
System.setIn(bais);
you replace the System.in InputStream, but your code in main
Scanner reader = new Scanner(System.in);
System.out.println("parser " + reader.nextLine());
is still waiting on the old System.in and therefore never receives any characters.
One way to solve it is to create a connected pair of PipedInputStream / PipedOutputStream and use these:
static PipedOutpuStream out;
public static void main(String[] args) {
PipedInputStream in = new PipedInputStream();
out = new PipedOutputStream();
in.connect(out);
System.setIn(in);
// rest of your main
}
public void keyPressed(KeyEvent ke) {
// much code left out
try {
String inputFromUser = this.jta.getText(from, to - from);
System.out.println("\ninputFromUser " + inputFromUser.trim());
out.write((inputFromUser + "\n").getBytes());
out.flush();
} catch (Exception ignored) {
}
// much code left out
}
I made PipedOutputStream out into a static field because of laziness, you could also pass it as constructor argument into the Console constructor.

How to connect method from another class to actionListener?

I'm trying to finish my project about searching graphs, where one of the functions is input (vertex and edges) from user.
I already have a method for this in another class, but now I need to put it into GUI.
I've already tried many of tutorials, but nothing worked. Can somebody help me, how to put the method getInputFromCommand to gui?
I've already tried to copy the method into the GUI, but there was problem with the "return g" because of the void result type, I've tried just to call the method, (I know.. stupid) but it didn't work either.
package Process;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Scanner;
public class FindIslands {
String message = "";
int V;
LinkedList<Integer>[] adjListArray;
static LinkedList<String> nodeList = new LinkedList<String>();
// constructor
FindIslands(int V) {
this.V = V;
adjListArray = new LinkedList[V];
for (int i = 0; i < V; i++) {
adjListArray[i] = new LinkedList<Integer>();
}
}
void addEdge(int src, int dest) {
adjListArray[src].add(dest);
adjListArray[dest].add(src);
}
void DFSUtil(int v, boolean[] visited) {
visited[v] = true;
message += getValue(v) + " ";
// System.out.print(getValue(v) + " ");
for (int x : adjListArray[v]) {
if (!visited[x]) {
DFSUtil(x, visited);
}
}
}
void connectedComponents() {
boolean[] visited = new boolean[V];
int count = 0;
message = "";
for (int v = 0; v < V; ++v) {
if (!visited[v]) {
DFSUtil(v, visited);
message += "\n";
// System.out.println();
count++;
}
}
System.out.println("" + count);
System.out.println("");
System.out.println("Vypis ostrovu: ");
String W[] = message.split("\n");
Arrays.sort(W, new java.util.Comparator<String>() {
#Override
public int compare(String s1, String s2) {
// TODO: Argument validation (nullity, length)
return s1.length() - s2.length();// comparison
}
});
for (String string : W) {
System.out.println(string);
}
}
public static void main(String[] args) {
FindIslands g = null; //
String csvFile = "nodefile.txt";
BufferedReader br = null;
String line = "";
int emptyLine = 0;
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
if (line.equals("")) {
emptyLine = 1;
// System.out.println("found blank line");
}
if (emptyLine == 0) {
// System.out.println(line);
nodeList.add(line);
} else if (line.isEmpty()) {
g = new FindIslands(nodeList.size());
} else {
String[] temp = line.split(",");
g.addEdge(getIndex(temp[0]), getIndex(temp[1]));
}
}
} catch (FileNotFoundException e) {
System.out.println("Soubor nenalezen, zadejte data v danem formatu");
g = getInputFromCommand();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Pocet ostrovu");
if (g != null) {
g.connectedComponents();
}
}
public static int getIndex(String str) {
return nodeList.indexOf(str);
}
public static String getValue(int index) {
return nodeList.get(index);
}
public static FindIslands getInputFromCommand() {
FindIslands g = null;
BufferedReader br = null;
String line = "";
int emptyLine = 0;
Scanner scanner = new Scanner(System.in);
line = scanner.nextLine();
while (!line.equals("")) {
if (line.equals("--gui")) {
Guicko gui = new Guicko();
gui.setVisible(true);
} else
nodeList.add(line);
line = scanner.nextLine();
}
g = new FindIslands(nodeList.size());
line = scanner.nextLine();
while (!line.equals("")) {
String[] temp = line.split(",");
if (temp.length != 2) {
System.out.println("spatny format zadanych dat, prosim zkuste znovu");
} else {
g.addEdge(getIndex(temp[0]), getIndex(temp[1]));
}
line = scanner.nextLine();
}
return g;
}
}
Where important is the last method "getInputFromCommand()"
and... gui
package Process;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.util.Scanner;
public class Guicko extends JFrame {
private JButton štartButton;
private JPanel panel;
private JTextField textField2;
private JTextArea textArea1;
public Guicko() {
add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setTitle("Zadej hodnoty");
setSize(500, 400);
textField2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
FindIslands.getInputFromCommand();
}
});
štartButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String str = "asd";
FindIslands g = null;
g.connectedComponents();
textArea1.setText(str);
}
});
}
public static void main (String args[]){
Guicko gui = new Guicko();
gui.setVisible(true);
}
}
I'm sure there are many correct ways this code can be fixed, but in IMHO, your Guicko class needs to have a FindIslands class member, and I think you need to move some stuff from FindIslands.main() into Guicko.main() or some other method.
Then your "Action Listener" inner classes' actionPerformed methods just delegate to the methods in the FindIslands member instance, like this
....
private FindIslands fi;
public Guicko() {
....
textField2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
fi = FindIslands.getInputFromCommand();
}
});
startButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String comps = fi.connectedComponents();// method needs to return a string
textArea1.setText(comps);
}
});
}
The whole idea of seperating GUI from domain is to make changes easily. GUI has knowledge of the domain but domain has no knowledge about the GUI. We can use an interface to seperate them, in that case, Domain says , i don't care who implements this interface but whoever implements this interface will get response and can work with me.
So , If we create a new GUI, we can let it implements that interface and the same domain will work with that GUI.
There are many mistakes but in order to make it work and to show you an example i did few changes.
public class Guicko extends JFrame implements PropertyChangeListener{
private JButton štartButton;
private JPanel panel;
private JTextField textField2;
private JTextArea textArea1;
private FindIslands land;
private JTextField textField;
private JButton button;
public Guicko() {
JPanel panel = new JPanel();
super.getContentPane().setLayout(new GridLayout());
//For each gui, there should be one land.
this.setLand(new FindIslands(100));
//Subscribe to the domain so that you can get update if something change in domain.
this.getLand().subscribe(this);
//Dummy buttons are fields(need too initiate first)
textField2 = new JTextField("",30);
štartButton = new JButton();
textField = new JTextField("",30);
button = new JButton();
button.setPreferredSize(new Dimension(100, 40));
button.setText("Get input from Domain");
štartButton.setPreferredSize(new Dimension(100, 40));
textField.setEditable(false);
štartButton.setText("Start");
panel.add(textField2);
panel.add(štartButton);
panel.add(textField);
panel.add(button);
add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setTitle("Zadej hodnoty");
setSize(500, 400);
//When you type something in , then this function will send it to domain(i mean to function : getInputFromCommand();).
this.addListerToField(štartButton,this.getLand(),textField2);
//Now the second case, suppose you press a button and want something to show up in textfield. In that case , this function will do work.
this.addListerToSecondField(button,this.getLand(),textField);
}
//Here i can catch the events from the domain.
#Override
public void propertyChange(PropertyChangeEvent e) {
if(e.getPropertyName().equals("String changed")) {
this.getTextField().setText((String) e.getNewValue());
}
}
private void addListerToSecondField(JButton button, FindIslands land, JTextField field) {
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
land.requireArgumentsForField();
}
});
}
private void addListerToField(JButton štartButton, FindIslands land, JTextField field) {
štartButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
land.getInputFromCommand(field.getText());
}
});
}
public static void main (String args[]){
Guicko gui = new Guicko();
gui.setVisible(true);
}
public FindIslands getLand() {
return land;
}
public void setLand(FindIslands land) {
this.land = land;
}
public JTextField getTextField() {
return textField;
}
public void setTextField(JTextField textField) {
this.textField = textField;
}
public JButton getButton() {
return button;
}
public void setButton(JButton button) {
this.button = button;
}
Here is the second class. Run it and try to get feeling for it how it works.
public class FindIslands {
String message = "";
int V;
LinkedList<Integer>[] adjListArray;
static LinkedList<String> nodeList = new LinkedList<String>();
// constructor
FindIslands(int V) {
this.V = V;
//initialize the list
this.setListeners(new ArrayList<>());
adjListArray = new LinkedList[V];
for (int i = 0; i < V; i++) {
adjListArray[i] = new LinkedList<Integer>();
}
}
void addEdge(int src, int dest) {
adjListArray[src].add(dest);
adjListArray[dest].add(src);
}
void DFSUtil(int v, boolean[] visited) {
visited[v] = true;
message += getValue(v) + " ";
// System.out.print(getValue(v) + " ");
for (int x : adjListArray[v]) {
if (!visited[x]) {
DFSUtil(x, visited);
}
}
}
void connectedComponents() {
boolean[] visited = new boolean[V];
int count = 0;
message = "";
for (int v = 0; v < V; ++v) {
if (!visited[v]) {
DFSUtil(v, visited);
message += "\n";
// System.out.println();
count++;
}
}
System.out.println("" + count);
System.out.println("");
System.out.println("Vypis ostrovu: ");
String W[] = message.split("\n");
Arrays.sort(W, new java.util.Comparator<String>() {
#Override
public int compare(String s1, String s2) {
// TODO: Argument validation (nullity, length)
return s1.length() - s2.length();// comparison
}
});
for (String string : W) {
System.out.println(string);
}
}
//You need only one main class, not two.----------------------------
/**
public static void main(String[] args) {
FindIslands g = null; //
String csvFile = "nodefile.txt";
BufferedReader br = null;
String line = "";
int emptyLine = 0;
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
if (line.equals("")) {
emptyLine = 1;
// System.out.println("found blank line");
}
if (emptyLine == 0) {
// System.out.println(line);
nodeList.add(line);
} else if (line.isEmpty()) {
g = new FindIslands(nodeList.size());
} else {
String[] temp = line.split(",");
g.addEdge(getIndex(temp[0]), getIndex(temp[1]));
}
}
} catch (FileNotFoundException e) {
System.out.println("Soubor nenalezen, zadejte data v danem formatu");
g = getInputFromCommand();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Pocet ostrovu");
if (g != null) {
g.connectedComponents();
}
}
**/
public static int getIndex(String str) {
return nodeList.indexOf(str);
}
public static String getValue(int index) {
return nodeList.get(index);
}
//Static cases are to be avoided.This is the property of object not class.
public void getInputFromCommand(String string) {
//Here you will recieve a string from the GUI and will be printed in command prompt.You can do whatever you want to do with it.
System.out.println("Recieve string is " + string);
//No idea what you are trying to do.
/** FindIslands g = null;
BufferedReader br = null;
String line = "";
int emptyLine = 0;
Scanner scanner = new Scanner(System.in);
line = scanner.nextLine();
while (!line.equals("")) {
if (line.equals("--gui")) {
Guicko gui = new Guicko();
gui.setVisible(true);
} else
nodeList.add(line);
line = scanner.nextLine();
}
g = new FindIslands(nodeList.size());
line = scanner.nextLine();
while (!line.equals("")) {
String[] temp = line.split(",");
if (temp.length != 2) {
System.out.println("spatny format zadanych dat, prosim zkuste znovu");
} else {
g.addEdge(getIndex(temp[0]), getIndex(temp[1]));
}
line = scanner.nextLine();
}
return line;**/
}
//This function is triggered with second button and you can send data to gui as shown below.
public void requireArgumentsForField() {
//Suppose i want to send following string.
String name = "I don't know";
this.getListeners().stream().forEach(e -> {
// I will catch this in view.
e.propertyChange(new PropertyChangeEvent(this, "String changed", null, name));
});
}
private ArrayList<PropertyChangeListener> listeners;
//Let the objects subscibe. You need this to publish the changes in domain.
public void subscribe(PropertyChangeListener listener) {
this.getListeners().add(listener);
}
public ArrayList<PropertyChangeListener> getListeners() {
return listeners;
}
public void setListeners(ArrayList<PropertyChangeListener> listeners) {
this.listeners = listeners;
}

Stock Market Simulator Java GUI

I am making a stock market simulator and I keep getting an error from each of my 3 classes the first class MYOSM the error is:
"Cannot find symbol- class stock"
The second class MarketTable outputs:
Cannot find MarketDataModel
And the third class MarketDataModel outputs the error:
Cannot find symbol- class stock
Have I gone wrong somewhere in my code I have checked it multiple times and I can't seem to locate it.
Here is my code:
MYOSM class:
import javax.swing.*;
import java.awt.*;
import java.util.*;
public class MYOSM extends JFrame implements Runnable {
Stock[] market = {
new Stock("JTree", 14.57),
new Stock("JTable", 17.44),
new Stock("JList", 16.44),
new Stock("JButton", 7.21),
new Stock("JComponent", 27.40)
};
boolean monitor;
Random rg = new Random();
Thread runner;
public MYOSM() {
// Not meant to be shown as a real frame
super("Thread only version . . .");
runner = new Thread(this);
runner.start();
}
public MYOSM(boolean monitorOn) {
super("Stock Market Monitor");
setSize(400, 100);
setDefaultCloseOperation(EXIT_ON_CLOSE);
monitor = monitorOn;
getContentPane().add(new JLabel("Trading is active. " +
"Close this window to close the market."),
BorderLayout.CENTER);
runner = new Thread(this);
runner.start();
}
public void run() {
while(true) {
int whichStock = Math.abs(rg.nextInt()) % market.length;
double delta = rg.nextDouble() - 0.4;
market[whichStock].update(delta);
if (monitor) {
market[whichStock].print();
}
try {
Thread.sleep(1000);
}
catch(InterruptedException ie) {
}
}
}
public Stock getQuote(int index) {
return market[index];
}
// This method returns the list of all the symbols in the market table
public String[] getSymbols() {
String[] symbols = new String[market.length];
for (int i = 0; i < market.length; i++) {
symbols[i] = market[i].symbol;
}
return symbols;
}
public static void main(String args[]) {
MYOSM myMarket = new MYOSM(args.length > 0);
myMarket.setVisible(true);
}
}
MarketTable class:
import java.awt.*;
import javax.swing.*;
public class MarketTable extends JFrame {
public MarketTable() {
super("Dynamic Data Test");
setSize(300, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
MarketDataModel mdm = new MarketDataModel(5);
mdm.setStocks(new int[] { 0, 1, 2 });
JTable jt = new JTable(mdm);
JScrollPane jsp = new JScrollPane(jt);
getContentPane().add(jsp, BorderLayout.CENTER);
}
public static void main(String args[]) {
MarketTable mt = new MarketTable();
mt.setVisible(true);
}
}
MarketDataModel class:
import javax.swing.table.*;
import javax.swing.*;
public class MarketDataModel extends AbstractTableModel
implements Runnable {
Thread runner;
MYOSM market;
int delay;
public MarketDataModel(int initialDelay) {
market = new MYOSM();
delay = initialDelay * 1000;
Thread runner = new Thread(this);
runner.start();
}
Stock[] stocks = new Stock[0];
int[] stockIndices = new int[0];
String[] headers = {"Symbol", "Price", "Change", "Last updated"};
public int getRowCount() { return stocks.length; }
public int getColumnCount() { return headers.length; }
public String getColumnName(int c) { return headers[c]; }
public Object getValueAt(int r, int c) {
switch(c) {
case 0:
return stocks[r].symbol;
case 1:
return new Double(stocks[r].price);
case 2:
return new Double(stocks[r].delta);
case 3:
return stocks[r].lastUpdate;
}
throw new IllegalArgumentException("Bad cell (" + r + ", " + c +")");
}
public void setDelay(int seconds) { delay = seconds * 1000; }
public void setStocks(int[] indices) {
stockIndices = indices;
updateStocks();
fireTableDataChanged();
}
public void updateStocks() {
stocks = new Stock[stockIndices.length];
for (int i = 0; i < stocks.length; i++) {
stocks[i] = market.getQuote(stockIndices[i]);
}
}
public void run() {
while(true) {
updateStocks();
fireTableRowsUpdated(0, stocks.length - 1);
try { Thread.sleep(delay); }
catch(InterruptedException ie) {}
}
}
}
You're missing a Stock class there. Should be something like this I suppose:
public class Stock {
public Stock(String string, double d) {
this.symbol = string;
this.price = d;
}
public String symbol;
public double price;
public double delta;
public String lastUpdate;
public void print() {
System.out.println(this);
}
public void update(double delta2) {
this.delta = delta2;
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Stock [symbol=").append(symbol).append(", price=").append(price).append(", delta=").append(delta).append(", lastUpdate=")
.append(lastUpdate).append("]");
return builder.toString();
}
}
Or is it just in a different package than those classes?
Also it's weird your error message has "stock" in lowercase.
With the Stock class added as above, I have managed to start your code, but I'm not sure what it was supposed to be doing. I must note it is poorly written in general, with some basic mistakes like usage of default package.

ImageViewer image loop from json codenameone

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

JPanel elements are not appearing

I'm using the Swing library to ask a user for their zipcode, but all that is appearing is a box, without the text box, or any of the other elements that I've added in (see code). Also, you likely need to know that I'm trying to get the int AskZip() in my public static void main(String[] args) method.
private static int zip;
public static int AskZip() {
JFrame zaWindow = new JFrame("What Zipcode");
zaWindow.setSize(200, 300);
JPanel jp = new JPanel();
final JTextField tf = new JTextField("Enter Zip Here");
JLabel label = new JLabel();
JButton button = new JButton("Get Weather");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String sZip = tf.getText();
int rZip = 0;
try {
if (sZip.length() != 5) {
JOptionPane.showMessageDialog(null, "Invalid zipcode!", "Error", JOptionPane.ERROR_MESSAGE);
} else {
rZip = Integer.parseInt(sZip);
}
} catch (NumberFormatException arg) {
JOptionPane.showMessageDialog(null, "Invalid zipcode!", "Error", JOptionPane.ERROR_MESSAGE);
}
zip = rZip;
}
});
label.setText("What is your zipcode?");
jp.add(label);
jp.add(tf);
jp.add(button);
zaWindow.add(jp);
return zip;
}
JFrame zaWindow..
This should be a modal dialog or a JOptionPane. E.G. This country has 3 states, each with 10 postcodes.
import java.awt.*;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.event.ChangeListener;
class ZipQuery {
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
ZipNumberModel znm = new ZipNumberModel();
JSpinner zip = new JSpinner(znm);
JOptionPane.showMessageDialog(null, zip, "Enter Zipcode", JOptionPane.QUESTION_MESSAGE);
System.out.println("User chose " + znm.getValue());
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
SwingUtilities.invokeLater(r);
}
}
class ZipNumberModel extends SpinnerNumberModel {
private ArrayList<Integer> zipCodes;
private int index = 0;
ZipNumberModel() {
zipCodes = new ArrayList<Integer>();
int zip = 10000;
for (int jj = 1; jj < 4; jj++) {
for (int ii = jj * zip; ii < jj * zip + 10; ii++) {
zipCodes.add(new Integer(ii));
}
}
}
#Override
public Object getValue() {
return zipCodes.get(index);
}
#Override
public Object getNextValue() {
if (index < zipCodes.size()-1) {
index++;
} else {
index = 0;
}
return zipCodes.get(index);
}
#Override
public Object getPreviousValue() {
if (index > 0) {
index--;
} else {
index = zipCodes.size()-1;
}
return zipCodes.get(index);
}
}

Categories