Accessing Java Swing Components Through Another Class? [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
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;
}

Firstly, this is actually a getter, since it return's a value.
public JButton setProcessItemBtn(){
return processItem;
}
This would be a setter
public void setProcessItemBtn(JButton btn){
processItem = btn;
}
But, you don't seem to have one of those.
If you did have that method, then you could do something like this
public static void main(String[] args) {
UserInterface gui = new UserInterface();
gui.setProcessItemBtn(new JButton("Some Text"));
gui.startUI();
}
Now, that isn't perfect, nor is it guaranteed to show a button at all, but the idea of "setting" a value is what is important.
Alternatively, you may want to not use a static method or making a new JFrame when you class already extends one... Try something like this
public class UserInterface extends JFrame {
// Button variables
public UserInterface(){
bookingUI();
}
public void bookingUI(){
//sets windows, and pane in the UI
setTitle("Ye old Book stoppe");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel toppane = new JPanel(new GridBagLayout());
JPanel bottomPane = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
setSize(800, 300);
setVisible(true);
//setting up buttons to be placed onto the bottompanel
processItem = new JButton("Process Item");
confirmItem = new JButton("Confirm Item");
viewOrder = new JButton("View Order");
finishOrder = new JButton("Finish Order ");
newOrder = new JButton("New Order");
exit = new JButton("Exit");
// etc...
}
Then you can try UserInterface gui = new UserInterface(); and get the buttons, and set the text on them

There are multiple errors in your code:
The NPE occurs due to this:
You have 2 variables called processItem, one global variable:
private JButton processItem;
and one local variable:
JButton processItem = new JButton("Process Item");
the second processItem variable only exists within the bookingUI() method and the one you're returning on your getter is the global one, which is not initialized!
If you want to initialize the global variable processItem remove this word JButton from here:
JButton processItem = new JButton("Process Item");
That's why you're returning a not initialized variable
You're creating a JFrame object and extending JFrame for no reason, remove the extends JFrame part on your class.
Why are your setter methods returning a value? As a convention they should be void (and set a value) and the getters should be the ones returning something.
You're not indenting your code correctly
You're making your JFrame visible before you have painted everything in it, it will cause you troubles later
You're not placing your program inside the EDT

Related

program not exiting upon GUI creation

For testing purposes I have created a GUI in my ClientGUI class. The program never seems to exit and hangs.I call my create function in main to see how the gui looks and after this the program should terminate but instead it hangs.Please explain to me why this is happening.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.io.*;
import java.net.*;
public class ClientGUI extends JFrame{
// creates username textfield
private JLabel username = new JLabel("Username ");
private JTextField textUsername = new JTextField(10);
//creates password textfield
private JLabel password = new JLabel("Password ");
private JPasswordField passText = new JPasswordField(10);
// adding two buttons
private JButton Login = new JButton("Login");
private JButton Create = new JButton("Create");
private JPanel error;
private JFrame my_error;
private JLabel errormsg = new JLabel("Error Try Again");
private JButton cancel_me = new JButton("OK");
private String option;
private String usr_name;
private char [] ident;
private String pass;
private String passme;
public volatile boolean []go = new boolean[1];
// constructor
ClientGUI(){
super("GossApp"); //title of jframe
}
public void CreatGui(){
JPanel myPanel = new JPanel(new GridBagLayout()); // creates a panel of type gridbaglayout
GridBagConstraints GridC = new GridBagConstraints();// constraints for layout
GridC.insets = new Insets(0,10,0,10); // spacing
// position 0,0 is corner
GridC.gridx = 0;
GridC.gridy = 0;
myPanel.add(username, GridC); // adding to panel
// position 0,1 adding user text field below username
GridC.gridy = 1;
myPanel.add(textUsername, GridC);
// position 0, 2 adding password name below user
GridC.gridx = 0;
GridC.gridy = 2;
myPanel.add(password, GridC);
//position 0,3 adding password text field below password
GridC.gridy = 3;
myPanel.add(passText, GridC);
// adding login button to panel next to password text
GridC.gridx = 1;
GridC.gridy = 3;
myPanel.add(Login, GridC);
Login.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
/*
String my_name = textUsername.getText();
char [] my_password = passText.getPassword();
String my_stringword = new String(my_password);
*/
option ="log";
whileLog(option);
}
});
// adding create button gui next to user text field
GridC.gridx = 1;
GridC.gridy = 1;
myPanel.add(Create,GridC);
Create.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
option= "create";
whileLog(option);
}
});
add(myPanel); //adds gui to jframe
setSize(270,170); // creates dimensions of frame
setLocationRelativeTo(null); // center gui
setVisible(true); // I can see!
my_error = new JFrame("Error");
error = new JPanel(new GridBagLayout());
GridC.gridx= 1;
GridC.gridy = 1;
error.add(cancel_me,GridC);
cancel_me.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
my_error.setVisible(false);
}
});
GridC.gridy = 2;
error.add(errormsg,GridC);
my_error.add(error);
my_error.pack();
my_error.setLocationRelativeTo(null);
my_error.setVisible(false);
}
public class clientserver{
public static void main(String[]args) {
ClientGUI my_gui = new ClientGUI();
my_gui.CreatGui();
}
}
you need to set
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
For your ClientGui, otherwise the default kicks in, which makes it not really close. The default keeps the JVM running as the JFrame hasn´t been destroyed properly.
an additional small paragraph from the methods documentation, which shows what the default is.
[...]
HIDE_ON_CLOSE (defined in WindowConstants): Automatically hide the frame after invoking any registered WindowListener objects.
[...]
EXIT_ON_CLOSE (defined in JFrame): Exit the application using the System exit method. Use this only in applications.
[...]
The value is set to HIDE_ON_CLOSE by default. Changes to the value of this property cause the firing of a property change event, with property name "defaultCloseOperation".
[...]

Swing Number Format Exception

For some reason the AddListener class below doesn't work, and I keep getting a number format exception. Could anyone please tell me the reason for this. It seems to me as if it should work.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class BabyCalculator extends JFrame {
JFrame theFrame = this;
JTextField addField; // Declaring this here so that you can access the variable from other places. MAKE SURE TO NOT DECLARE THIS AGAIN IN THE CONSTRUCTOR
JTextField totalField;
public BabyCalculator() {
//You set this up so that you can refer to the frame using the inner class below.
setDefaultCloseOperation(EXIT_ON_CLOSE);
setName("Baby Calculator");
setLayout(new GridLayout(3, 0));
//add
JLabel addLabel = new JLabel("Amount to add:");
addField = new JTextField(10);
JButton addButton = new JButton("add");
addButton.addActionListener(new AddListener());
//multiply
JLabel multiplyLabel = new JLabel("Amount to multiply:");
JTextField multiplyField = new JTextField(10);
JButton multiplyButton = new JButton("multiply");
//total
JLabel totalLabel = new JLabel("Total");
totalField = new JTextField(10);
totalField.setEditable(false);
JButton stopButton = new JButton("Stop");
stopButton.addActionListener(new StopListener());
//Create Panels
JPanel topRow = new JPanel(new BorderLayout());
JPanel middleRow = new JPanel(new BorderLayout());
JPanel bottomRow = new JPanel(new FlowLayout());
//Add the top Row
topRow.add(addLabel, BorderLayout.WEST);
topRow.add(addField, BorderLayout.CENTER);
topRow.add(addButton, BorderLayout.EAST);
add(topRow);
middleRow.add(multiplyLabel, BorderLayout.WEST);
middleRow.add(multiplyField, BorderLayout.CENTER);
middleRow.add(multiplyButton, BorderLayout.EAST);
add(middleRow);
bottomRow.add(totalLabel);
bottomRow.add(totalField);
bottomRow.add(stopButton);
add(bottomRow);
pack();
setVisible(true);
}
public class AddListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String addFieldText = addField.getText();
String totalFieldText = totalField.getText();
double addAmount = Double.parseDouble(addFieldText);
double total = Double.parseDouble(totalFieldText);
total += addAmount;
totalField.setText(total + "");
}
}
//end class AddListener
public class StopListener implements ActionListener {//this is an inner class
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(theFrame, "You Clicked the stop button");
}//end class StopListener
}
public static void main(String[] args) {
JFrame newFrame = new BabyCalculator();
}
}
Note: The problem in the code is definitely related to the AddListener. Whenever I click the add button in the GUI I get an exception.
The problem is with the totalFieldText, it's default value is blank, meaning that when you try and convert to a double value, it causes a NumberFormatException
Try giving it a default value of 0, for example
totalField = new JTextField("0", 10);
You might also like to take a look at How to Use Spinners and How to Use Formatted Text Fields which will make your life easier

Trying to find error in Java Swing program

So this is my program... It's a way to enter and list marathon runners. Now I'm getting an error when using the "Ny" button (http://gyazo.com/e29517af6befd6242d86e6fe1dc5aae1). Here's the error code: http://gyazo.com/9f80885d41db38cfa5502fe911f6a893.
I think the problems is between the "Form" panel and the listener. There may be unreachable code somewhere? I had this working the other day but I lost the code. Now it doesn't work.
The idea is that the "ny" button shows the user a panel "Form", but instead I get the rror.
I'm a huge noob, so I expect it's some obvious syntax error I just can't seem to spot.
Any feedback is appreciated.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class Maraton extends JFrame{
JTextArea display;
JButton visa;
ArrayList <Tävlande> list = new ArrayList <Tävlande>();
Maraton(){
super("Kista Maraton");
display = new JTextArea();
display.setEditable(false);
add(display, BorderLayout.CENTER);
add(new JScrollPane(display),BorderLayout.CENTER);
setLocationRelativeTo(null);
setSize(300, 400);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel nedre = new JPanel ();
JPanel höger = new JPanel();
add(nedre, BorderLayout.SOUTH);
add(höger, BorderLayout.EAST);
höger.setLayout(new BoxLayout(höger, BoxLayout.Y_AXIS));
nedre.setBackground( new Color(246,246,246) );
nedre.setBorder(BorderFactory.createLineBorder(new Color(200,200,200)));
JButton ny = new JButton("Ny");
ny.addActionListener(new NyLis());
JButton visa = new JButton("Visa");
visa.addActionListener(new VisaLis());
visa.setEnabled(false);
JButton nyTid = new JButton("Ny Tid");
nedre.add(ny);
nedre.add(visa);
nedre.add(nyTid);
JRadioButton StartNrRb = new JRadioButton("Startnr");
JRadioButton NamnRb = new JRadioButton("Namn");
JRadioButton ÅlderRb = new JRadioButton("Ålder");
JRadioButton TidRb = new JRadioButton("Tid");
höger.add(StartNrRb);
höger.add(NamnRb);
höger.add(ÅlderRb);
höger.add(TidRb);
ButtonGroup bg1 = new ButtonGroup();
bg1.add(NamnRb);
bg1.add(StartNrRb);
bg1.add(ÅlderRb);
bg1.add(TidRb);
}
class Form2 extends JPanel{
JTextField startNrFält;
JTextField tidFält;
Form2(){
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
JPanel rad0 = new JPanel();
rad0.add(new JLabel("Start Nummer: "));
rad0.add(new JLabel("Tid: "));
rad0.setLayout(new BoxLayout(rad0, BoxLayout.Y_AXIS));
rad0.add(startNrFält);
rad0.add(tidFält);
add(rad0);
}
}
class Form extends JPanel{
JTextField namnFält;
JTextField landFält;
JTextField ålderFält;
Form(){
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
JPanel rad1 = new JPanel();
rad1.add(new JLabel("Namn: "));
namnFält = new JTextField(15);
rad1.add(namnFält);
add(rad1);
JPanel rad2 = new JPanel();
rad2.add(new JLabel("Land: "));
landFält = new JTextField(15);
rad2.add(landFält);
add(rad2);
JPanel rad3 = new JPanel();
rad3.add(ålderFält);
rad3.add(new JLabel("Ålder: "));
ålderFält = new JTextField(5);
rad3.add(ålderFält);
add(rad3);
}
}
class NyLis implements ActionListener{
public void actionPerformed(ActionEvent ave){
Form f = new Form();
int svar = JOptionPane.showConfirmDialog(null, f);
String namn = f.namnFält.getText();
String land = f.landFält.getText();
int ålder = Integer.parseInt(f.ålderFält.getText());
Tävlande tv = new Tävlande (namn,land,ålder);
list.add(tv);
visa.setEnabled(true);
}
}
class VisaLis implements ActionListener{
public void actionPerformed(ActionEvent ave) {
display.setText("");
for (Tävlande t : list){
display.append(t.toString()+"\n");
}
}
}
class NyTidLis implements ActionListener{
public void actionPerformed(ActionEvent ave) {
Form f2 = new Form();
JOptionPane.showMessageDialog(null, f2);
}
}
public static void main (String []args){
new Maraton();
}
}
The problem is you're trying to add a null object to your JPanel when you click the ny button. The offending code is found in the constructor for your Form object:
rad3.add(ålderFält);
ålderFält = new JTextField(5); //NO! Create the JTextFieldObject first
rad3.add(ålderFält);
Alter the code to the following:
ålderFält = new JTextField(5);
rad3.add(ålderFält);
rad3.add(ålderFält);
And you should have no problems (or at least the code runs for me).
You also have a problem with your visa button. You're declaring an entirely new JButton in your constructor, which will lead to more NullPointerExceptions when you try to enable it.
In the future, read your stack trace a little more closely. Sometimes you have to dig through a few lines of it to find out where, exactly, in your code you're going wrong. This is especially true when you're doing graphical stuff.
You are redefining the JButton visa in the constructor of your class on this line:
JButton visa = new JButton("Visa");
This is distinct from the visa variable defined class level (here this.visa, and visa represent two seperate JButtons), which you attempt to access (uninitialized) in your NyLis actionListener.
Change the aforementioned line to:
visa = new JButton("Visa");

gui help... with an actionListener

I'm writing my first GUI program that actually does something and I am having problems with the action listener. The program when complete will take a double input and make conversions from one unit to another based on some radio button selections which i haven't added yet. The problem right now is the Action listener doesn't recognize my text fields.
I have an input text field and an output text fields in separate panels. I created an action listener and I added the input text field to the listener.
ActionListener handler = new HandlerClass();
textField.addActionListener(handler);
then I created an in class definition for the handler class but when I write the action preformed method textField and output cannot be resolved by the program. Can anyone see what I'm doing wrong?
public class conversionDisplay extends JFrame{
/**
*
*/
private static final long serialVersionUID = 1L;
private JPanel northPanel;
private JPanel southPanel;
private JPanel eastPanel;
private JPanel westPanel;
public conversionDisplay() {
super("Temperature Conversion");
northPanel = new JPanel(); //create northPanel
northPanel.setLayout(new GridLayout(1,2,5,5));
northPanel.add(new JPanel());
JPanel northLabelPanel = new JPanel(new BorderLayout()) ;
northLabelPanel.add(new JLabel("Input"), BorderLayout.EAST);
northPanel.add(northLabelPanel);
JTextField textField =new JTextField(10);
northPanel.add(textField);
northPanel.add(new JPanel());
southPanel = new JPanel(); //create southPanel
southPanel.setLayout(new GridLayout(1,2));
southPanel.add(new JPanel());
JPanel southLabelPanel = new JPanel(new BorderLayout());
southLabelPanel.add(new JLabel("Output "), BorderLayout.EAST);
southPanel.add(southLabelPanel);
JTextField output;
southPanel.add(output = new JTextField( 10));
output.setEditable(false);
southPanel.add(new JPanel());
add(northPanel,BorderLayout.NORTH); //add north panel
add(southPanel,BorderLayout.SOUTH); //add north panel
ActionListener handler = new HandlerClass();
textField.addActionListener(handler);
setSize(350, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
private class HandlerClass implements ActionListener{
public void actionPerformed(ActionEvent e) {
double input = textField.getText();
if (input != 0)
{
output.setText(input); //Perform conversion
}
}
}
}
Your textField JTextField is declared inside of a constructor and is thus only visible within that block (again the constructor). You need to make it an instance field of the class.
i.e.,
public class Foo {
private Bar bar = new Bar(); // this field is visible throughout the object
public Foo() {
Baz baz = new Baz(); // this is only visible within this constructor
}
So just like the bar variable above is visible while the baz variable that is declared in the constructor is not, you'll want to move your JTextField variable declarations out of the constructor.
you must parse String to Double value
public void actionPerformed(ActionEvent e) {
double input = Double.parseDouble(textField.getText());
if (input != 0)
{
output.setText(input+""); //Perform conversion
}
}
and declare JTextField output,textField as Globel.
public class conversionDisplay extends JFrame{
/**
*
*/
private static final long serialVersionUID = 1L;
private JPanel northPanel;
private JPanel southPanel;
private JPanel eastPanel;
private JPanel westPanel;
JTextField output = new JTextField(10);
public conversionDisplay() {
super("Temperature Conversion");

Using ArrayList in a JPanel

Class SampleFiveA extends JPanel. This contains textfields, one below the other, each of which has a label on the left. All textfields will be of the same width and positioned against the right border of the panel. SampleFiveA has only one constructor that accepts the following three parameters:
ArrayList names,
ArrayList values,
int cols
I so far created the sample username password screen in GUI but now I have a problem implementing an ArrayList in JPanel one for User Name and the other for password. Kind of stuck there for hours now cant find a proper example to do it. Below is the code I commented what I need to be done using ArrayList.
public class SampleFiveA extends JPanel {
ArrayList<String> names = new ArrayList<String>(); //the text for the labels
ArrayList<String> values = new ArrayList<String>(); // the initial contents of the text fields
int col ; //the number of columns used to set the width of each textfield
public SampleFiveA()
{
JPanel p = new JPanel();
p.setLayout(new GridLayout(2,2));
JLabel lab1 = new JLabel("User Name", JLabel.LEFT);
p.add(lab1 = new JLabel("User Name"));
JTextField txt1 = new JTextField("User Name", JTextField.RIGHT);
p.add(txt1= new JTextField());
JLabel lab2 = new JLabel("Password ", JLabel.LEFT);
p.add(lab2 = new JLabel("Password"));
JPasswordField txt2 = new JPasswordField("*****",JPasswordField.RIGHT );
p.add(txt2 = new JPasswordField());
// names.add(lab1,lab2);// Not right but I want to put the label text to this arrayList
// values.add(txt1,txt2);//
add(p);
};
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.getContentPane().add(new SampleFiveA());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200,200);
frame.setVisible(true);
};
};
you can use
names.add(txt1.getText());
values.add(txt2.getText());
but maybe you should think about a better data structure, e.g. a HashMap and
hashmap.put(txt1.getText(),txt2.getText())
(and you should do this based on some event,e.g. user presses a button, not in the constructor, as otherwise the value will be the one you set before)
Here's a start for you.
It adds a FocusListener to the text fields and makes sure that the content of the ArrayList is updated with the current value when the text field looses focus.
import java.awt.GridLayout;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.*;
public class Main extends JPanel {
ArrayList<String> names = new ArrayList<String>(); // the text for the
// labels
ArrayList<String> values = new ArrayList<String>(); // the initial contents
// of the text fields
int col; // the number of columns used to set the width of each textfield
public Main() {
JPanel p = new JPanel();
p.setLayout(new GridLayout(2, 2));
names = new ArrayList<String>();
values = new ArrayList<String>();
JLabel lab1 = new JLabel("User Name", JLabel.LEFT);
p.add(lab1);
JTextField txt1 = new JTextField("User Name", JTextField.RIGHT);
p.add(txt1);
names.add(lab1.getText());
values.add(txt1.getText());
JLabel lab2 = new JLabel("Password ", JLabel.LEFT);
p.add(lab2);
JPasswordField txt2 = new JPasswordField("*****", JPasswordField.RIGHT);
p.add(txt2);
names.add(lab2.getText());
values.add(txt2.getText());
// names.add(lab1,lab2);// Not right but I want to put the label text to
// this arrayList
// values.add(txt1,txt2);//
txt1.addFocusListener(new ArrayListFocusListener(txt1, values, 0));
txt2.addFocusListener(new ArrayListFocusListener(txt2, values, 1));
add(p);
// Start a thread to print the content of the list for 10 seconds
new Thread() {
public void run() {
for (int i = 0; i < 10; i++) {
try {
sleep(1000);
} catch (InterruptedException e) {
}
System.out.println(values);
}
}
}.start();
};
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.getContentPane().add(new Main());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 200);
frame.setVisible(true);
};
class ArrayListFocusListener implements FocusListener {
JTextField textField;
ArrayList<String> backingList;
int myIndex;
public ArrayListFocusListener(JTextField textField,
ArrayList<String> backingList, int myIndex) {
this.textField = textField;
this.backingList = backingList;
this.myIndex = myIndex;
}
public void focusGained(FocusEvent e) {
}
#Override
public void focusLost(FocusEvent e) {
backingList.set(myIndex, textField.getText());
}
}
};
I'm sure what you are trying to do. You either want to put the JLabel in an ArrayList or the text of that label.
If you want to put the whole JLabel in an ArrayList, you should make a ArrayList<JLabel>. But I take it you want to get the text from the JLabel, so you should write names.add(lab1.getText());.
The constructor you have made doesn't take any parameters. The parameters you have wrote are the instance variable, meaning those are the variables any instance of that class will have. If you want to pass parameters in your constructor you should do what thasc told you.
You write:
JLabel lab1 = new JLabel("User Name", JLabel.LEFT);
p.add(lab1 = new JLabel("User Name"));
But since you are already creating the lab1 JLabel you could just write p.add(lab1).
And a final note I think SampleFiveA should better extend JFrame unless you want it to extend JPanel to use it somewhere else. If you need it to be standalone you should change that.
cheers

Categories