I try to read all lines in the text area into StringBuilder so that I can use the text in text area as a whole string. However I get the NullPointerException in line s.append(line);. Why?
public class tu extends JFrame implements ActionListener{
JTextArea t;
static StringBuilder s;
tu (){
setLayout(/*new BorderLayout()*/null);
t=new JTextArea(30,77);
JScrollPane s=new JScrollPane(t,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
JButton b=new JButton("process");
b.addActionListener(this);
JPanel p=new JPanel();
JPanel p1=new JPanel();
p.add(s);
p.setBorder(new TitledBorder("sequence"));
p.setBounds(0,0,880,540);
p1.add(b);
p1.setBounds(380,570,100,40);
add(p);
add(p1);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(900,700);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
String text=t.getText();
while (text!=null){for (String line : text.split("\\n")){
s.append(line);
}}
}
public static void main(String[] args){
tu t=new tu();
}
}
Attempting to invoke any method on an object that has not been instantiated will result in an NPE. You need to instantiate your StringBuilder s:
StringBuilder s = new StringBuilder();
Do you really want to wait until the user has clicked the JButton before building up the contents of this StringBuilder? StringBuilders are typically used as on-demand helper objects with local scope.
A number of things to note:
Use of static member variables is considered poor design
Class names start with uppercase letters
Don't use absolute positioning(null layout). Use a layout manager instead
The preferred approach is to create an instance of JFrame directly & use.
The preferred approach for ActionListeners is to use either an anonymous instance or the Action interface.
Consider using initial threads
your StringBuilder is still null, when you want to write to it.
you need to instantiate your StringBuilder before appending.
s = new StringBuilder();
btw your StringBuilder s and your JScrollPane s have the same variable name, you should use different names.
Related
I am very new and I have no idea how to set the color in this same line of code, I need it to be this line because it is covered by a loop while or if there are other ways, I would appreciate it if you told me, thanks.
add(new JButton(new PersonAction(new Person(miResultSet.getString("name"), miResultSet.getString("identification"))),setBackground(Color.yellow)));
If you want to do it in an uncluttered way, use more lines than one and create every object needed in a single statement:
while (someConditionIsTrue) {
// create a Person passing some parameters
Person p = new Person(miResultSet.getString("name"),
miResultSet.getString("identification"));
// create a PersonAction with the recently created person as parameter
PersonAction pa = new PersonAction(p);
// create the JButton passing the PersonAction as parameter
JButton jb = new JButton(pa);
// set the background of the JButton
jb.setBackground(Color.YELLOW)));
// add it to wherever it is to be added
someThing.add(jb);
}
This will make it much easier to read and debug…
Try this
add(new JButton(new PersonAction(new Person(miResultSet.getString("name"), miResultSet.getString("identification")))).setBackground(Color.yellow));
You have not constructed jbutton properly, more over you have used comma to access property instead of dot operator.
Or you can try this...
while (miResultSet.next()) {
Person person = new Person(miResultSet.getString("name"), miResultSet.getString("identification"));
PersonAction action = new PersonAction(person);
JButton actionButton = new JButton(action);
actionButton.setBackground(Color.yellow);
// set other properties if you need
add(actionButton);
}
P.S. I guess condition in while loop. Really - I don't know exacly.
this my code .....
public class A {
JLabel A = new JLabel() ;
public JLabel newform(){
A.setBounds(0 , 197, 409, 245);
A.setIcon(createImageIcon("/Pictures/BG.png"));
return A; }
public void swinginDown_NF ( ){
AnimationClass AC = new AnimationClass();
AC.jLabelYDown(A.getY(), 270, 6, 1,A);
}
class B ....
public class B {
JLabel B = new JLabel() ;
public JLabel Box(){
B.setBounds(170 , 197, 409, 245);
B.setIcon(createImageIcon("/Pictures/BBD.png"));
B.addMouseListener(new java.awt.event.MouseAdapter() {
public final void mouseClicked(java.awt.event.MouseEvent evt) {
A a_class = new A();
a_class.swinginDown_NF();
} });
return B; }
Main...
JFrame frame = new JFrame(" AA ");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setUndecorated(true);
JLabel Label = new JLabel() ;
A a = new A();
B b = new B() ;
Label.add(B.Box());
Label.add(A.newform());
frame.getContentPane().add( Label , BorderLayout.CENTER);
My problem when I click in label Box nothing happen in label newform ...
when I click in label Box function swingDown_NF its open but the label doesnt go down ...... Why ???
You're creating a new A object within the swinging down method, one that is completely separate and unique from the displayed object, and so changing the state of the new object will have no effect on the displayed one. You'll have to pass in a reference of the displayed one to where it's needed. For example you could have the B class accept an A parameter in its constructor.
Some side recommendations:
Please learn and follow Java naming and formatting conventions as your code is very difficult to follow.
You have class and field with the same names, A and B. Again, this will only confuse us and the future you -- never do this.
Avoid null layouts and setBounds if at all possible as it leads to very rigid and hard to debug GUI's. Instead use layout managers.
Your posted code won't compile. It looks like you've tried to simplify your real code for this post which is fine, but in the process you've posted bad non-compilable code including calling an instance method as if it were static. Yes, do simplify your code, but please don't post bad code in the process since you want us to understand your code and your problem well.
Im having some issues getting the copy and paste methods from JTextComponent working
for my program i have an array of strings that will be the menu choices. "Copy" and "Paste" are two of these.
else if (e.getActionCommand().equalsIgnoreCase("Copy"))
{
JTextArea a = new JTextArea();
a.setEditable(true);
a.copy();
}
else if (e.getActionCommand().equalsIgnoreCase("Paste"))
{
JTextArea a = new JTextArea();
a.setEditable(true);
a.getSelectedText();
a.paste();
}
im getting no error messages but its not working. any help would be appreciated
You're creating a new instance of JTextArea each time your want to perform an action.
These won't represent what is actually on the screen. Instead, interact with a instance variable or pass the instance of the JTextArea that is on the screen in as a parameter
You are declaring a local object whose scope is limited only in an if condition:
else if (e.getActionCommand().equalsIgnoreCase("Copy"))
{
JTextArea a = new JTextArea(); // CREATING A NEW OBJECT
a.setEditable(true);
a.copy();
} // AS Soon as the code comes HERE THE Instance IS LOST with the data
Declare;
JTextArea a = new JTextArea(); outside the if condition, maybe in the class before main(){}
Create an private instance variable of the same.
Hope this helps. Let me know, if you have any questions.
class TEST{
public JTextArea a = new JTextArea();
TEST objectOfTEST = new TEST():
publis static String someText = "";
public static void main(String[] args){
if(e.getActionCommand().equalsIgnoreCase("Copy")){
someText = objectOfTEST.a.getText();
}
else if(e.getActionCommand().equalsIgnoreCase("Paste")){
// PERFORM SOME OPERATION
someText = "Paste this";
objectOfTEST.a.setText("Some TEXT that you want to set here");
}
}
}
Im trying to get a value from a text field (entered by the users) to use for processing. But no matter what I do it will not get the value that was entered it seem to remain empty. Could some one please tell me why it will not get the value from the Text field.
this is the method which initialy created the text field which was named writeStrings
public void chooseEmpToAdd()
{
JTextArea EmpDetails = new JTextArea(5,20);
JTextField writeStrings = new JTextField(20);
JLabel enterIDno = new JLabel("Please enter The Employye ID number that you wish to assign to a department: ");
JButton submit = new JButton (" Submit") ;
ButtonListenerEmp Listener2 = new ButtonListenerEmp();
submit.addActionListener(Listener2);
JFrame frameAllEmps = new JFrame();
frameAllEmps.setSize( 150, 140 );
frameAllEmps.pack();
frameAllEmps.setVisible(true);
//layout
frameAllEmps.setLayout(new FlowLayout());
frameAllEmps.add(enterIDno);
int x = 0;
System.out.println("ALL Emps from the tree map");
for(int key:employeeMap.keySet())
{
Employee dEmp = employeeMap.get(key);
System.out.println("Employe no :" +x+": "+dEmp);
EmpDetails.setText(EmpDetails.getText()+" "+dEmp);
frameAllEmps.add(EmpDetails);
x++;
}
frameAllEmps.add(new JScrollPane(EmpDetails));
frameAllEmps.add(writeStrings);
frameAllEmps.add(submit);
frameAllEmps.pack();
}
And this is the action listener which should take the value from the Text box and print it to the console, but it does not work.
private class ButtonListenerEmp implements ActionListener
{
public void actionPerformed (ActionEvent e )
{
String ID ;
int dID;
ID = writeStrings.getText();
System.out.println("start of try b4 changes: "+ID);
}
}
The listener implementation shouldn't have access to the local variable writeStrings, I'm not even sure how that would compile--is the code you posted accurate?
Oh, you probably have both a local variable writeStrings, and an instance variable writeStrings, although it's hard to say since you didn't post the rest of the code. Try not declaring writeStrings in the chooseEmpToAdd method; use the class variable instead.
Because you're declaring the text field as a local variable of chooseEmpToAdd method, so it is not being seen by ButtonListenerEmp class. To solve this problem, declare the text field as a class field and make it public or pass the text of the text field as an argument of ButtonListenerEmp constructor.
The variable ID might not have been initialized (i.e. String ID = "";)
Also there is a compile error at the line writeStrings.getText() because the variable writeStrings doesn't exist outside of the chooseEmpToAdd() method. Try declaring JTextField writeStrings = new JTextField(20); before the method instead.
One thing that comes to my mind from the code presented is that you create the new JTextField and store it in a local variable called writeStrings maybe that is not the same you try to read from lateron.
Hello
I'm making a program that tracks the number of users that are logged on by entering names through textfield0. I hit a road block being new to java I still don't understand some things I was wondering how one would add names to the array User in real time and have the array be count it show it in textfield1.
Thank you in advance.
public class UserTracking {
public static void main(String[] args){
final Kong f = new Kong();
f.pack();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(200,110);
f.setVisible(true);
}
}
class Kong extends JFrame implements ActionListener
{
JTextField textfield0 = new JTextField();
JTextField textfield1 = new JTextField();
JLabel label0 = new JLabel("User");
JLabel label1 = new JLabel("Number of Users:");
JButton btnon = new JButton("Log on");
JButton btnoff = new JButton("Log off");
String User[] ={};
public Kong()
{
super("Shazam");
JPanel panel1 = new JPanel(new BorderLayout());
panel1.add(textfield0,BorderLayout.CENTER);
panel1.add(label0,BorderLayout.WEST);
JPanel panel2 = new JPanel(new BorderLayout(10,10));
panel2.add(btnon,BorderLayout.WEST);
panel2.add(btnoff,BorderLayout.EAST);
JPanel panel3 = new JPanel(new BorderLayout());
panel3.add(textfield1,BorderLayout.CENTER);
panel3.add(label1,BorderLayout.WEST);
JPanel frame = new JPanel(new BorderLayout(5,5));
frame.add(panel1,BorderLayout.NORTH);
frame.add(panel2,BorderLayout.EAST);
frame.add(panel3,BorderLayout.SOUTH);
setContentPane(frame);
}
public void actionPerformed(ActionEvent e)
{
}
}
If you've had experience with C++, think of Java arrays as C++ arrays in that once their size is defined, it stays that way. If you wish to increase the capacity, you need to recreate the array and add the contents of the old array inside. Essentially this is what vector did.
In Java if you want an expandable array, you essentially want a List object. I would strongly encourage you to use an ArrayList which is essentially the equivalent of vector in Java, allowing you to add as many objects as you want without worrying about its capacity.
If you ever need an array, you can convert it using the toArray() method (though in my experience, ArrayList does everything you'd require).
The size of an array in java can't be changed after the first initialization.
If you want a dynamic sized data container, you can use any implementation of the List interface. For example ArrayList :
ArrayList<String> user = new ArrayList<String>();
And to add each user to the ArrayList :
user.add(username);
Use an ArrayList.
What you need is not an array, but a more flexible datatype (that is able to "grow" in size) like some List implementation: ArrayList is actually backed by an array, but you don't need to manage (re)allocation yourself.
Instead of taking String array you can take ArrayList it would be easier. Something like this
ArrayList<String> user = new ArrayList<String>();
On some action like button or text change event write this
user.add(textField1.getText());
The actionPerformed method should
add a string into the User array (which should be named users)
ask the array its new length
change the value in the count textfield (textfield1, which really has a bad name)
The problem is that Java arrays have a fixed length. They can't grow. That'w why java.util.ArrayList exists : it's a class that behaves like a dynamic-length array. Read its javadoc to know how to use it.
You are also missing linking buttons to ActionListener. Once that is done, you could use ArrayList to add users to the list as they login and remove users from list as they logoff.
private ArrayList<String> loggedOnUsers = new ArrayList<String>();
and
void actionPerformed(event)
{
if(it's logOn button action)
{
add user to loggedOnUsers list
}
else
{
remove user from loggedOnUsers list
}
}