How do I properly read numbers from awt textfields? - java

I've written a GUI for a simulation project that I'm doing, and in the event handling code of the window, I have, for instance,
private void timestepKeyTyped(java.awt.event.KeyEvent evt) {
String text = timestep.getText();
AMEC.steptime = Integer.parseInt(text);
}
where I would like to assign any input typed into field timestep to be assigned to AMEC.steptime. I do this for all textfields.
However, my simulation doesn't run properly when passed these parameters, and upon debugging I found that only the first character gets parsed to int. For instance, if I type "31", then the value assigned to AMEC.steptime becomes 3 instead of 31.
How do I fix this?

The problem you are facing is that you are using a KeyListener. Just don't use it, use an ActionListener and when you hit ENTER actionPerformed is executed. Then you can put the same code an will run like a charm.
Use swing not awt.
Example how to use it:
import first:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JTextField;
Then in somewhere in your code
JTextField textfield = new JTextField();
textfield.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
JTextField timestep =(JTextField) e.getSource();// you could use this or just your variable.
String text = timestep.getText();
AMEC.steptime = Integer.parseInt(text);
}
});
As a side note, you would be interested in only allowing in this textfield number values. Read more in how to make it in this previous question.
Restricting JTextField input to Integers

Related

Updating a jLabel

I have a simple GUI that has a jTextField that waits for the user to put in something. After a button is clicked, the program:
reads the input, saves it in a String variable;
opens a new GUI (that is in a separate class file), which contains an empty jLabel, and passes the String variable to it, changing the jLabel text to it.
The problem is that no matter how hard I try to reconfigure the code, adding things like repaint(), revalidate(), etc., the jLabel in the second GUI stays empty. Using a System.out.println(jLabel.getText()) reveals that the text value is indeed changed, but not displayed. How do I "refresh" this jLabel, so it'd show what I want it to? I'm aware I could add an event, though I don't want the user to click anything to refresh the GUI, the values should be there as it's initiated. I've read trough several similar posts, but found that the solutions don't work for me.
The code of first GUI's button click event:
private void sbuttonActionPerformed(java.awt.event.ActionEvent evt) {
errortext.setText("");
Search = sfield.getText();
Transl = hashes.find(Search);
if (Transl.equals("0")) errortext.setText("Word not found in database.");
else {
ws.run(Search, Transl); // <- this opens the second GUI, with two String parameters I want to display in the second GUI;
}
}
The code of the second GUI (activeword and translation are the jLabels that are giving me trouble.):
public void run(String Search, String Transl) {
WordScreen init = new WordScreen(); //initialise the second GUI;
init.setVisible(true);
activeword.setText(Search);
translation.setText(Transl);
}
Any reply is very welcome! Please ask me for more information about the code if necessary, I will make sure to reply as soon as possible!
Best solution: change WordScreen's constructor to accept the two Strings of interest:
From this:
public void run(String Search, String Transl) {
WordScreen init = new WordScreen(); //initialise the second GUI;
init.setVisible(true);
activeword.setText(Search);
translation.setText(Transl);
}
to this:
public void run(String search, String transl) {
WordScreen init = new WordScreen(search, transl);
init.setVisible(true);
}
Then in the WordScreen constructor use those Strings where needed:
public WordScreen(String search, String transl) {
JLabel someLabel = new JLabel(search);
JLabel otherLabel = new JLabel(transl);
// put them where needed
}
Note that I cannot create a comprehensive answer without your posting a decent MRE
As an aside, you will want to learn and use Java naming conventions. Variable names should all begin with a lower letter while class names with an upper case letter. Learning this and following this will allow us to better understand your code, and would allow you to better understand the code of others.

how to print a glyph of supplementary characters in java onto my JTextField when i just click the button

I have a simple program just need to set the character whose Unicode value larger the character data type (supplementary character) on JTextField when the button is click .Tell me i am really fed up and how i will do it .This problem have already taken my 4 days.
//importing the packages
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
//My own custom class
public class UnicodeTest implements ActionListener
{
JFrame jf;
JLabel jl;
JTextField jtf;
JButton jb;
UnicodeTest()
{
jf=new JFrame();// making a frame
jf.setLayout(null); //seting the layout null of this frame container
jl=new JLabel("enter text"); //making the label
jtf=new JTextField();// making a textfied onto which a character will be shown
jb=new JButton("enter");
//setting the bounds
jl.setBounds(50,50,100,50);
jtf.setBounds(50,120,400,100);
jb.setBounds(50, 230, 100, 100);
jf.add(jl);jf.add(jtf);jf.add(jb);
jf.setSize(400,400);
jf.setVisible(true); //making frame visible
jb.addActionListener(this); // registering the listener object
}
public void actionPerformed(ActionEvent e) // event generated on the button click
{ try{
int x=66560; //to print the character of this code point
jtf.setText(""+(char)x);// i have to set the textfiled with a code point character which is supplementary in this case
}
catch(Exception ee)// caughting the exception if arrived
{ ee.printStackTrace(); // it will trace the stack frame where exception arrive
}
}
// making the main method the starting point of our program
public static void main(String[] args)
{
//creating and showing this application's GUI.
new UnicodeTest();
}
}
Since you are not giving enough information on what's wrong, I can only guess that either or both:
You are not using a font that can display the character.
You are not giving the text field the correct string representation of the text.
Setting a font that can display the character
Not all fonts can display all characters. You have to find one (or more) that can and set the Swing component to use that font. The fonts available to you are system dependent, so what works for you might not work for others. You can bundle fonts when you deploy your application to ensure it works for everyone.
To find a font on your system that can display your character, I used
Font[] fonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts();
for (Font f : fonts) {
if (f.canDisplay(66560)) {
System.out.println(f);
textField.setFont(f.deriveFont(20f));
}
}
The output (for me) is a single font, so I allowed myself to set it in the loop:
java.awt.Font[family=Segoe UI Symbol,name=Segoe UI Symbol,style=plain,size=1]
as also noted in the comments to the question by Andrew Thompson.
Giving the text field the correct string representation
The text fields require UTF-16. Supplementary characters in UTF-16 are encoded in two code units (2 of these: \u12CD). Assuming you start from a codepoint, you can convert it to characters and then make a string from them:
int x = 66560;
char[] chars = Character.toChars(x); // chars [0] is \uD801 and chars[1] is \uDC00
textField.setText(new String(chars)); // The string is "\uD801\uDC00"
// or just
textField.setText(new String(Character.toChars(x)));
as notes by Andrew Thompson in the comments to this answer (previously I used a StringBuilder).

How to send key press input into a browser via code (e.g. java)

I plan on writing a solver to the recently popular 2048 game
github link
I'm wondering how I could go about this without actually building the game first then solving it... My question is: Is there a way I can send key presses (e.g. 'left' 'right' 'up' and 'down' ) into a web-browser via some sort of language like java/c?
Sorry if this question has been posted before, I was not sure how to actually phrase the question and could not find any results.
use keybd_event function to send key press,
example :
keybd_event(VK_UP,0xE0,0,0);//do click, it will be stay pressed until you release it
keybd_event(VK_UP,0xE0,KEYEVENTF_KEYUP,0);//release click
the second parameter is scan code,there is a list of make and break scan codes for each key
http://stanislavs.org/helppc/make_codes.html,
and here you can find the virtual key codes
http://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx
Using Java applets you can add a text listener to your component and capture the Keystrokes. For example, in the code below you are capturing the keystrokes of a textbox.
import java.awt.event.*;
import java.awt.*;
import java.applet.*;
public class KeyReader extends Applet{
private static final long serialVersionUID = 1L;
public void init(){
TextField textBox = new TextField(" ");
add(textBox);
textBox.addKeyListener (new KeyAdapter() {
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
System.out.println("You Pressed " + keyCode);
}
}
);
}
}

Wrong behavior in concatenation of strings when allignment of component is "RIGHT_TO_LEFT"

private JTextField resultTextField = new JTextField("0");
resultTextField.setFont(textFieldFont);
resultTextField.setBounds(COMMON_X, COMMON_Y, 180, 50);
resultTextField.applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
add(resultTextField);
I have created a JTextField as above.My application consists of number buttons and '.'. When I click on number buttons they get appended right (i.e. "5" on 5 click and then "52" on 2 click). But on clicking the '.' button the expected result is "5." but the it is displayed as ".5" and then on clicking "2" , "5.2" is displayed.
Where could I be going wrong?
I'm guessing (from your tags) that you're programming a calculator of some sort and that you want to achieve right-aligned text, not right-to-left-oriented text.
Right-to-left orientation is used for e.g. arabic languages, which are written (you guessed it) from right to left, instead of the "western" way of writing from left to right.
I suggest you remove the applyComponentOrientation() and look at setHorizontalAlignment instead.
PS: that being said, I can't really tell why '5'+'.' is '.5', but '5'+'.'+'2' is displayed as '5.2'.
I got interested, and produced the following SSCCE:
import java.awt.ComponentOrientation;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class BasicFrame extends JFrame
{
public static void main(String[] args)
{
BasicFrame frame = new BasicFrame();
frame.go();
}
private void go()
{
JTextField resultTextField = new JTextField("0");
resultTextField.applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
add(resultTextField);
pack();
setVisible(true);
}
}
So now I have the same question: If I clear the field and enter "123", it appears as "123"; when I click the period key (either of them), the field then shows ".123"; if I then enter "abc", the field shows "123.abc"; the period jumps to the right of the displayed string when I enter the 'a'. This does not follow what a former boss of mine called the "principle of least atstonishment"...

Java Hangman Project: Action Listener

I am creating a hangman game. I made a button A - Z using the GUI Toolbars in Netbeans as follows:.
My problem is, how can I add an actionlistener to all of it. Is it possible to use a loop? If i click the button A, i will get the character 'a' and so on..
Yes it is possible to use a loop, but since your JButtons were created by using NetBeans code-generation, they won't be in an array or collection initially, and so this is something that you'll have to do: create an array of JButton and fill it with the buttons created by NetBeans. Then it's a trivial matter to create a for loop and in that loop add an ActionListener that uses the ActionEvent's actionCommand (as noted above) in its logic.
Having said this, I think that the better solution is to forgo use of the NetBean's GUI builder (Matisse) and instead to create your Swing code by hand. This will give you much greater control over your code and a much better understanding of it as well. For instance, if you do it this way, then in your for loop you can both create your buttons, add the listeners, and add the button to its container (JPanel).
e.g.,
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
public class Foo2 {
public static void main(String[] args) {
JPanel buttonContainer = new JPanel(new GridLayout(3, 9, 10, 10));
List<JButton> letterButtons = new ArrayList<JButton>(); // *** may not even be necessary
for (char buttonChar = 'A'; buttonChar <= 'Z'; buttonChar++) {
String buttonText = String.valueOf(buttonChar);
JButton letterButton = new JButton(buttonText);
letterButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String actionCommand = e.getActionCommand();
System.out.println("actionCommand is: " + actionCommand);
// TODO fill in with your code
}
});
buttonContainer.add(letterButton);
letterButtons.add(letterButton);
}
JOptionPane.showMessageDialog(null, buttonContainer);
}
}
Well, with some pseudo code, wouldn't this make sence for you?
for(button in bord) {
button.addActionListener(my_actionlistener);
}
Then in your actionlistener you can see which button was pressed
public void actionPerformed(ActionEvent e) {
// button pressed
if ("string".equals(e.getActionCommand()) {
// do something
}
// and so forth
}
You'll need to add the buttons to a list of some kind so you can iterate through them, Netbeans doesn't do this for you when you generate the buttons.
After that, just run a for each loop on the list containing all the buttons. To get the values of the characters just cast the relevant ascii value, which starts at 97 for a lower case a or 65 for an upper case A:
int charNum = 97;
for(Button b : board) {
char charVal = (char)charNum;
charNum++;
//add the action listener
}

Categories

Resources