command doesn't work in a canvas j2me program - java

i made a canvas J2ME program and i used key press and key code to complete the program! now i have a big problem with two screen commands!
I need to use the command labels "Ersal" and "Virayesh" as below code but the command code doesn't work! i could use the key Codes(-6) but then i don't have command labels in the screen.
So whats your solution?
can i just add two labels in the screen not command?!
or how can i active these command void!
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
import javax.microedition.lcdui.*;
import com.sun.midp.io.j2me.comm.WAP;
import com.sun.midp.io.j2me.comm.SDA;
public class Demo extends MIDlet
{
Command ersal = new Command("Ersal", Command.STOP, 1);
Command virayesh = new Command("Virayesh", Command.SCREEN, 1);
private Canvas m_canvas = new DemoCanvas();
private Display m_disp;
int v = 0;
public static final int IME_NOTIFY = -6;
public static final int KEY_ASTERISK = 42;
public static final int KEY_HASH = 35;
String a;
int step = -1;
public Demo() {
// TODO Auto-generated constructor stub
m_disp = Display.getDisplay(this);
m_disp.setCurrent(m_canvas);
}
private class DemoCanvas extends Canvas implements CommandListener
{
private String info = "Barname Estelam\n*:Meno Aval\n\nYek dokme ` `ra\nfeshar dahid";
public DemoCanvas(){}
public void paint(Graphics g)
{
g.setColor(0xFFFFFF);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
g.setColor(0);
g.drawString(info, 0, 5, Graphics.LEFT|Graphics.TOP);
/*
if(step==-1){
step=0;
try {
Thread.sleep(5000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
info = "1:moshakhasat\nkhodro \n2:estelam taghib \n3:etelaat malek \n4:estelam khalafi";
repaint();
}
*
*/
}
protected void keyPressed(int keyCode)
{
/*
if(IME_NOTIFY == keyCode){
String m = WAP.GetT9String();
SDA.SDS_SendMsg("20002",m);
info = WAP.GetT9String() + "\nersal shod";
}
*
*/
if(keyCode==42 || step==-1){
info="1:moshakhasat\nkhodro \n2:estelam taghib \n3:etelaat malek \n4:estelam khalafi";
step=0;
a="";
m_canvas.removeCommand(ersal);
m_canvas.removeCommand(virayesh);
//m_disp.setCurrent(m_canvas);
WAP.WAP_InputMethodContents("");
}
String content = WAP.GetT9String();
if(step==2){
step=3;
//tayid T9
m_canvas.addCommand(ersal);
m_canvas.addCommand(virayesh);
String n = WAP.GetT9String();
if(a.equals("11") && n.length()>7)
info = "moshakhasat\nkhodro\n\npelak:\n" + pelakSp(content);
if(a.equals("12") && n.length()>7)
info = "moshakhasat\nkhodro\n\nshomare shasi:\n" + content;
if(a.equals("13") && n.length()>7)
info = "moshakhasat\nkhodro\n\nshomare motor:\n" + content;
if(a.equals("21") && n.length()>7)
info = "estelam taghib\n\npelak:\n" + pelakSp(content);
if(a.equals("31") && n.length()>7)
info = "etelaat malek\n\npelak:\n" + pelakSp(content);
if(a.equals("41") && n.length()>7)
info = "estelam khalafi\n\npelak:\n" + pelakSp(content);
repaint();
}
if(step==1){
if(keyCode==49){
step=2;
a+="1";
//pelak
String c = info;
WAP.WAP_InputMethodContentsLength(8);
WAP.SwitchToT9InputMethod(0);
//bazgasht T9
String b = WAP.GetT9String();
repaint();
}
if(keyCode==50 && a.equals("1")){
step=2;
a+="2";
//shomare shasi0-9
String c = info;
WAP.WAP_InputMethodContentsLength(14);
WAP.SwitchToT9InputMethod(0);
//bazgasht T9
String b = com.sun.midp.io.j2me.comm.WAP.GetT9String();
}
repaint();
if(keyCode==51 && a.equals("1")){
step=2;
a+="3";
//shomare motor
String c = info;
WAP.WAP_InputMethodContentsLength(10);
WAP.SwitchToT9InputMethod(0);
//bazgasht T9
String b = com.sun.midp.io.j2me.comm.WAP.GetT9String();
repaint();
}
}
if(step==0){
if(keyCode==49){
a="1";
info="*Moshakhasat\nkhodro*\n1:Pelak\n2:Shomare Shasi\n3:Shomare Motor";
step=1;
}
if(keyCode==50){
a="2";
info="*Estelam Taghib*\n1:Pelak";
step=1;
}
if(keyCode==51){
a="3";
info="*Moshakhast Malek*\n1:Pelak";
step=1;
}
if(keyCode==52){
a="4";
info="*Estelam Khalafi*\n1:Pelak";
step=1;
}
}
repaint();
}
public void commandAction(Command c, Displayable d) {
String m = WAP.GetT9String();
SDA.SDS_SendMsg("20002",m);
info = WAP.GetT9String() + "\nersal shod";
// throw new UnsupportedOperationException("Not supported yet.");
}
}
protected void destroyApp(boolean unconditional)
throws MIDletStateChangeException {
// TODO Auto-generated method stub
notifyDestroyed();
}
protected void pauseApp() {}
protected void startApp() throws MIDletStateChangeException {
// TODO Auto-generated method stub
}
public String pelakSp(String a){
//tafkike pelak
String m = a.substring(0, 2) + " " + a.substring(2, 3) + " " + a.substring(3, 6) + "-" + a.substring(6, 8);
return m;
}
}

Try
this.addCommand(...)
in your constructor

i got the problem!
i didn't used command listener for my canvas!
i add this and it solved:
m_canvas.setCommandListener(new CommandListener() {
public void commandAction(Command c, Displayable d) {
String m = WAP.GetT9String();
SDA.SDS_SendMsg("20002",m);
info = WAP.GetT9String() + "\nersal shod";
}
});

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.

automatically highlights words in the textpane

I have this code from java2s.com and I just modified it. I don't know if I need to use the runnable or the documentlistener so that the application will automatically highlight the word that was defined in the code. I don't have much knowledge about the two, I tried the runnable but I encountered errors. Can someone help me? Here's the code.
public class Sample {
public static void main(String[] args) {
JFrame f = new JFrame();
JTextPane textPane = new JTextPane();
String word = "";
Highlighter highlighter = new UnderlineHighlighter(null);
textPane.setHighlighter(highlighter);
textPane.setText("This is a test");
final WordSearcher searcher = new WordSearcher(textPane);
final UnderlineHighlighter uhp = new UnderlineHighlighter(Color.red);
String w = "i";
int offset = searcher.search(w);
if (offset == -1) {
return;
}
try {
textPane.scrollRectToVisible(textPane.modelToView(offset));
} catch (BadLocationException ex) {
}
textPane.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent evt) {
searcher.search(word);
}
#Override
public void removeUpdate(DocumentEvent evt) {
searcher.search(word);
}
#Override
public void changedUpdate(DocumentEvent evt) {
}
});
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//f.add(panel, "South");
f.add(new JScrollPane(textPane), "Center");
f.setSize(400, 400);
f.setVisible(true);
}
public static String word;
public static Highlighter highlighter = new UnderlineHighlighter(null);
}
class WordSearcher {
public WordSearcher(JTextComponent comp) {
this.comp = comp;
this.painter = new UnderlineHighlighter.UnderlineHighlightPainter(
Color.red);
}
public int search(String word) {
int firstOffset = -1;
Highlighter highlighter = comp.getHighlighter();
Highlighter.Highlight[] highlights = highlighter.getHighlights();
for (int i = 0; i < highlights.length; i++) {
Highlighter.Highlight h = highlights[i];
if (h.getPainter() instanceof
UnderlineHighlighter.UnderlineHighlightPainter) {
highlighter.removeHighlight(h);
}
}
if (word == null || word.equals("")) {
return -1;
}
String content = null;
try {
Document d = comp.getDocument();
content = d.getText(0, d.getLength()).toLowerCase();
} catch (BadLocationException e) {
// Cannot happen
return -1;
}
word = word.toLowerCase();
int lastIndex = 0;
int wordSize = word.length();
while ((lastIndex = content.indexOf(word, lastIndex)) != -1) {
int endIndex = lastIndex + wordSize;
try {
highlighter.addHighlight(lastIndex, endIndex, painter);
} catch (BadLocationException e) {
// Nothing to do
}
if (firstOffset == -1) {
firstOffset = lastIndex;
}
lastIndex = endIndex;
}
return firstOffset;
}
protected JTextComponent comp;
protected Highlighter.HighlightPainter painter;
}
class UnderlineHighlighter extends DefaultHighlighter {
public UnderlineHighlighter(Color c) {
painter = (c == null ? sharedPainter : new UnderlineHighlightPainter(c));
}
public Object addHighlight(int p0, int p1) throws BadLocationException {
return addHighlight(p0, p1, painter);
}
public void setDrawsLayeredHighlights(boolean newValue) {
// Illegal if false - we only support layered highlights
if (newValue == false) {
throw new IllegalArgumentException(
"UnderlineHighlighter only draws layered highlights");
}
super.setDrawsLayeredHighlights(true);
}
public static class UnderlineHighlightPainter extends
LayeredHighlighter.LayerPainter {
public UnderlineHighlightPainter(Color c) {
color = c;
}
public void paint(Graphics g, int offs0, int offs1, Shape bounds,
JTextComponent c) {
// Do nothing: this method will never be called
}
public Shape paintLayer(Graphics g, int offs0, int offs1, Shape bounds,
JTextComponent c, View view) {
g.setColor(color == null ? c.getSelectionColor() : color);
Rectangle alloc = null;
if (offs0 == view.getStartOffset() && offs1 == view.getEndOffset()) {
if (bounds instanceof Rectangle) {
alloc = (Rectangle) bounds;
} else {
alloc = bounds.getBounds();
}
} else {
try {
Shape shape = view.modelToView(offs0,
Position.Bias.Forward, offs1,
Position.Bias.Backward, bounds);
alloc = (shape instanceof Rectangle) ? (Rectangle) shape
: shape.getBounds();
} catch (BadLocationException e) {
return null;
}
}
FontMetrics fm = c.getFontMetrics(c.getFont());
int baseline = alloc.y + alloc.height - fm.getDescent() + 1;
g.drawLine(alloc.x, baseline, alloc.x + alloc.width, baseline);
g.drawLine(alloc.x, baseline + 1, alloc.x + alloc.width,
baseline + 1);
return alloc;
}
protected Color color; // The color for the underline
}
protected static final Highlighter.HighlightPainter sharedPainter = new
UnderlineHighlightPainter(
null);
protected Highlighter.HighlightPainter painter;
}
Maybe your code has some import errors? It runs fine with Java 1.8. In this situation it is Ok to use DocumentListener. Made some modifications in main class for finding text "test":
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.*;
import java.awt.*;
public class Sample {
public static void main(String[] args) {
JFrame f = new JFrame();
JTextPane textPane = new JTextPane();
String word = "test";
Highlighter highlighter = new UnderlineHighlighter(null);
textPane.setHighlighter(highlighter);
textPane.setText("This is a test");
final WordSearcher searcher = new WordSearcher(textPane);
final UnderlineHighlighter uhp = new UnderlineHighlighter(Color.red);
String w = "i";
int offset = searcher.search(w);
if (offset == -1) {
return;
}
try {
textPane.scrollRectToVisible(textPane.modelToView(offset));
} catch (BadLocationException ex) {
}
textPane.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent evt) {
searcher.search(word);
}
#Override
public void removeUpdate(DocumentEvent evt) {
searcher.search(word);
}
#Override
public void changedUpdate(DocumentEvent evt) {
}
});
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new JScrollPane(textPane), "Center");
f.setSize(400, 400);
f.setVisible(true);
searcher.search(word);
}
public static String word;
public static Highlighter highlighter = new UnderlineHighlighter(null);
}
}

Painting canvas and System.out.println() not working

I have JFrame with a start button, which triggers the calculation of a Julia Set.
The code that is executed when the start button is clicked is as follows:
public void actionPerformed(ActionEvent aActionEvent)
{
String strCmd = aActionEvent.getActionCommand();
if (strCmd.equals("Start"))
{
m_cCanvas.init();
m_cSMsg = "c = " + Double.toString(m_dReal) + " + " + "j*" + Double.toString(m_dImag);
m_bRunning = true;
this.handleCalculation();
}
else if (aActionEvent.getSource() == m_cTReal)
Which used to work fine, except that the application could not be closed anymore. So I tried to use m_bRunning in a separate method so that actionPerformed() isn't blocked all the time to see if that would help, and then set m_bRunning = false in the method stop() which is called when the window is closed:
public void run()
{
if(m_bRunning)
{
this.handleCalculation();
}
}
The method run() is called from the main class in a while(true) loop.
Yet unfortunately, neither did that solve the problem, nor do I now have any output to the canvas or any debug traces with System.out.println(). Could anyone point me in the right direction on this?
EDIT:
Here are the whole files:
// cMain.java
package juliaSet;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.Dimension;
public class cMain {
public static void main(String[] args)
{
int windowWidth = 1000;//(int)screenSize.getWidth() - 200;
int windowHeight = 800;//(int)screenSize.getHeight() - 50;
int plotWidth = 400;//(int)screenSize.getWidth() - 600;
int plotHeight = 400;//(int)screenSize.getHeight() - 150;
JuliaSet cJuliaSet = new JuliaSet("Julia Set", windowWidth, windowHeight, plotWidth, plotHeight);
cJuliaSet.setVisible(true);
while(true)
{
cJuliaSet.run();
}
}
}
// JuliaSet.java
package juliaSet;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.swing.*;
import java.util.Random;
import java.io.*;
import java.lang.ref.*;
public class JuliaSet extends JFrame implements ActionListener
{
private JButton m_cBStart;
private JTextField m_cTReal;
private JTextField m_cTImag;
private JTextField m_cTDivergThresh;
private JLabel m_cLReal;
private JLabel m_cLImag;
private JLabel m_cLDivergThresh;
private int m_iDivergThresh = 10;
private String m_cMsgDivThresh = "Divergence threshold = " + m_iDivergThresh;
private JuliaCanvas m_cCanvas;
private int m_iPlotWidth; // number of cells
private int m_iPlotHeight; // number of cells
private Boolean m_bRunning = false;
private double m_dReal = 0.3;
private double m_dImag = -0.5;
private String m_cSMsg = "c = " + Double.toString(m_dReal) + " + " + "j*" + Double.toString(m_dImag);
private String m_cMsgIter = "x = 0, y = 0";
private Complex m_cCoordPlane[][];
private double m_dAbsSqValues[][];
private int m_iIterations[][];
private Complex m_cSummand;
private BufferedImage m_cBackGroundImage = null;
private FileWriter m_cFileWriter;
private BufferedWriter m_cBufferedWriter;
private String m_sFileName = "log.txt";
private Boolean m_bWriteLog = false;
private static final double PLOTMAX = 2.0; // we'll have symmetric axes
// ((0,0) at the centre of the
// plot
private static final int MAXITER = 0xff;
JuliaSet(String aTitle, int aFrameWidth, int aFrameHeight, int aPlotWidth, int aPlotHeight)
{
super(aTitle);
this.setSize(aFrameWidth, aFrameHeight);
m_iPlotWidth = aPlotWidth;
m_iPlotHeight = aPlotHeight;
m_cSummand = new Complex(m_dReal, m_dImag);
m_cBackGroundImage = new BufferedImage(aFrameWidth, aFrameHeight, BufferedImage.TYPE_INT_RGB);
this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
stop();
super.windowClosing(e);
System.exit(0);
}
});
GridBagLayout cLayout = new GridBagLayout();
GridBagConstraints cConstraints = new GridBagConstraints();
this.setLayout(cLayout);
m_cCanvas = new JuliaCanvas(m_iPlotWidth, m_iPlotHeight);
m_cCanvas.setSize(m_iPlotWidth, m_iPlotHeight);
m_cBStart = new JButton("Start");
m_cBStart.addActionListener(this);
m_cTReal = new JTextField(5);
m_cTReal.addActionListener(this);
m_cTImag = new JTextField(5);
m_cTImag.addActionListener(this);
m_cTDivergThresh = new JTextField(5);
m_cTDivergThresh.addActionListener(this);
m_cLReal = new JLabel("Re(c):");
m_cLImag = new JLabel("Im(c):");
m_cLDivergThresh = new JLabel("Divergence Threshold:");
cConstraints.insets.top = 3;
cConstraints.insets.bottom = 3;
cConstraints.insets.right = 3;
cConstraints.insets.left = 3;
// cCanvas
cConstraints.gridx = 0;
cConstraints.gridy = 0;
cLayout.setConstraints(m_cCanvas, cConstraints);
this.add(m_cCanvas);
// m_cLReal
cConstraints.gridx = 0;
cConstraints.gridy = 1;
cLayout.setConstraints(m_cLReal, cConstraints);
this.add(m_cLReal);
// m_cTReal
cConstraints.gridx = 1;
cConstraints.gridy = 1;
cLayout.setConstraints(m_cTReal, cConstraints);
this.add(m_cTReal);
// m_cLImag
cConstraints.gridx = 0;
cConstraints.gridy = 2;
cLayout.setConstraints(m_cLImag, cConstraints);
this.add(m_cLImag);
// m_cTImag
cConstraints.gridx = 1;
cConstraints.gridy = 2;
cLayout.setConstraints(m_cTImag, cConstraints);
this.add(m_cTImag);
// m_cLDivergThresh
cConstraints.gridx = 0;
cConstraints.gridy = 3;
cLayout.setConstraints(m_cLDivergThresh, cConstraints);
this.add(m_cLDivergThresh);
// m_cTDivergThresh
cConstraints.gridx = 1;
cConstraints.gridy = 3;
cLayout.setConstraints(m_cTDivergThresh, cConstraints);
this.add(m_cTDivergThresh);
// m_cBStart
cConstraints.gridx = 0;
cConstraints.gridy = 4;
cLayout.setConstraints(m_cBStart, cConstraints);
this.add(m_cBStart);
if (m_bWriteLog)
{
try
{
m_cFileWriter = new FileWriter(m_sFileName, false);
m_cBufferedWriter = new BufferedWriter(m_cFileWriter);
} catch (IOException ex) {
System.out.println("Error opening file '" + m_sFileName + "'");
}
}
this.repaint();
this.transformCoordinates();
}
public synchronized void stop()
{
if (m_bRunning)
{
m_bRunning = false;
boolean bRetry = true;
}
if (m_bWriteLog)
{
try {
m_cBufferedWriter.close();
m_cFileWriter.close();
} catch (IOException ex) {
System.out.println("Error closing file '" + m_sFileName + "'");
}
}
}
public void collectGarbage()
{
Object cObj = new Object();
WeakReference ref = new WeakReference<Object>(cObj);
cObj = null;
while(ref.get() != null) {
System.gc();
}
}
public void setSummand(Complex aSummand)
{
m_cSummand.setIm(aSummand.getIm());
m_dImag = aSummand.getIm();
m_cSummand.setRe(aSummand.getRe());
m_dReal = aSummand.getRe();
m_cSMsg = "c = " + Double.toString(m_dReal) + " + " + "j*" + Double.toString(m_dImag);
}
public void paint(Graphics aGraphics)
{
Graphics cScreenGraphics = aGraphics;
// render on background image
aGraphics = m_cBackGroundImage.getGraphics();
this.paintComponents(aGraphics);
// drawString() calls are debug code only....
aGraphics.setColor(Color.BLACK);
aGraphics.drawString(m_cSMsg, 10, 450);
aGraphics.drawString(m_cMsgIter, 10, 465);
aGraphics.drawString(m_cMsgDivThresh, 10, 480);
// rendering is done, draw background image to on screen graphics
cScreenGraphics.drawImage(m_cBackGroundImage, 0, 0, null);
}
public void actionPerformed(ActionEvent aActionEvent)
{
String strCmd = aActionEvent.getActionCommand();
if (strCmd.equals("Start"))
{
m_cCanvas.init();
m_cSMsg = "c = " + Double.toString(m_dReal) + " + " + "j*" + Double.toString(m_dImag);
m_bRunning = true;
}
else if (aActionEvent.getSource() == m_cTReal)
{
m_dReal = Double.parseDouble(m_cTReal.getText());
m_cSMsg = "c = " + Double.toString(m_dReal) + " + " + "j*" + Double.toString(m_dImag);
m_cSummand.setRe(m_dReal);
}
else if (aActionEvent.getSource() == m_cTImag)
{
m_dImag = Double.parseDouble(m_cTImag.getText());
m_cSMsg = "c = " + Double.toString(m_dReal) + " + " + "j*" + Double.toString(m_dImag);
m_cSummand.setIm(m_dImag);
}
else if (aActionEvent.getSource() == m_cTDivergThresh)
{
m_iDivergThresh = Integer.parseInt(m_cTDivergThresh.getText());
m_cMsgDivThresh = "Divergence threshold = " + m_iDivergThresh;
}
this.update(this.getGraphics());
}
public void transformCoordinates()
{
double dCanvasHeight = (double) m_cCanvas.getHeight();
double dCanvasWidth = (double) m_cCanvas.getWidth();
// init matrix with same amount of elements as pixels in canvas
m_cCoordPlane = new Complex[(int) dCanvasHeight][(int) dCanvasWidth];
double iPlotRange = 2 * PLOTMAX;
for (int i = 0; i < dCanvasHeight; i++)
{
for (int j = 0; j < dCanvasWidth; j++)
{
m_cCoordPlane[i][j] = new Complex((i - (dCanvasWidth / 2)) * iPlotRange / dCanvasWidth,
(j - (dCanvasHeight / 2)) * iPlotRange / dCanvasHeight);
}
}
}
public void calcAbsSqValues()
{
int iCanvasHeight = m_cCanvas.getHeight();
int iCanvasWidth = m_cCanvas.getWidth();
// init matrix with same amount of elements as pixels in canvas
m_dAbsSqValues = new double[iCanvasHeight][iCanvasWidth];
m_iIterations = new int[iCanvasHeight][iCanvasWidth];
Complex cSum = new Complex();
if (m_bWriteLog) {
try
{
m_cBufferedWriter.write("m_iIterations[][] =");
m_cBufferedWriter.newLine();
}
catch (IOException ex)
{
System.out.println("Error opening file '" + m_sFileName + "'");
}
}
for (int i = 0; i < iCanvasHeight; i++)
{
for (int j = 0; j < iCanvasWidth; j++)
{
cSum.setRe(m_cCoordPlane[i][j].getRe());
cSum.setIm(m_cCoordPlane[i][j].getIm());
m_iIterations[i][j] = 0;
do
{
m_iIterations[i][j]++;
cSum.square();
cSum.add(m_cSummand);
m_dAbsSqValues[i][j] = cSum.getAbsSq();
} while ((m_iIterations[i][j] < MAXITER) && (m_dAbsSqValues[i][j] < m_iDivergThresh));
this.calcColour(i, j, m_iIterations[i][j]);
m_cMsgIter = "x = " + i + " , y = " + j;
if(m_bWriteLog)
{
System.out.println(m_cMsgIter);
System.out.flush();
}
if (m_bWriteLog) {
try
{
m_cBufferedWriter.write(Integer.toString(m_iIterations[i][j]));
m_cBufferedWriter.write(" ");
}
catch (IOException ex) {
System.out.println("Error writing to file '" + m_sFileName + "'");
}
}
}
if (m_bWriteLog) {
try
{
m_cBufferedWriter.newLine();
}
catch (IOException ex) {
System.out.println("Error writing to file '" + m_sFileName + "'");
}
}
}
m_dAbsSqValues = null;
m_iIterations = null;
cSum = null;
}
private void calcColour(int i, int j, int aIterations)
{
Color cColour = Color.getHSBColor((int) Math.pow(aIterations, 4), 0xff,
0xff * ((aIterations < MAXITER) ? 1 : 0));
m_cCanvas.setPixelColour(i, j, cColour);
cColour = null;
}
private void handleCalculation()
{
Complex cSummand = new Complex();
for(int i = -800; i <= 800; i++)
{
for(int j = -800; j <= 800; j++)
{
cSummand.setRe(((double)i)/1000.0);
cSummand.setIm(((double)j)/1000.0);
this.setSummand(cSummand);
this.calcAbsSqValues();
this.getCanvas().paint(m_cCanvas.getGraphics());
this.paint(this.getGraphics());
}
}
cSummand = null;
this.collectGarbage();
System.gc();
System.runFinalization();
}
public boolean isRunning()
{
return m_bRunning;
}
public void setRunning(boolean aRunning)
{
m_bRunning = aRunning;
}
public Canvas getCanvas()
{
return m_cCanvas;
}
public void run()
{
if(m_bRunning)
{
this.handleCalculation();
}
}
}
class JuliaCanvas extends Canvas
{
private int m_iWidth;
private int m_iHeight;
private Random m_cRnd;
private BufferedImage m_cBackGroundImage = null;
private int m_iRed[][];
private int m_iGreen[][];
private int m_iBlue[][];
JuliaCanvas(int aWidth, int aHeight)
{
m_iWidth = aWidth;
m_iHeight = aHeight;
m_cRnd = new Random();
m_cRnd.setSeed(m_cRnd.nextLong());
m_cBackGroundImage = new BufferedImage(m_iWidth, m_iHeight, BufferedImage.TYPE_INT_RGB);
m_iRed = new int[m_iHeight][m_iWidth];
m_iGreen = new int[m_iHeight][m_iWidth];
m_iBlue = new int[m_iHeight][m_iWidth];
}
public void init() {
}
public void setPixelColour(int i, int j, Color aColour)
{
m_iRed[i][j] = aColour.getRed();
m_iGreen[i][j] = aColour.getGreen();
m_iBlue[i][j] = aColour.getBlue();
}
private int getRandomInt(double aProbability)
{
return (m_cRnd.nextDouble() < aProbability) ? 1 : 0;
}
#Override
public void paint(Graphics aGraphics)
{
// store on screen graphics
Graphics cScreenGraphics = aGraphics;
// render on background image
aGraphics = m_cBackGroundImage.getGraphics();
for (int i = 0; i < m_iWidth; i++)
{
for (int j = 0; j < m_iHeight; j++)
{
Color cColor = new Color(m_iRed[i][j], m_iGreen[i][j], m_iBlue[i][j]);
aGraphics.setColor(cColor);
aGraphics.drawRect(i, j, 0, 0);
cColor = null;
}
}
// rendering is done, draw background image to on screen graphics
cScreenGraphics.drawImage(m_cBackGroundImage, 1, 1, null);
}
#Override
public void update(Graphics aGraphics)
{
paint(aGraphics);
}
}
class Complex {
private double m_dRe;
private double m_dIm;
public Complex()
{
m_dRe = 0;
m_dIm = 0;
}
public Complex(double aRe, double aIm)
{
m_dRe = aRe;
m_dIm = aIm;
}
public Complex(Complex aComplex)
{
m_dRe = aComplex.m_dRe;
m_dIm = aComplex.m_dIm;
}
public double getRe() {
return m_dRe;
}
public void setRe(double adRe)
{
m_dRe = adRe;
}
public double getIm() {
return m_dIm;
}
public void setIm(double adIm)
{
m_dIm = adIm;
}
public void add(Complex acComplex)
{
m_dRe += acComplex.getRe();
m_dIm += acComplex.getIm();
}
public void square()
{
double m_dReSave = m_dRe;
m_dRe = (m_dRe * m_dRe) - (m_dIm * m_dIm);
m_dIm = 2 * m_dReSave * m_dIm;
}
public double getAbsSq()
{
return ((m_dRe * m_dRe) + (m_dIm * m_dIm));
}
}
I'm quoting a recent comment from #MadProgrammer (including links)
"Swing is single threaded, nothing you can do to change that, all events are posted to the event queue and processed by the Event Dispatching Thread, see Concurrency in Swing for more details and have a look at Worker Threads and SwingWorker for at least one possible solution"
There is only one thread in your code. That thread is busy doing the calculation and can not respond to events located in the GUI. You have to separate the calculation in another thread that periodically updates the quantities that appears in the window. More info about that in the links, courtesy of #MadProgrammer, I insist.
UPDATED: As pointed by #Yusuf, the proper way of launching the JFrame is
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new JuliaSet("Julia Set", windowWidth, windowHeight, plotWidth, plotHeight);
}
});
Set the frame visible on construction and start calculation when the start button is pressed.
First;
Endless loop is not a proper way to do this. This part is loops and taking CPU and never give canvas to refresh screen. if you add below code your code will run as expected. but this is not the proper solution.
cMain.java:
while (true) {
cJuliaSet.run();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Second: you could call run method when start button clicked. But you should create a thread in run method to not freeze screen.
public static void main(String[] args) {
int windowWidth = 1000;// (int)screenSize.getWidth() - 200;
int windowHeight = 800;// (int)screenSize.getHeight() - 50;
int plotWidth = 400;// (int)screenSize.getWidth() - 600;
int plotHeight = 400;// (int)screenSize.getHeight() - 150;
JuliaSet cJuliaSet = new JuliaSet("Julia Set", windowWidth, windowHeight, plotWidth, plotHeight);
cJuliaSet.setVisible(true);
//While loop removed
}
actionPerformed:
if (strCmd.equals("Start")) {
m_cCanvas.init();
m_cSMsg = "c = " + Double.toString(m_dReal) + " + " + "j*" + Double.toString(m_dImag);
m_bRunning = true;
this.run(); // added call run method.
} else if (aActionEvent.getSource() == m_cTReal) {
run method:
public void run()
{
if(m_bRunning)
{
new Thread(){ //Thread to release screen
#Override
public void run() {
JuliaSet.this.handleCalculation();
}
}.start(); //also thread must be started
}
}
As said by #RubioRic, SwingUtilities.invokeLater method is also a part of solution. But you need to check whole of your code and you should learn about Threads.

JOptionPane.showInputDialog() is called twice, why?

In the showDebugWindow() method inside a class I called, [TinyDebug], the JOptionPane.showInputDialog() is called twice even after I input the correct password, why is that?
Additionally, this code is being executed from an update() method in my Game class, which is called once every second.
Take a look below at the following sets of code for the problem.
Game:
public class Game extends TinyPixel {
private static Game game;
private static KeyManager keyManager;
private static MouseManager mouseManager;
private static GameStateManager sManager;
private boolean isRunning;
private int targetTime;
private final int frameCap = 60;
public Game(String gameTitle, String gameVersion, int gameWidth, int gameRatio, int gameScale) {
super(gameTitle, gameVersion, gameWidth, gameRatio, gameScale);
init();
}
public void init() {
Utilities.printMessage("\t\t-[" + Library.gameTitle + "]-" +
"\n[Game Version]: " + gameVersion +
"\n[Unique Build Number]: " + Utilities.generateCode(16));
ResourceLoader.loadImages();
ResourceLoader.loadMusic();
ResourceLoader.loadSound();
ResourceLoader.loadFonts();
keyManager = new KeyManager(this);
mouseManager = new MouseManager(this);
sManager = new GameStateManager(this);
}
#Override public void update() {
sManager.update();
mouseManager.update();
}
#Override public void render() {
BufferStrategy bs = tinyWindow.getCanvas().getBufferStrategy();
if (bs == null) {
tinyWindow.getCanvas().createBufferStrategy(3);
tinyWindow.getCanvas().requestFocus();
return;
}
Graphics g = bs.getDrawGraphics();
g.clearRect(0, 0, gameWidth, gameHeight);
sManager.render(g);
g.dispose();
bs.show();
}
public void start() {
if(isRunning) return;
isRunning = true;
new Thread(this, gameTitle + " " + gameVersion).start();
}
public void stop() {
if(!isRunning) return;
isRunning = false;
}
#Override public void run() {
isRunning = true;
targetTime = 1000 / frameCap;
long start = 0;
long elapsed = 0;
long wait = 0;
while (isRunning) {
start = System.nanoTime();
update();
render();
elapsed = System.nanoTime() - start;
wait = targetTime - elapsed / 1000000;
if (wait < 0) wait = 5;
try {
Thread.sleep(wait);
} catch (InterruptedException e) {
Utilities.printErrorMessage("Failed to Load " + gameTitle + " " + gameVersion);
}
}
stop();
}
public static KeyManager getKeyManager() {
return keyManager;
}
public static GameStateManager getsManager() {
return sManager;
}
public static Game getGame() {
return game;
}
}
GameLauncher:
public class GameLauncher {
public static void main(String[] args) {
new Game(Library.gameTitle, Library.gameVersion, 640, TinyPixel.Square, 1).start();
}
}
GameStateManager:
public class GameStateManager {
private int numStates = 3;
public static final int MenuState = 0;
public static final int LoadingState = 1;
public static final int GameState = 2;
public static GameState[] gStates;
private static int currentState;
private static String currentMusic;
protected Game game;
public GameStateManager(Game game) {
this.game = game;
init();
}
private void init() {
gStates = new GameState[numStates];
currentState = MenuState;
//currentMusic = Library.backgroundMusic;
//TinyPlayer.playMusic(currentMusic);
loadState(currentState);
}
private void loadState(int gState) {
if (gState == MenuState) gStates[gState] = new MenuState(game, this);
if (gState == LoadingState) gStates[gState] = new LoadingState(game, this);
if (gState == GameState) gStates[gState] = new PlayState(game, this);
}
private void unloadState(int gState) {
gStates[gState] = null;
}
public void setState(int gState) {
unloadState(gState);
currentState = gState;
loadState(gState);
}
private void changeMusic(String key) {
if (currentMusic.equals(key)) return;
TinyPlayer.stopMusic(currentMusic);
currentMusic = key;
TinyPlayer.loop(currentMusic);
}
public void update() {
try {
gStates[currentState].update();
} catch (Exception e) {}
}
public void render(Graphics g) {
try {
gStates[currentState].render(g);
} catch (Exception e) {}
}
public static int getCurrentState() {
return currentState;
}
}
GameState:
public abstract class GameState {
protected Game game;
protected GameStateManager sManager;
public GameState(Game game, GameStateManager sManager) {
this.game = game;
this.sManager = sManager;
init();
}
public abstract void init();
public abstract void update();
public abstract void render(Graphics g);
}
MenuState:
public class MenuState extends GameState {
private Rectangle playBtn, exitBtn;
private TinyDebug tinyDebug;
public static final Color DEFAULT_COLOR = new Color(143, 48, 223);
public MenuState(Game game, GameStateManager sManager) {
super(game, sManager);
init();
}
public void init() {
tinyDebug = new TinyDebug();
int xOffset = 90, yOffset = 70;
playBtn = new Rectangle(Game.getWidth() / 2 - xOffset, Game.getHeight() / 2, 180, 40);
exitBtn = new Rectangle(Game.getWidth() / 2 - xOffset, Game.getHeight() / 2 + yOffset, 180, 40);
}
public void update() {
if (Game.getKeyManager().debug.isPressed()) {
Game.getKeyManager().toggleKey(KeyEvent.VK_Q, true);
tinyDebug.showDebugWindow();
}
if (Game.getKeyManager().space.isPressed()) {
Game.getKeyManager().toggleKey(KeyEvent.VK_SPACE, true);
sManager.setState(GameStateManager.LoadingState);
}
if (Game.getKeyManager().exit.isPressed()) {
Game.getKeyManager().toggleKey(KeyEvent.VK_ESCAPE, true);
System.exit(0);
}
}
public void render(Graphics g) {
//Render the Background
g.drawImage(Library.menuBackground, 0, 0, Game.getWidth(), Game.getHeight(), null);
//Render the Game Version
TinyFont.drawFont(g, new Font(Library.gameFont, Font.PLAIN, 8), Color.white, "Version: " + Library.gameVersion, Game.getWidth() / 2 + 245, Game.getHeight() - 30);
//Render the Social Section
TinyFont.drawFont(g, new Font(Library.gameFont, Font.PLAIN, 8), Color.white, "#nickadamou", 20, Game.getHeight() - 60);
TinyFont.drawFont(g, new Font(Library.gameFont, Font.PLAIN, 8), Color.white, "#nicholasadamou", 20, Game.getHeight() - 45);
TinyFont.drawFont(g, new Font(Library.gameFont, Font.PLAIN, 8), Color.white, "Ever Tried? Ever Failed? No Matter. Try Again. Fail Again. Fail Better.", 20, Game.getHeight() - 30);
//Render the Debug Section
tinyDebug.renderDebug(g);
g.setColor(Color.white);
g.drawRect(playBtn.x, playBtn.y, playBtn.width, playBtn.height);
g.drawRect(exitBtn.x, exitBtn.y, exitBtn.width, exitBtn.height);
TinyFont.drawFont(g, new Font(Library.gameFont, Font.PLAIN, 14), Color.white, "Play Game [space]", playBtn.x + 10, playBtn.y + 25);
TinyFont.drawFont(g, new Font(Library.gameFont, Font.PLAIN, 14), Color.white, "Exit Game [esc]", exitBtn.x + 20, exitBtn.y + 25);
}
}
keyManager:
public class KeyManager implements KeyListener {
private Game game;
public KeyManager(Game game) {
this.game = game;
game.getTinyWindow().getCanvas().addKeyListener(this);
}
public class Key {
private int amtPressed = 0;
private boolean isPressed = false;
public int getAmtPressed() {
return amtPressed;
}
public boolean isPressed() {
return isPressed;
}
public void toggle(boolean isPressed) {
this.isPressed = isPressed;
if (isPressed) amtPressed++;
}
}
public Key up = new Key();
public Key down = new Key();
public Key left = new Key();
public Key right = new Key();
public Key space = new Key();
public Key debug = new Key();
public Key exit = new Key();
public void keyPressed(KeyEvent key) {
toggleKey(key.getKeyCode(), true);
}
public void keyReleased(KeyEvent key) {
toggleKey(key.getKeyCode(), false);
}
public void keyTyped(KeyEvent e) {}
public void toggleKey(int keyCode, boolean isPressed) {
game.getTinyWindow().getFrame().requestFocus();
game.getTinyWindow().getCanvas().requestFocus();
if (keyCode == KeyEvent.VK_W || keyCode == KeyEvent.VK_UP) {
up.toggle(isPressed);
}
if (keyCode == KeyEvent.VK_S || keyCode == KeyEvent.VK_DOWN) {
down.toggle(isPressed);
}
if (keyCode == KeyEvent.VK_A || keyCode == KeyEvent.VK_LEFT) {
left.toggle(isPressed);
}
if (keyCode == KeyEvent.VK_D || keyCode == KeyEvent.VK_RIGHT) {
right.toggle(isPressed);
}
if (keyCode == KeyEvent.VK_SPACE) {
space.toggle(isPressed);
}
if (keyCode == KeyEvent.VK_Q) {
debug.toggle(isPressed);
}
if (keyCode == KeyEvent.VK_ESCAPE) {
exit.toggle(isPressed);
}
}
#SuppressWarnings("unused")
private void debug(KeyEvent key) {
System.out.println("[keyCode]: " + key.getKeyCode());
}
}
TinyDebug:
public class TinyDebug {
private final String appTitle = Library.gameTitle;
private String tinyPassword, tinyBuildCode;
private boolean isAllowedDebugging = false;
private boolean isShowingTinyText = false;
public TinyDebug() {
tinyPassword = "test123"; // - Standard Password (Non-Renewable)
//tinyPassword = Utilities.generateCode(16); // - Stronger Password (Renewable)
writePasswordToFile(tinyPassword);
tinyBuildCode = Utilities.generateCode(16);
}
//TODO: This method invokes JOptionPane.showInputDialog() twice even after I input the correct password, why?
public void showDebugWindow() {
boolean hasRun = true;
if (hasRun) {
Clipboard cBoard = Toolkit.getDefaultToolkit().getSystemClipboard();
cBoard.setContents(new StringSelection(tinyPassword), null);
if (isAllowedDebugging() && isShowingTinyText()) return;
String userPassword = JOptionPane.showInputDialog("Input Password to Enter [TinyDebug].");
do {
if (userPassword.equals(tinyPassword)) {
JOptionPane.showMessageDialog(null, "[" + appTitle + "]: The Password Entered is Correct.", appTitle + " Message", JOptionPane.PLAIN_MESSAGE);
isAllowedDebugging(true);
isShowingTinyText(true);
break;
} else {
JOptionPane.showMessageDialog(null, "[Error Code]: " + Utilities.generateCode(16) + "\n[Error]: Password is Incorrect.", appTitle + " Error Message", JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
} while (userPassword != null || userPassword.trim().isEmpty() != true);
}
hasRun = false;
}
#SuppressWarnings("unused")
public void renderDebug(Graphics g) {
if (isAllowedDebugging()) {
//TODO: Render Debug Information.
TinyFont.drawFont(g, new Font(Library.gameFont, Font.PLAIN, 8), Color.white, "Tiny Pixel [Debug]", 5, 10);
TinyFont.drawFont(g, new Font(Library.gameFont, Font.PLAIN, 8), Color.white, "#. [Options are Shown Here]", 10, 25);
if (isShowingTinyText()) {
String debugHeader = appTitle + " Information";
String debugPasswordField = appTitle + " Information:";
String debugBuildNumber = appTitle + " Unique Build #: " + getTinyBuildCode();
}
}
}
//TODO: This method prints the [Utilities.printMessage(appTitle + ": [tinyPassword] Generated and Stored # FilePath: \n" + logFile.getAbsolutePath());] twice, why?
private void writePasswordToFile(String tinyPassword) {
BufferedWriter bWriter = null;
try {
File logFile = new File("tinyPassword.txt");
Utilities.printMessage(appTitle + ": [tinyPassword] Generated and Stored # FilePath: \n" + logFile.getAbsolutePath());
bWriter = new BufferedWriter(new FileWriter(logFile));
bWriter.write(appTitle + " debug Password: " + tinyPassword);
} catch (Exception e) {
Utilities.printErrorMessage("Failed to Write [tinyPassword] to File.");
} finally {
try {
bWriter.close();
} catch (Exception e) {
Utilities.printErrorMessage("Failed to Close [bWriter] Object.");
}
}
}
public String getTinyPassword() {
return tinyPassword;
}
public String getTinyBuildCode() {
return tinyBuildCode;
}
public void isShowingTinyText(boolean isShowingTinyText) {
this.isShowingTinyText = isShowingTinyText;
}
public boolean isShowingTinyText() {
return isShowingTinyText;
}
public void isAllowedDebugging(boolean isAllowedDebugging) {
this.isAllowedDebugging = isAllowedDebugging;
if (isAllowedDebugging) showDebugWindow();
}
public boolean isAllowedDebugging() {
return isAllowedDebugging;
}
}
In showDebugWindow() method, you have this statement:
if (userPassword.equals(tinyPassword)) {
...
isAllowedDebugging(true); // Problematic statement
...
}
Which calls this method:
public void isAllowedDebugging(boolean isAllowedDebugging) {
this.isAllowedDebugging = isAllowedDebugging;
if (isAllowedDebugging) showDebugWindow(); // Second call?
}
As you see, when you set isAllowedDebugging switch, you also call the method, so when you enter password correct, this second call happens.

RMS stored values are not permanently available in J2ME emulator

I have code to stored the value using RMS in J2ME. It's working fine on emulator. So, my first problem is
When i restart the emulator all the stored values are deleted.
Stored values are showing in the emulator, but not in the Mobile, in which i am testing my application.
I am using NetBeans for developing my J2ME application.
===UPDATED===
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import javax.microedition.rms.*;
public class TryNew extends MIDlet implements CommandListener, ItemCommandListener {
private RecordStore record;
private StringItem registered;
static final String REC_STORE = "SORT";
//Button existUser;
Display display = null;
private Ticker ticker;
Form form = null;
Form form1 = null;
TextField tb, tb1, tb2, tb3;
ChoiceGroup operator = null;
String str = null;
Command backCommand = new Command("Back", Command.BACK, 0);
Command loginCommand = new Command("Login", Command.OK, 2);
Command saveCommand = new Command("Save New", Command.OK, 1);
Command sendCommand = new Command("Send", Command.OK, 2);
Command selectCommand = new Command("Select", Command.OK, 0);
Command exitCommand = new Command("Exit", Command.STOP, 3);
private ValidateLogin ValidateLogin;
public TryNew() {
}
public void startApp() throws MIDletStateChangeException {
display = Display.getDisplay(this);
form = new Form("Login");
registered = new StringItem("", "Registered ?", StringItem.BUTTON);
form1 = new Form("Home");
tb = new TextField("Login Id: ", "", 10, TextField.PHONENUMBER);//TextField.PHONENUMBER
tb1 = new TextField("Password: ", "", 30, TextField.PASSWORD);
operator = new ChoiceGroup("Select Website", Choice.POPUP, new String[]{"Game", "Joke", "SMS"}, null);
form.append(tb);
form.append(tb1);
form.append(operator);
form.append(registered);
registered.setDefaultCommand(selectCommand);
registered.setItemCommandListener(this);
form.addCommand(saveCommand);
ticker = new Ticker("Welcome Screen");
form.addCommand(loginCommand);
form.addCommand(selectCommand);
form.addCommand(exitCommand);
// existUser = new StringItem(null, "Registered ?");
// form.append(existUser);
form.setCommandListener(this);
form1.addCommand(exitCommand);
form1.addCommand(sendCommand);
form1.setCommandListener(this);
form.setTicker(ticker);
display.setCurrent(form);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
void showMessage(String message, Displayable displayable) {
Alert alert = new Alert("");
alert.setTitle("Error");
alert.setString(message);
alert.setType(AlertType.ERROR);
alert.setTimeout(5000);
display.setCurrent(alert, displayable);
}
public void commandAction(Command c, Displayable d) {
if (c == exitCommand) {
destroyApp(true);
notifyDestroyed();
} else if (c == backCommand) {
display.setCurrent(form);
} else if (c == loginCommand) {
ValidateLogin = new ValidateLogin(this);
ValidateLogin.start();
ValidateLogin.validateLogin(tb.getString(), tb1.getString(), operator.getString(operator.getSelectedIndex()));
} else if (c == saveCommand) {
openRecord();
writeRecord(tb.getString(), tb1.getString(), operator.getString(operator.getSelectedIndex()));
closeRecord();
showAlert("Login Credential Saved Successfully !!");
}
}
////==============================================================================/////
/// Record Management
public void openRecord() {
try {
record = RecordStore.openRecordStore(REC_STORE, true);
} catch (Exception e) {
db(e.toString());
}
}
public void closeRecord() {
try {
record.closeRecordStore();
} catch (Exception e) {
db(e.toString());
}
}
public void deleteRecord() {
if (RecordStore.listRecordStores() != null) {
try {
RecordStore.deleteRecordStore(REC_STORE);
} catch (Exception e) {
db(e.toString());
}
}
}
public void writeRecord(String login_id, String pwd, String operator_name) {
String credential = login_id + "," + pwd + "," + operator_name;
byte[] rec = credential.getBytes();
try {
if (login_id.length() > 10 || login_id.length() < 10) {
showAlert("Please Enter valid Login Id");
} else if (pwd.length() < 1) {
showAlert("Please Password !!");
} else {
record.addRecord(rec, 0, rec.length);
}
} catch (Exception e) {
db(e.toString());
}
}
private void showAlert(String err) {
Alert a = new Alert("");
a.setString(err);
a.setTimeout(Alert.FOREVER);
display.setCurrent(a);
}
public void readRecord() {
try {
if (record.getNumRecords() > 0) {
Comparator comp = new Comparator();
RecordEnumeration re = record.enumerateRecords(null, comp, false);
while (re.hasNextElement()) {
String str = new String(re.nextRecord());
showAlert(str);
}
}
} catch (Exception e) {
db(e.toString());
}
}
private void db(String error) {
System.err.println("Exception: " + error);
}
public void commandAction(Command c, Item item) {
if (c == selectCommand && item == registered) {
openRecord();
readRecord();
closeRecord();
}
}
class Comparator implements RecordComparator {
public int compare(byte[] rec1, byte[] rec2) {
String str1 = new String(rec1);
String str2 = new String(rec2);
int result = str1.compareTo(str2);
if (result == 0) {
return RecordComparator.EQUIVALENT;
} else if (result < 0) {
return RecordComparator.PRECEDES;
} else {
return RecordComparator.FOLLOWS;
}
}
}
class ValidateLogin implements Runnable {
TryNew midlet;
private Display display;
String login_id;
String pwd;
String operator_name;
public ValidateLogin(TryNew midlet) {
this.midlet = midlet;
display = Display.getDisplay(midlet);
}
public void start() {
Thread t = new Thread(this);
t.start();
}
public void run() {
if (login_id.length() > 10 || login_id.length() < 10) {
showAlert("Please Enter valid Login Id");
} else if (pwd.length() < 1) {
showAlert("Please Password !!");
} else {
showHome();
}
}
/* This method takes input from user like text and pass
to servlet */
public void validateLogin(String login_id, String pwd, String operator_name) {
this.login_id = login_id;
this.pwd = pwd;
this.operator_name = operator_name;
}
/* Display Error On screen*/
private void showAlert(String err) {
Alert a = new Alert("");
a.setString(err);
a.setTimeout(Alert.FOREVER);
display.setCurrent(a);
}
private void showHome() {
tb2 = new TextField("To: ", "", 30, TextField.PHONENUMBER);
tb3 = new TextField("Message: ", "", 300, TextField.ANY);
form1.append(tb2);
form1.append(tb3);
form1.addCommand(loginCommand);
//display.setCurrent(tb3);
display.setCurrent(form1);
}
};
}
This is what i got, when i click the Manage Emulator
You need to fix the storage_root of your app in WTK,
Whenever you start your enulator it would refer to same storage_root, by default it creates different data files for each session

Categories