Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / First Aid / December 2007

Tip: Looking for answers? Try searching our database.

ActionListener

Thread view: 
Art Cummings - 01 Dec 2007 18:44 GMT
Hello all,

I'm trying to understand how to invoke an ActionListener but maintain a
variable that will be available to another ActionListener called "previous".
The problem is how to have a variable persists between calls.  I want to
populate the ArrayList everytime the user hits next or previous and use my
variable to position it at the correct index.

As you no doubt can tell, i'm relatively new to java.

Thanks for any help

private class nextButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
int hold=0;
int index=0;
String name="";
ArrayList names = new ArrayList();
names = getNames();

name = names.get(index).toString();
System.out.println(name);
System.out.println(index);
index = index++;

}
}

private class previousButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
int hold=0;
int index=0;
String name="";
ArrayList names = new ArrayList();
names = getNames();//populates ArrayList

name = names.get(index).toString();
System.out.println(name);
System.out.println(index);
index = index++;

}
}
Knute Johnson - 01 Dec 2007 19:46 GMT
> Hello all,
>
[quoted text clipped - 43 lines]
> }
> }

Make the variables instance or class variables.

class MyClass {
    final ArrayList list = new ArrayList();

list is visible to the entire class including subclasses.

Signature

Knute Johnson
email s/nospam/knute/

Art Cummings - 01 Dec 2007 20:01 GMT
Knute, i'm not sure i understand.  I'm trying to make the index variable
availble to the other methods.  The idea is that this index can be used to
either go forward or backward depending on which ActionListener is called.
Is there a way to do this with an interger value?  You may have already
explained this and i'm too thick to see, so please have patience.

Art

>> Hello all,
>>
[quoted text clipped - 50 lines]
>
> list is visible to the entire class including subclasses.
RedGrittyBrick - 01 Dec 2007 22:55 GMT
Hello Art, you "top-posted" please don't do that. Top-posting
reorganised ...

> Knute Johnson wrote:
>
[quoted text clipped - 4 lines]
>>> everytime the user hits next or previous and use my variable to
>>> position it at the correct index.

[Code for two independent ActionListener classes omitted]

>> Make the variables instance or class variables.
>>
[quoted text clipped - 8 lines]
> value?  You may have already explained this and i'm too thick to see,
> so please have patience.

If you posted a more complete example, we'd be able to suggest a better
way to organise the code.

class IndexView extends JPanel implements ActionListener {

    private int index;
    private static String PRIOR = "Previous", NEXT = "Next";
    private JLabel indexLabel = new JLabel();

    IndexView() {
        JButton n = new JButton(NEXT);
        n.addActionListener(this);
        add(n);

        JButton p = new JButton(PRIOR);
        p.addActionListener(this);
        add(p);

        add (indexLabel);
    }

    // One actionlistener can service many buttons
    actionPerformed(ActionEvent e) {
    String command = e.getActionCommand();
        if (command.equals(PRIOR))
            index--;
        else if (command.equals(NEXT))
            index++;
        else
            System.out.println("Unexpected command " + command);

        indexLabel.setText("index = " + index);
    }

    // Maybe you need access to index in the class that
    // instantiates IndexView?
    public int getIndex() {
        return index;
    }

}

Untested. Batteries not included.
Art Cummings - 02 Dec 2007 00:17 GMT
Knute here's the whole things.  Red, i'm not sure what you mean by top
posting.

Art

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.text.DecimalFormat;
import java.util.ArrayList; // to use array list
import java.util.Scanner; // Needed for the Scanner class
import java.io.*; // Needed for the File class

public class StudentTestPlusButtons extends JFrame

{

private JButton prev;// previous record button
private JButton save;// save button
private JButton next;// next record button
private JRadioButton numberGrade;
private JRadioButton letterGrade;
private JRadioButton average;
private JButton exit;
private JLabel test_1;
private JLabel test_2;
private JLabel test_3;
private JTextField test1; // test 1 label
private JTextField test2; // test 2 label
private JTextField test3; // test 3 label
private JLabel name;
private JTextField student;
private JButton read;
private final int WINDOW_HEIGHT = 300;
private final int WINDOW_WIDTH = 500;
private JPanel buildPanel;
private JPanel buildButtonPanel;
private StudentAddWindow studentAdd;
private CalcGrade calc;
private GreetingPanel greet;
private ButtonGroup bg;
public final char SELECT = 'A';
static int index=0;

/**
Constructor
*/

public StudentTestPlusButtons()
{

//Set the title
setTitle("Student grade calculator");

setLayout(new BorderLayout());
//Set size of window
//setSize(WINDOW_WIDTH, WINDOW_HEIGHT);

//Close button
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create custom panels
studentAdd = new StudentAddWindow();
calc = new CalcGrade();
greet = new GreetingPanel();

//Build the panel and add it to the frame
buildPanel();
buildButtonPanel();

//Add components to the content pane
add(studentAdd, BorderLayout.EAST);
add(buildButtonPanel, BorderLayout.WEST);

add(calc, BorderLayout.CENTER);
add(buildPanel,BorderLayout.NORTH);
//PACK
pack();

//display the window
setVisible(true);
}

private void buildButtonPanel()
{
buildButtonPanel = new JPanel();

//buttons
prev = new JButton("Prev");
next = new JButton("Next");
save = new JButton("Save");
read = new JButton("Read record");
exit = new JButton("Exit");
//numer = new JRadioButton("Numeric grade");
//alpha = new JRadioButton("Letter grade");
//radio buttons
numberGrade = new JRadioButton();
letterGrade = new JRadioButton();
average = new JRadioButton();

//register action listeners
prev.addActionListener(new prevButtonListener());
next.addActionListener(new nextButtonListener());
save.addActionListener(new saveButtonListener());
read.addActionListener(new readButtonListener());
exit.addActionListener(new exitButtonListener());

//add buttons to panel
buildButtonPanel.add(prev);
buildButtonPanel.add(next);
buildButtonPanel.add(save);
buildButtonPanel.add(read);
buildButtonPanel.add(exit);

//add radio buttons
//group radio buttons
bg = new ButtonGroup();
bg.add(numberGrade);
bg.add(letterGrade);
bg.add(average);

/* bg = new ButtonGroup();
bg.add(numer);
bg.add(alpha);

buildButtonPanel.add(numer);
buildButtonPanel.add(alpha);*/

}

private void buildPanel()
{
buildPanel = new JPanel();

student = new JTextField(20);
name = new JLabel("Student name");

test_1 = new JLabel("Test 1");
test1 = new JTextField(10);
test_2 = new JLabel("Test 2");
test2 = new JTextField(10);
test_3 = new JLabel("Test 3");
test3 = new JTextField(10);

//clear data and set grades equal -1
test1.setText("");
test2.setText("");
test3.setText("");
student.setText("");

//add items to panel
buildPanel.add(name);
buildPanel.add(student);
buildPanel.add(test_1);
buildPanel.add(test1);
buildPanel.add(test_2);
buildPanel.add(test2);
buildPanel.add(test_3);
buildPanel.add(test3);

}

private class readButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
// Create a Scanner object for keyboard input.

//Scanner keyboard = new Scanner(System.in);
int count =0;
String name="";
ArrayList list = new ArrayList();

try
{

// Get the filename.
//System.out.print("Enter the filename: ");
//String filename = keyboard.nextLine();

// Open the file.
File file = new File("c:\\students.txt");

Scanner inputFile = new Scanner(file);

// Read lines from the file until no more are left.
while (inputFile.hasNext())
{
// Read the next name.
String StudentName = inputFile.nextLine();
list.add(StudentName);
count ++;
// Display the last name read.

}
System.out.println(count);
// Close the file.
name = list.get(0).toString();
student.setText(name);
inputFile.close();
}
catch(IOException x)
{
//System.out.println("Unable to add student - " + x.getMessage());
JOptionPane.showMessageDialog(null, "Unable to write record");
//JOptionPane.ERROR_MESSAGE);
System.exit(1);
}
}
}

private class saveButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{

}
}

private class nextButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
int hold=0;

String name="",hold1="",hold2="",hold3="";
ArrayList names = new ArrayList();
double[][] grades;
names = getNames();

//get and show name
name = names.get(index).toString();

grades = getScores();
System.out.println("the index is "+index);

//get and show grades
test1.setText(hold1 = Double.toString(grades[index][0]));
test2.setText(hold2 = Double.toString(grades[index][1]));;
test3.setText(hold3 = Double.toString(grades[index][2]));

index = index++;

//test1 = grades[index][1].toString();
}

}

private class exitButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}

private class prevButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
}
}

public char getGradeType()
{
char gType = 'A';

if (numberGrade.isSelected())
gType = 'N';
else if (letterGrade.isSelected())
gType = 'L';
else
gType = 'A';
return gType;
}

public double[][] getScores()
{
// Create a Scanner object for keyboard input.
final int ROW = 3, COL=3;
int row=0;
double [][] gradeArray;
gradeArray = new double[ROW][COL];

try
{
// Open the file.
File file = new File("c:\\grades.txt");
Scanner inputFile = new Scanner(file);
while (inputFile.hasNext())
{
String line = inputFile.nextLine();
row ++;
}

inputFile.close();

//File file = new File(filename);
// Scanner inputFile = new Scanner(file);
file = new File("c:\\grades.txt");
inputFile = new Scanner(file);

/* while (inputFile.hasNext())
{*/
for (int i=0; i < row ; i++)

{
String line = inputFile.nextLine();
String hold, line2="", linenew;
System.out.println("the row amount " + row);
double hold2,hold3=0;
int lineLength = 0;
int comma=0;
int beg=0;

for (int x=0; x < COL; x++)
{
System.out.println("you got here");
lineLength = line.length();
comma = line.indexOf(',');
linenew = line.substring(beg,comma);
hold3 = Double.parseDouble(linenew);
gradeArray[i][x] = hold3;
line = line.substring(beg+(comma+1),lineLength);
System.out.println(hold3);
//line = line.substring(comma,lineLength - comma);
}//end inner for

}// end outer for
// Close the file.

inputFile.close();
System.out.println("this is the outer loop");
//

}catch(IOException x)
{
//System.out.println("Unable to add student - " + x.getMessage());
JOptionPane.showMessageDialog(null, "Unable to read record");
//JOptionPane.ERROR_MESSAGE);
System.exit(1);
}

return gradeArray;

}

public ArrayList getNames()
{
int count =0;
String name="";
ArrayList list = new ArrayList();

try
{

// Get the filename.
//System.out.print("Enter the filename: ");
//String filename = keyboard.nextLine();

// Open the file.
File file = new File("c:\\students.txt");

Scanner inputFile = new Scanner(file);

// Read lines from the file until no more are left.
while (inputFile.hasNext())
{
// Read the next name.
String StudentName = inputFile.nextLine();
list.add(StudentName);
count ++;
// Display the last name

}
System.out.println(count);
// Close the file.
name = list.get(0).toString();
student.setText(name);
inputFile.close();
}
catch(IOException x)
{
//System.out.println("Unable to add student - " + x.getMessage());
JOptionPane.showMessageDialog(null, "Unable to write record");
//JOptionPane.ERROR_MESSAGE);
System.exit(1);
}

return list;
}

}

> Hello Art, you "top-posted" please don't do that. Top-posting reorganised
> ...
[quoted text clipped - 64 lines]
>
> Untested. Batteries not included.
Knute Johnson - 02 Dec 2007 02:26 GMT
Art:

By top posting he means not to put the content of your new post on top
of the old post.  Frankly I don't care but I know you will get unending
grief if you don't.

As to your code.  I was not able to compile it because it was missing
several pieces so we will ignore that for the moment.  ActionListeners
consume a lot of memory and you usually only need one so I would go with
one.  When you create a button and add an ActionListener to it, it will
default to using the text of the button as its actionCommand.  So your
button looks like this;

JButton b = new JButton("Press Me");
addActionListener(al);

Your action listener then tests the action command to branch to the
appropriate code;

ActionListener al = new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
        String ac = ae.getActionCommand();

        if (ac.equals("Press Me")) {
            // do this
        } else if (ac.equals("Quit")) {
            // do that
        }

I like to set up my main class as an ActionListener implementor;

public class MainClass extends Whatever implements ActionListener {

So in my MainClass I have to have a method;

    public void actionPerformed(ActionEvent ae) {
        //
    }

Then when I create my buttons I just;

    JButton b = new JButton("Press Me");
    b.addActionListener(this);

So your question on how to get to the variable in multiple
ActionListeners or methods?

public class MyClass extends JFrame implements ActionListener {
    private int seeEveryWhereIndex;

    // a lot of other stuff

    // gui code
    JButton b = new JButton("Decrement");
    b.addActionListener(this);

    b = new JButton("Increment");
    b.addActionListener(this);

    // other stuff

    public void actionPerformed(ActionEvent ae) {
        String ac = ae.getActionCommand();

        if (ac.equals("Decrement")) {
            --seeEveryWhereIndex;
        } else if (ac.equals("Increment")) {
            ++seeEveryWhereIndex;
        }

Putting your "seeEveryWhere" variable where we have it here makes it
visible to your whole class.

One other thing that will make your life easier (as well as the folks
who try to help you on this list) is to indent your source code like
mine is above.  It makes it much easier to read.  There are also some
recommended standards for variable and class names.

http://java.sun.com/docs/codeconv/html/CodeConventions.doc8.html

These just make it easier for others to know what you are up to.

Unless my program is really large or I'm going to use the same code
multiple times, I like to build my GUI in a primary container.  In your
example above, I would put my GUI code in the StudentTest?? class.

A simple example below;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class test extends JFrame implements ActionListener {
    private int index;
    private JLabel label;

    public test() {
        super("test");

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new GridBagLayout());

        GridBagConstraints c = new GridBagConstraints();
        c.insets = new Insets(2,2,2,2);
        c.gridx = 0;

        label = new JLabel(Integer.toString(index));
        add(label,c);

        JButton b = new JButton("Increment");
        b.addActionListener(this);
        add(b,c);

        b = new JButton("Decrement");
        b.addActionListener(this);
        add(b,c);

        pack();
        setVisible(true);
    }

    public void actionPerformed(ActionEvent ae) {
        String ac = ae.getActionCommand();

        if (ac.equals("Increment")) {
            ++index;
            label.setText(Integer.toString(index));
        } else if (ac.equals("Decrement")) {
            --index;
            label.setText(Integer.toString(index));
        }
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                new test();
            }
        });
    }
}

Signature

Knute Johnson
email s/nospam/knute/

Art Cummings - 02 Dec 2007 15:41 GMT
Thanks Knute,

Art


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.