I tried to make this GUI program which take input from the user by text field and should return it with uppercase convertion:   import javax.swing.*; import java.awt.*; import java.awt.event.*;  public class gui {  JTextField textField;  JFrame frame;  JButton button;  public static void main(String args[]) {     gui tr = new gui();     tr.go(); }  public void go() {       JFrame frame = new JFrame();     JTextField textField = new JTextField("Type here);     JButton button = new JButton("Send");     button.addActionListener(new buttonListener());     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);     frame.getContentPane().add(BorderLayout.CENTER, textField);     frame.getContentPane().add(BorderLayout.SOUTH, button);     frame.setSize(300, 300);     frame.setVisible(true);  }  class buttonListener implements ActionListener {     public void actionPerformed(ActionEvent event) {         String txt;         txt = textField.getText();         txt = txt.toUpperCase();         textField.setText(txt);     } } }   The file respond by null pointer exception. Ive tried to add exception handler, and to change the program based on instances Ive seen online. please explain to me my mistake. Thank you.
129
What are Null Pointer Exceptions (java.lang.NullPointerException) and what causes them?  What methods/tools can be used to determine the cause so that you stop the exception from causing the program to terminate prematurely?
85933
I was writing a toString() for a class in Java the other day by manually writing out each element of the class to a String and it occurred to me that using reflection it might be possible to create a generic toString() method that could work on ALL classes. I.E. it would figure out the field names and values and send them out to a String.  Getting the field names is fairly simple, here is what a co-worker came up with:  public static List initFieldArray(String className) throws ClassNotFoundException {      Class c = Class.forName(className);     Field field[] = c.getFields();     List&lt;String&gt; classFields = new ArrayList(field.length);      for (int i = 0; i &lt; field.length; i++) {         String cf = field[i].toString();         classFields.add(cf.substring(cf.lastIndexOf(".") + 1));     }      return classFields; }   Using a factory I could reduce the performance overhead by storing the fields once, the first time the toString() is called. However finding the values could be a lot more expensive.  Due to the performance of reflection this may be more hypothetical then practical. But I am interested in the idea of reflection and how I can use it to improve my everyday programming.
84342
I have a JFrame. This JFrame contains a JButton. I click the JButton and 10 JTextFields are created.  the problem: I cannot see them until "I force a repaint()" by resizing the window. Only then do I see the JTextFields created.  CODE:  JPanel points = new JPanel();  //Creating the JTextFields: for (int i=0; i&lt;10; i++) {     JTextField textField = new JTextField();     points.add(textField); }  repaint(); this.repaint(); super.repaint(); points.repaint();     THANK YOU - after the for loop, I just called points.validate() and it worked...
86715
I'm looking at some GXT code for GWT and I ran across this use of Generics that I can't find another example of in the Java tutorials. The class name is  if you want to look at all of the code.  Here are the important parts:  private RpcMap map;  public &lt;X&gt; X get(String property) {   if (allowNestedValues &amp;&amp; NestedModelUtil.isNestedProperty(property)) {     return (X)NestedModelUtil.getNestedValue(this, property);   }   return map == null ? null : (X) map.get(property); }   X is defined nowhere else in the class or anywhere in the hierarchy, and when I hit "go to declaration" in eclipse it just goes to the &lt;X&gt; in the public method signature.  I've tried to call this method with the following two examples to see what happens:  public Date getExpiredate() {     return  get("expiredate"); }  public String getSubject() {     return  get("subject"); }   They compile and show no errors or warnings.  I would think at the very least I would have to do a cast to get this to work.  Does this mean that Generics allow a magic return value that can be anything and will just blow up at runtime?  This seems counter to what generics are supposed to do.  Can anyone explain this to me and possibly give me a link to some documentation that explains this a little better?  I've went through Sun's 23 page pdf on generics and every example of a return value is defined either at the class level or is in one of the parameters passed in.
5329
I'm building a function to extend the Enum.Parse concept that  Allows a default value to be parsed in case that an Enum value is not found Is case insensitive  So I wrote the following: public static T GetEnumFromString&lt;T&gt;(string value, T defaultValue) where T : Enum {     if (string.IsNullOrEmpty(value)) return defaultValue;     foreach (T item in Enum.GetValues(typeof(T)))     {         if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item;     }     return defaultValue; }  I am getting a Error Constraint cannot be special class System.Enum. Fair enough, but is there a workaround to allow a Generic Enum, or am I going to have to mimic the Parse function and pass a type as an attribute, which forces the ugly boxing requirement to your code. EDIT All suggestions below have been greatly appreciated, thanks. Have settled on (I've left the loop to maintain case insensitivity - I am using this when parsing XML) public static class EnumUtils {     public static T ParseEnum&lt;T&gt;(string value, T defaultValue) where T : struct, IConvertible     {         if (!typeof(T).IsEnum) throw new ArgumentException(&quot;T must be an enumerated type&quot;);         if (string.IsNullOrEmpty(value)) return defaultValue;          foreach (T item in Enum.GetValues(typeof(T)))         {             if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item;         }         return defaultValue;     } }  EDIT: (16th Feb 2015) Christopher Currens has posted  below, which is well worth a look, and an upvote. I will remove this edit if the solution bubbles further up the page. EDIT 2: (13th Apr 2021) As this has now been addressed, and supported, since C# 7.3, I have changed the accepted answer, though full perusal of the top answers is worth it for academic, and historical, interest :)
119341
I'm pretty new to programming and made a few programs so far. I recently made a Calculator program and I hope you guys could tell me what I could do to improve. int firstNumber; string sign; int secondNumber; int answer;  Console.WriteLine(&quot;Input Number:&quot;); firstNumber = Convert.ToInt32(Console.ReadLine()); Console.Clear();  Console.WriteLine(&quot;Input Sign:&quot;); sign = Console.ReadLine(); Console.Clear();  Console.WriteLine(&quot;Input Second Number:&quot;); secondNumber = Convert.ToInt32(Console.ReadLine()); Console.Clear();  switch (sign) {     case &quot;+&quot;:         answer = firstNumber + secondNumber;         Console.WriteLine(answer);         Console.ReadKey();     break;     case &quot;-&quot;:         answer = firstNumber - secondNumber;         Console.WriteLine(answer);         Console.ReadKey();     break;     case &quot;*&quot;:         answer = firstNumber * secondNumber;         Console.WriteLine(answer);         Console.ReadKey();     break;     case &quot;/&quot;:         answer = firstNumber / secondNumber;         Console.WriteLine(answer);         Console.ReadKey();     break;     default:         Console.WriteLine(&quot;Invalid Input&quot;);     break; }
85236
Here is my complete code sample   global class b1 implements Database.Batchable&lt;sObject&gt; {   global final string query;  global final string s_object;  global final string field;  global final string field_value;   global b1 (string q, string s, string f, string v){        Query =q;        s_object=s;        field = f;       field_value =v;    }    global Database.QueryLocator start (Database.BatchableContext BC){   return Database.getQueryLocator (query);   }    global void excute(Database.BatchableContext BC, List&lt;sObject&gt; batch) {   for(s_object o= batch){   o.put(field,field_valu);    }   update batch;   }     global void finish(Database.BatchableContext BC){    } }
49022
How can I send keyboard input messages to either the currently selected window or the previously selected window?   I have a program which I use to type some characters which are not present on my keyboard and I would like it if I could just send the input directly rather than me having to copy and paste all the time.  EDIT:  The application of this is typing the German Umlauts. I'm an American and I work in Germany. I'm working on an American keyboard and from time to time I have to type in the umlauts / the euro symbol / the sharp S. Currently I have a simple WinForms application with a textfield and some buttons with the extra characters on it. I type into the textfield and I can press the buttons to append text to the textfield. I then copy the text and paste it where ever. What would be nice though if I could just just hit one of the buttons and it would send the text where ever I'm typing / was typing. The current program works fairly well but I could make it better.
113428
is a simple way to script small GUIs.  Can anyone give a nice example with a button and a text widget. When the button is pressed should a shell command be executed and the output piped to the text widget.  If you have other nice and clean examples for useful tasks, please add them too.
366
Let's say we have this code for a LWC:  &lt;!-- helloExpressions.html --&gt; &lt;template&gt;     &lt;div class="slds-m-around_medium"&gt;         &lt;lightning-input name='firstName' label="First Name" onchange={handleChange}&gt;&lt;/lightning-input&gt;         &lt;lightning-input name='lastName' label="Last Name" onchange={handleChange}&gt;&lt;/lightning-input&gt;         &lt;p class="slds-m-top_medium"&gt;Uppercased Full Name: {uppercasedFullName}&lt;/p&gt;     &lt;/div&gt; &lt;/template&gt;   and this is the JS file:  // helloExpressions.js import { LightningElement, track } from 'lwc';  export default class HelloExpressions extends LightningElement {     @track firstName = '';     @track lastName = '';      handleChange(event) {         const field = event.target.name;         if (field === 'firstName') {             this.firstName = event.target.value;         } else if (field === 'lastName') {             this.lastName = event.target.value;         }     }      get uppercasedFullName() {         return `${this.firstName} ${this.lastName}`.toUpperCase();     } }   firstName and lastName have been decorated with @track. Now as per the documentation, decorating a property with @track makes it private and reactive, while to mark a property public and reactive, use @api.  So if I just change the decorator to @api for both these variables, it should work. I am referring these from the same component only. But it's not working.  UPDATE: 27th Feb -------------------- Somehow it's working today. I just changed the decorator of the variables to api.  import { LightningElement, api } from 'lwc';  export default class HelloExpressions extends LightningElement {     @api firstName = '';     @api lastName = '';      handleChange(event) {         const field = event.target.name;         if (field === 'firstName') {             this.firstName = event.target.value;         } else if (field === 'lastName') {             this.lastName = event.target.value;         }     }      get uppercasedFullName() {         return `${this.firstName} ${this.lastName}`.toUpperCase();     } }   So it's working.
15861
I was wondering if there was some kind of J tool in the java swing library that opens up a file browser window and allows a user to choose a file. Then the ouput of the file would be the absolute path of the chosen file.  Thanks in advance,
32831
If you have a java.io.InputStream object, how should you process that object and produce a String?    Suppose I have an InputStream that contains text data, and I want to convert it to a String, so for example I can write that to a log file.  What is the easiest way to take the InputStream and convert it to a String?  public String convertStreamToString(InputStream is) {     // ??? }
62286
I need to make some reflective method calls in Java. Those calls will include methods that have arguments that are primitive types (int, double, etc.). The way to specify such types when looking up the method reflectively is int.class, double.class, etc.  The challenge is that I am accepting input from an outside source that will specify the types dynamically. Therefore, I need to come up with these Class references dynamically as well. Imagine a delimited file a list of method names with lists of parameter types:  doSomething int double doSomethingElse java.lang.String boolean   If the input was something like java.lang.String, I know I could use Class.forName("java.lang.String") to that Class instance back. Is there any way to use that method, or another, to get the primitive type Classes back?  Edit: Thanks to all the respondents. It seems clear that there is no built-in way to cleanly do what I want, so I will settle for reusing the ClassUtils class from the Spring framework. It seems to contain a replacement for Class.forName() that will work with my requirements.
57572
I normally use the following idiom to check if a String can be converted to an integer.  public boolean isInteger( String input ) {     try {         Integer.parseInt( input );         return true;     }     catch( Exception e ) {         return false;     } }   Is it just me, or does this seem a bit hackish?  What's a better way?    See my answer (with benchmarks, based on the  by ) to see why I've reversed my position and accepted  to this problem.  I think this original code will be used by most people because it's quicker to implement, and more maintainable, but it's orders of magnitude slower when non-integer data is provided.
7351
I have an inline code example with a nested Java generic declaration, using the typewriter typeface. However, the closing &gt;&gt; is rendering as a black box. A cursory Google search suggested $&gt;&gt;$, but this removes the typewriter font. Using \textgreater in place of the actual &gt; also encounters the same problem. Here is the offending snippet:  ...declaration {\tt List&lt;Map&lt;Integer, String&gt;&gt;} is...   Any ideas?
118126
G'day all,   I have a console project where it is intended the user presses the keyboard direction keys (non-numeric keypad) to move an avatar. I am having difficulty coding to check for the press of these keys. In Pascal it was easy enough to use "readkey" and code, for example, for #80 for the down keypress. However, I am stumped how to implement the same functionality in Java, though I think I understand the use of System.in and BufferedInputStream.  Could anyone help me out? Your thoughts or hints are much appreciated.
116230
We have a user provided string that may contain unicode characters, and we want the robot to type that string.  How do you convert a string into keyCodes that the robot will use? How do you do it so it is also java version independant (1.3 -> 1.6)?  What we have working for "ascii" chars is  //char c = nextChar(); //char c = 'a'; // this works, and so does 'A' char c = 'á'; // this doesn't, and neither does 'Ă' Robot robot = new Robot(); KeyStroke key = KeyStroke.getKeyStroke("pressed " + Character.toUpperCase(c) ); if( null != key ) {   // should only have to worry about case with standard characters   if (Character.isUpperCase(c))   {     robot.keyPress(KeyEvent.VK_SHIFT);   }    robot.keyPress(key.getKeyCode());   robot.keyRelease(key.getKeyCode());    if (Character.isUpperCase(c))   {     robot.keyRelease(KeyEvent.VK_SHIFT);   } }