I am trying to access java swing components from a different class. For example, I need to change the text on a button once a specific operation has been completed. I am trying to use "getters" and "setters" to do the operation(at the bottom of the section of code.) Right now I only want to "set" the text.    I have another class that calls the "set" method and tries to set the text of the chosen button. This is the main class. The line of code that is "gui.setProcessItemBtn().setText("Some Text");" Throws:      Exception in thread "main" java.lang.NullPointerException   I believe this means that there isnt anything to set the text to. Am i missing something to link my setter methods to the actual gui components?      Main class   package book; import book.UserInterface;  /**  *  * @author KJ4CC  */ public class Book   {     /**      * @param args the command line arguments      */     public static void main(String[] args) {        UserInterface gui = new UserInterface();        gui.startUI();        gui.setProcessItemBtn().setText("Some Text");     }  }   User Interface class       public class UserInterface extends JFrame {         private JButton processItem;         private JButton confirmItem;         private JButton viewOrder;         private JButton finishOrder;         private JButton newOrder;         private JButton exit;          public void startUI(){              UserInterface gui = new UserInterface();             gui.bookingUI();         }          public static void  bookingUI(){             //sets windows, and pane in the UI              JFrame frame = new JFrame("Ye old Book stoppe");             frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);             JPanel toppane = new JPanel(new GridBagLayout());             JPanel bottomPane = new JPanel(new GridBagLayout());             GridBagConstraints c = new GridBagConstraints();             frame.setSize(800, 300);             frame.setVisible(true);             //adds labels  to the window         //----------------------------------------------------------BUTTOM PANE-------------------------         //setting up buttons to be placed onto the bottompanel          JButton processItem = new JButton("Process Item");         JButton confirmItem = new JButton("Confirm Item");         JButton viewOrder = new JButton("View Order");         JButton finishOrder = new JButton("Finish Order ");         JButton newOrder = new JButton("New Order");         JButton exit = new JButton("Exit");         //adding the buttons to the pane.---------------------------------------------------------------         GridBagConstraints b = new GridBagConstraints();         b.insets = new Insets(5,5,5,5);         b.ipadx = 10;         b.ipady = 10;         b.gridx = 1;         b.gridy = 0;         bottomPane.add(processItem, b);         b.gridx = 2;         b.gridy = 0;         bottomPane.add(confirmItem,b);         confirmItem.setEnabled(false);         b.gridx = 3;         b.gridy = 0;         bottomPane.add(viewOrder, b);         viewOrder.setEnabled(false);         b.gridx = 4;         b.gridy = 0;         bottomPane.add(finishOrder,b);         finishOrder.setEnabled(false);         b.gridx = 5;         b.gridy = 0;         bottomPane.add(newOrder,b);         b.gridx = 6;         b.gridy = 0;         bottomPane.add(exit, b);         bottomPane.setBackground(Color.BLUE);         frame.add(bottomPane,BorderLayout.SOUTH);         frame.setSize(810, 310);           }       //Creating getters and setters to change the text for the buttons and labels.      public JButton setProcessItemBtn(){          return processItem;      }     public JButton setConfirmItemBtn(){          return confirmItem;      }      public JButton setViewOrderbtn(){         return viewOrder;      }     public JButton setFinishOrderBtn(){          return finishOrder;      }     public JButton setNewOrderBtn(){          return newOrder;      }     public JButton setsetExitBtn(){          return exit;      }
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?
9571
I realize that it seems to be a duplicate of  but my question has a slight difference (from my point of view):  Once I know that   I will not use my class with "techniques that only works on properties" and  I will not use validation code in the getter/setter.   Is there any difference (except the style/future development ones), like some type of control in setting the property?  Is there any additional difference between:  public string MyString { get; set; }   and   public string myString;   (I am aware that, that the first version requires C# 3.0 or above and that the compiler does create the private fields.)
103112
When and why would somebody do the following:  doSomething( (MyClass) null );   Have you ever done this? Could you please share your experience?
83916
I'm building a mod for Terraria that will add classes and their corresponding abilities to the game. You're a warrior? Push your ability key and you'll use your berserk ability.   I'm trying to make my player code as simple as possible. I'd like to set the player's in-game "class" by doing something like this at the top of the player class so the rest of the methods in it can access it later:  //Set class WarriorClass playerClass == new WarriorClass(playerReference, level)   Herein lies the first issue. I get an error at playerReference that says:  Error   CS0236  A field initializer cannot reference the non-static field, method, or property 'ModPlayer.playerReference'  MyMod   Ok, so I looked that up and set the initialization in the WarriorClass instead:  public Player playerReference = new Player();   And I have this now in my player code:  //Set class      WarriorClass playerClass = new WarriorClass(level);   Here's the beauty of it. In the gamepad input method within my player code all I ever have to do is:      //On key presses     public override void ProcessTriggers(TriggersSet triggersSet)     {         if (MyMod.ability1Key.JustPressed)         {              playerClass.UseAbility(MyMod.ability1Key);         }   Now that the ability1 key was pressed, let the WarriorClass handle what to do:      public void UseAbility(ModHotKey key)     {             //Ability 1             if (key.JustPressed == MyMod.ability1Key)             {                 //Start berserking                 if (player.HasBuff(ModContent.BuffType&lt;BerserkBuff&gt;()) == false )                 {                     //Lose 10% of your life                     lifeLost = player.statLifeMax2 / 10;                     player.statLife = player.statLife - (int)lifeLost;                      //Berserk and add damage over in the Buff code                     player.AddBuff(ModContent.BuffType&lt;BerserkBuff&gt;(), 600, false);                 }   This is all great!!! I can add any amount of classes I want and this player code never changes. Except If I want to add if/then logic to select a class in say, Update() then it breaks the following reference in my gamepad input code:  playerClass.UseAbility(MyMod.ability1Key);   Of course it won't have a reference unless I hard code it at the top of the player file, but I don't know what class a player will be until they pick one.  Am I doing this fundamentally in a bad way or am I missing something else in terms of OO programming? I don't want to have to initialize every class for the character at the top of the file like this:  WarriorClass warriorClass = new WarriorClass(level); ArcherClass archerClass = new ArcherClass(level); ...   ... just to do this in the gamepad input method:  if (classChoice == "Warrior") {      warriorClass.UseAbility(MyMod.ability1Key); } else if (classChoice == "Archer") {      archerClass.UseAbility(MyMod.ability1Key); }
95172
I was hoping to set up an abstract component with some useful markup (custom spinner and notifier components in this instance) that could be extended by other components.  The structure would be:  AbstractComponent   AbstractMarkup   Body of Extending Component  However, when I call a method on the abstract component, it is unable to find any of it's own components. I think this is an error, because it makes the abstract component much less useful.  Here is code that will replicate the issue:  TestFindAbstract.cmp  &lt;aura:component abstract="true" extensible="true" &gt;     &lt;ui:outputText value="hey" aura:id="myText"/&gt;     {!v.body} &lt;/aura:component&gt;   TestFindAbstractHelper.js  ({     changeText : function(component) {         var text = component.find("myText");         text.set("v.value","New Text");     } })   Now, the extending class:  TestFind.cmp  &lt;aura:component extends="c:TestFindAbstract"&gt;     &lt;lightning:button label="Press Me" iconName="utility:download" iconPosition="left" onclick="{!c.changeText}" /&gt;  &lt;/aura:component&gt;   TestFindController.js     ({     changeText : function(component, event, helper) {     helper.changeText(component);     } })   I would have expected the extending class to call the method on the abstract class, find the component and change the value. Instead, I get the very diplomatic error message:     This page has an error. You might just need to refresh it.   Action failed: c$TestFind$controller$changeText [Cannot read property 'set' of undefined]   Failing descriptor: {c$TestFind$controller$changeText}   Any insights would be appreciated!
439
Consider:  namespace WindowsApplication1 {     public partial class Form1 : Form     {         public Form1()         {             InitializeComponent();         }          private void button1_Click(object sender, EventArgs e)         {             //int[] val = { 0, 0};             int val;             if (textBox1.Text == "")             {                 MessageBox.Show("Input any no");             }             else             {                 val = Convert.ToInt32(textBox1.Text);                 Thread ot1 = new Thread(new ParameterizedThreadStart(SumData));                 ot1.Start(val);             }         }          private static void ReadData(object state)         {             System.Windows.Forms.Application.Run();         }          void setTextboxText(int result)         {             if (this.InvokeRequired)             {                 this.Invoke(new IntDelegate(SetTextboxTextSafe), new object[] { result });             }             else             {                 SetTextboxTextSafe(result);             }         }          void SetTextboxTextSafe(int result)         {             label1.Text = result.ToString();         }          private static void SumData(object state)         {             int result;             //int[] icount = (int[])state;             int icount = (int)state;              for (int i = icount; i &gt; 0; i--)             {                 result += i;                 System.Threading.Thread.Sleep(1000);             }             setTextboxText(result);         }          delegate void IntDelegate(int result);          private void button2_Click(object sender, EventArgs e)         {             Application.Exit();         }     } }   Why is this error occurring?     An object reference is required for the nonstatic field, method, or property 'WindowsApplication1.Form1.setTextboxText(int)
929
I would like to be able to write a Java class in one package which can access non-public methods of a class in another package without having to make it a subclass of the other class. Is this possible?
106050
Hi I'm pretty new to Stack Overflow so I hope that I'm doing this correctly and that someone out there has the answer I need.  I'm currently coding a program in Java with Eclipse IDE an my question is this:  I need a snippet of code that does the following  It's supposed to get a .TXT file containing text and from that .TXT file  count the number of rows and print it,  count the number of words and print it,  count the number of characters and print it. And finally make a list of the top 10 words used and print that.  Allt the printing is done to system outprintln  I'm pretty new to Java and am having some difficulties.  Anyone out there who can provide me with these lines of code or that knows where i can find them? I want to study the code provided that's how I learn best=)  Thanks to all   Didnt find the edit button sorry...  I Added this to my question:  Hehe it´s an assignment but not a homework assignment ok i see well i could provide what i've done so far, i think im pretty close but it´s not working for me. Is there anything i have missed?  // Class    Tip   import java.io.*; import java.util.*;  class Tip {     public static void main(String [] args) throws Exception     {          String root = System.getProperty("user.dir");            InputStream is = new FileInputStream( root + "\\tip.txt" );         Scanner scan = new Scanner( is );          String tempString = "";         int lines = 0;         int words = 0;         Vector&lt;Integer&gt; wordLength = new Vector&lt;Integer&gt;();         int avarageWordLength = 0;          while(scan.hasNextLine() == true)         {                 tempString = scan.nextLine();                 lines++;         }          is.close();          is = new FileInputStream( root );         scan = new Scanner( is );          while(scan.hasNext() == true)         {                 tempString = scan.next();                 wordLength.add(tempString.length());                 words++;         }          for(Integer i : wordLength)         {                 avarageWordLength += i;         }         avarageWordLength /= wordLength.size();           System.out.println("Lines : " + lines);         System.out.println("Words : " + words);         System.out.println("Words Avarage Length : " + avarageWordLength);          is.close();          } }
10955
Is there any way to access controller variable set in a Method in Javascript. In the example above the value is set in constructor. But when I set it in a method it is showing as NULL in Javascript  In controller:  public class abc {     public string varA { get;set; }     public void fn(){         varA='hello';     } }   In VFPage:  function hello(){     var bool = '{!varA}';     alert(bool); }   The alert statement in the VF Page(i.e bool) is displayed as null. Can you please help how to access a variable set from a method instead of constructor?
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.
60178
In Java, is there any way to use the JDK libraries to discover the private classes implemented within another class? Or do I need so use something like asm?
1905
I ran into an interesting (and very frustrating) issue with the equals() method today which caused what I thought to be a well tested class to crash and cause a bug that took me a very long time to track down.   Just for completeness, I wasn't using an IDE or debugger - just good old fashioned text editor and System.out's. Time was very limited and it was a school project.  Anyhow -   I was developing a basic shopping cart which could contain an ArrayList of Book objects. In order to implement the addBook(), removeBook(), and hasBook() methods of the Cart, I wanted to check if the Book already existed in the Cart. So off I go -  public boolean equals(Book b) {     ... // More code here - null checks     if (b.getID() == this.getID()) return true;     else return false; }   All works fine in testing. I create 6 objects and fill them with data. Do many adds, removes, has() operations on the Cart and everything works fine. I read that you can either have equals(TYPE var) or equals(Object o) { (CAST) var } but assumed that since it was working, it didn't matter too much.  Then I ran into a problem - I needed to create a Book object with only the ID in it from within the Book class. No other data would be entered into it. Basically the following:  public boolean hasBook(int i) {     Book b = new Book(i);     return hasBook(b); }  public boolean hasBook(Book b) {     // .. more code here     return this.books.contains(b); }   All of a sudden, the equals(Book b) method no longer works. This took a VERY long time to track down without a good debugger and assuming the Cart class was properly tested and correct. After swaapping the equals() method to the following:  public boolean equals(Object o) {     Book b = (Book) o;     ... // The rest goes here    }   Everything began to work again. Is there a reason the method decided not to take the Book parameter even though it clearly  was  a Book object? The only difference seemed to be it was instantiated from within the same class, and only filled with one data member. I'm very very confused. Please, shed some light?
100082
When you press a button or change a setting, this is an operation which you can also do in Python, how do you find the Python equivalent to accessing these user interface elements.   Settings (text, numbers, colors... etc) Buttons (tools you access via key bindings, menu items etc) Menus (accessed via headers, other menus or key-bindings)
29419
There are a group of private methods in my class, and I need to call one dynamically based on an input value. Both the invoking code and the target methods are in the same instance. The code looks like this:  MethodInfo dynMethod = this.GetType().GetMethod("Draw_" + itemType); dynMethod.Invoke(this, new object[] { methodParams });   In this case, GetMethod() will not return private methods. What BindingFlags do I need to supply to GetMethod() so that it can locate private methods?
18943
I'm using the Apache Commons EqualsBuilder to build the equals method for a non-static Java inner class. For example:  import org.apache.commons.lang.builder.EqualsBuilder;  public class Foo {     public class Bar {         private Bar() {}          public Foo getMyFoo() {             return Foo.this         }          private int myInt = 0;          public boolean equals(Object o) {             if (o == null || o.getClass() != getClass) return false;              Bar other = (Bar) o;             return new EqualsBuilder()                 .append(getMyFoo(), other.getMyFoo())                 .append(myInt, other.myInt)                 .isEquals();         }     }      public Bar createBar(...) {         //sensible implementation     }      public Bar createOtherBar(...) {         //another implementation     }      public boolean equals(Object o) {         //sensible equals implementation     } }   Is there syntax by which I can refer to other's Foo reference apart from declaring the getMyFoo() method? Something like other.Foo.this (which doesn't work)?
92972
I want to put individual JComboBoxes into each cells of a JTable. ie. The JComboBox content is not identical for each cell.   I basically would like to be able to just call the following code to add a row of JComboBox into the JTable. Anyone has any idea? Thanks  JComboBox cb1 = new JComboBox(...); JComboBox cb2 = new JComboBox(...); model.addRow(new Object[] {"Row name", cb1, cb2} );  JComboBox cb3 = new JComboBox(...); JComboBox cb4 = new JComboBox(...); model.addRow(new Object[] {"Row name 2", cb3, cb4} );   The closest example code I can find is as follows. But it is for where JComboBox content is identical for the individual column. Not the solution I need.  TableColumn col = table.getColumnModel().getColumn(vColIndex); col.setCellEditor(new MyComboBoxEditor(values));   where  public class MyComboBoxEditor extends DefaultCellEditor {     public MyComboBoxEditor(String[] items) {         super(new JComboBox(items));     } }
103233
How do I implement a draggable tab using Java Swing? Instead of the static JTabbedPane I would like to drag-and-drop a tab to different position to rearrange the tabs.  EDIT: .