Listening events on another class
Hi, I am doing a program that uses differents jpanels, So I need to set a button enabled when an event ocurrs in another panel, how can I do that. the problem is that the panel from wich I need to listen is another class.
please can someone help me posting some small code that shows how can I listen events on other classes. I think I am able to detect it changing a static variable on another class and having a thread that verify its state, But i dont want to do that, I want to use a listener or any other similar way.
there's a lot of ways so it depends on the architecture of your program.
here's a couple of ideas to play with.
import javax.swing.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class MyFrame extends javax.swing.JFrame {
public MyFrame(AnotherClass a) {
JButton b1 = new JButton("OK");
b1.addActionListener(a);
JButton b2 = new JButton(a.getButtonAction("Cancel"));
getContentPane().setLayout(new java.awt.FlowLayout());
getContentPane().add(b1);
getContentPane().add(b2);
setLocationRelativeTo(null);
pack();
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
public static void main(String[] args){
new MyFrame(new AnotherClass()).setVisible(true);
import javax.swing.Action;
import javax.swing.AbstractAction;
import java.awt.event.*;
public class AnotherClass implements ActionListener {
private Action a;//cancel action
public AnotherClass() {}
private void setEnabled(boolean b){
a.setEnabled(b);
//cancel action
public Action getButtonAction(String name){
a = new AbstractAction(name){
public void actionPerformed(ActionEvent ae){
System.out.println("Cancel");
return a;
public void actionPerformed(ActionEvent e) {
//ok button action
System.out.println("okay");
}
Similar Messages
-
Listening events in another class in a another folder
Listening events in another class in a another folder
Is there away of controlling a event from another location without being in the same directory/location.
I've got a button made and a Event Action for the button made in two seperate classes. But I can't make them work without placing them both in the same location together.
Any simple code that help communicate of long distances/folders.
Thankyous.The "distance" should not be an issue, only visibility. The class that contains the button need to implement some public method of adding an ActionListener to the button. Of course the class that implements the action listener would have to have access to the instance of the button class to call that method.
Class A {
private JButton myButton;
public void addActionListenerToButton (ActionListener listener){
myButton.addActionListener (listener);
} -
Handeling listner and window events in another class
All if i have my one class that defines a JPanel how i put my listner events into another class.
so if i had
import javax.swing.*;
class MyFrame extends JFrame {
public MyFrame() {
setTitle("My Empty Frame");
setSize(300,200); // default size is 0,0
setLocation(10,200); // default is 0,0 (top left corner)
public static void main(String[] args) {
JFrame f = new MyFrame();
f.show();
}And then in a class WindowEvents.class i wanted to have all of the actions for any buttons
etc. How do i interface that with the main JPanel or JFrameI would make another class, for instance if you were doing an ActionListener event, you'd have a seperate class such as,
public class ButtonHandler implements ActionListener {
private YourPanelClass view;
public ButtonHandler(YourPanelClass view) {
this.view = view;
public void actionPerformed(ActionEvent e) {
//event handling code
view.updateGUI();
}Then in your main frame class, you'd want an updateGUI(); method which would perform the actions required and to add the event to your button you'd do something like this:
ImageIcon upIcon = new ImageIcon("navigationIcons/Up24.gif", "Up Button");
JButton upBtn = new JButton(upIcon);
upBtn.setToolTipText("Up");
UpdateButtonHandler ubh = new UpdateButtonHandler(this);
upBtn.setActionCommand("bob");
upBtn.addActionListener(ubh);I'm actually having a simular problem to you, where as I have 1 class for my main frame, one class for my button panel with the buttons on and 1 class for my graphics cpt which im moving about via pressing the buttons. Then another class for my actionListener event, im finding it hard to get the event to work correctly because the updateGUI(); method theoretically needs to be placed inside my button panel class, but if I do that I can't seem to update the graphics cpt properly to actually move it, unless I do it in the main frame class which then means I can't have a seperate class for my button panel. Anyone got any ideas on a solution? -
In java,how to trigger an event in one class from an event in another class
i need sloution to thisbecause, when the swing components are colloborating each other,i need to control the components with respect to others events.
eventListeners are the way to go.
-Js -
Listen for event in own class?
Hi
I dispatch events from models to classes listening. How do you set up an event and listener in the same class?
Eg for the former - a model "MyModel" to class - it's:
public static const MY_VAR:String = "myVar";
triggered by...
dispatchEvent(new Event(MY_VAR));
picked up in another class by...
modelVar.addEventListener(MyModel.MY_VAR, doSomething);
but what if the class that's dispatching also has the listener?
So if MyClass is dispatching the event, along the lines of...
addEventListener(MyClass.MY_VAR, doSomething);
Cheers for taking a lookVery often I'm waiting for a few key items before I can finally do something else. Setting simple flags or checking nulls can help with this.
Often I download multiple data structures (JSON/XML/etc) and I need all of them before I can parse them because the co-depend on each other. URLLoaders finish at different times so I just set a flag for what I need but check if all are complete before I continue each time one finishes.
e.g.
package
public class IHateWaiting extends EventDispatcher
public static const MY_VAR:String = "myVar";
private var _xmlA:XML;
private var _xmlB:XML;
public function IHateWaiting()
// load A
var ulA:URLLoader = new URLLoader();
ulA.addEventListener(Event.COMPLETE, _handleFinishedF);
ulA.load(new URLRequest("http://www.example.com/a.xml"));
// load B
var ulB:URLLoader = new URLLoader();
ulB.addEventListener(Event.COMPLETE, _handleFinishedF);
ulB.load(new URLRequest("http://www.example.com/b.xml"));
// listen to self
addEventListener(IHateWaiting.MY_VAR, _handleAppEventF);
private function _handleFinishedF(e:Event):void
if (e.type == Event.COMPLETE)
var data:XML = XML(e.target.data);
// A or B? any way you can tell
if (data.A.length() > 0) _xmlA = data;
else if (data.B.length() > 0) _xmlB = data;
// event method (requires extra handler or a fake event)
if (_xmlA && _xmlB) dispatchEvent(new Event(IHateWaiting.MY_VAR));
// preferred direct reference, no handler needed
// if (_xmlA && _xmlB) _parseXML();
private function _handleAppEventF(e:Event):void
if (e.type == IHateWaiting.MY_VAR) _parseXML();
private function _parseXML():void
// parse XML
I recommend the reference version from post #2. It's cleaner because you don't need to double up on functions (handler->reference) like you see above with dispatching. The only purpose for _handleAppEventF() in this case is just to run _parseXML(), which is a useless duplicate function.
I've always kept my handlers free of model-esque logic, so you see me calling a different function from that handler, _parseXML(). This is just because I want my handlers to only handle events and then hand off the work elsewhere.
Instead of dispatching the event, I agree with moccamaximum, run the method directly. Even if it's 2 lines of code to do 1 thing, I think the clarity of it is much cleaner coding. So I would recommend nuking the self-listener in the constructor above. When I have all the data I'm looking for, I'd run the methods in the class directly and If the parent needs to know, I'd dispatch when they complete.
e.g.
private function _handleFinishedF(e:Event):void
if (e.type == Event.COMPLETE)
var data:XML = XML(e.target.data);
// A or B? any way you can tell
if (data.A.length() > 0) _xmlA = data;
else if (data.B.length() > 0) _xmlB = data;
if (_xmlA && _xmlB)
// parse first (synchronous)
_parseXML();
// xml ready, dispatch to parent
dispatchEvent(new Event(IHateWaiting.MY_VAR)); -
Event handling from class to another
i get toolbarDemo.java which make event handling to JTextArea in the same class
http://java.sun.com/docs/books/tutorial/uiswing/components/example-1dot4/index.html#ToolBarDemo
but i have another class and i make object of toolBar class and i move toolBar icons only how can i move the event handling as open ,save,copy,paste to my another class
i want to ignore actionPerformed of toolBar class and listen to my another's class actionPerformed
thanksRather than trying to use the ToolBarDemo class as-is you can use/modify the methods in it for your own class, like this:
import java.awt.*;
import java.awt.event.*;
import java.net.URL;
import javax.swing.*;
import javax.swing.text.TextAction;
public class ToolBarIconTest implements ActionListener
static final private String OPEN = "open";
static final private String SAVE = "save";
static final private String COPY = "copy";
static final private String PASTE = "paste";
public void actionPerformed(ActionEvent e)
String cmd = e.getActionCommand();
if (OPEN.equals(cmd))
System.out.println("show a JFileChooser open dialog");
if (SAVE.equals(cmd))
System.out.println("show a JFileChooser save dialog");
private JToolBar getToolBar()
JToolBar toolBar = new JToolBar();
addButtons(toolBar);
return toolBar;
protected void addButtons(JToolBar toolBar) {
JButton button = null;
//first button
button = makeGeneralButton("Open24", OPEN,
"To open a document",
"Open", this);
toolBar.add(button);
//second button
button = makeGeneralButton("Save24", SAVE,
"To save a document",
"Save", this);
toolBar.add(button);
//third button
button = makeGeneralButton("Copy24", COPY,
"Copy from focused text component",
"Copy", copy);
toolBar.add(button);
//fourth button
button = makeGeneralButton("Paste24", PASTE,
"Paste to the focused text component",
"Paste", paste);
toolBar.add(button);
protected JButton makeGeneralButton(String imageName,
String actionCommand,
String toolTipText,
String altText,
ActionListener l) {
//Look for the image.
String imgLocation = "toolbarButtonGraphics/general/"
+ imageName
+ ".gif";
URL imageURL = ToolBarIconTest.class.getResource(imgLocation);
//Create and initialize the button.
JButton button = new JButton();
button.setActionCommand(actionCommand);
button.setToolTipText(toolTipText);
button.addActionListener(l);
if (imageURL != null) { //image found
button.setIcon(new ImageIcon(imageURL, altText));
} else { //no image found
button.setText(altText);
System.err.println("Resource not found: "
+ imgLocation);
return button;
private Action copy = new TextAction(COPY)
public void actionPerformed(ActionEvent e)
JTextComponent tc = getFocusedComponent();
int start = tc.getSelectionStart();
int end = tc.getSelectionEnd();
if(start == end)
tc.selectAll();
tc.copy();
private Action paste = new TextAction(PASTE)
public void actionPerformed(ActionEvent e)
getFocusedComponent().paste();
private JPanel getTextFields()
JPanel panel = new JPanel(new BorderLayout());
panel.add(new JTextField(12), "North");
panel.add(new JTextField(12), "South");
return panel;
public static void main(String[] args)
ToolBarIconTest test = new ToolBarIconTest();
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(test.getToolBar(), "North");
f.getContentPane().add(test.getTextFields());
f.setSize(360,240);
f.setLocation(200,200);
f.setVisible(true);
}Use the -cp option as shown in the ToolBarDemo class comments
C:\jexp>java -cp .;path_to_jar_file/jlfgr-1_0.jar ToolBarIconTest -
Fire event from one class to another.
I have a Login JFrame class that allows users to enter username and password. I then have another JFrame class which will monitor when someone logs in. I am trying to get the username and password to appear on the monitor login frame text area when the user presses enter on the login frame.
I can get it ot work by passing the Monitor class into the Login classes constructor but I want to be able to open the classes separately.When I try to open separatley at present I get java.lang.NullPointerException
at project.LoginGUI.actionPerformed(LoginGUI.java:70) which is referring to the following code:
if(listen.equals("OK")){
GymMonitor.username.setText(username.getText());
Both classes are in the same package. What I want to know is how to fire an event from one class to another? when the class you are firing to is constructed separately.
I hope this question is not too verbose.
ThanksGenerally for something like this you would use a listener.
Your login window is its own entity--it has a user interface, and it gets some information which someone else could ask it for. It could even generate its own events, such as when the user presses "OK". You would first define an interface for anyone who wants to know when someone logs in:
public interface ILoginListener extends java.util.EventListener
public void login(LoginEvent event);
}You would then define the LoginEvent class to contain information like what the user entered for username and password. You could give your login dialog a couple of methods:
private Vector myListeners = new Vector();
public void addLoginListener(ILoginListener listener) {
myListeners.add(listener);
public void removeLoginListener(ILoginListener listener) {
myListeners.remove(listener);
protected void fireLogin(LoginEvent event) {
for (Iterator it = myListeners.iterator(); it.hasNext(); ) {
ILoginListener listener = (ILoginListener)it.next();
listener.login(event);
}You'd have your login dialog call fireLogin every time the user logged in.
Then, you could implement ILoginListener in your monitor window:
public void login(LoginEvent event) {
// now do something with the event you just got.
}All the code I put in here is really generic stuff. You'll write this kind of stuff hundreds of times probably during your career. I haven't tested it though.
Hope this helps. :) -
Getting values from a JTextField on a JPanel in another class
I have created a class which extends a JPanel and added a JTextField to it, which has an addActionListener for getting the values typed in the JTextField. I want to use the class created in another class and retrieve the values typed in the JTextField, so how do i go about that? I have the class created below so the problem is how to retrieve content of val[val] in another class?
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class TextFieldChooser extends JPanel{
int val;
public TextFieldChooser(String str){
val = 0;
setLayout(new FlowLayout());
add(new JLabel(str));
JTextField txtf = new JTextField(5);
txtf.addActionListener(new TextFieldListener());
add(txtf);
}//end constructor
private class TextFieldListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
val = Integer.parseInt(e.getActionCommand());
}//end text field listener
public int getValue(){
return val;
}//classThe problem is which listener can be programmed to handle the event performed on the class TextFieldChooser in the other class?
I have created a class which extends a JPanel and
added a JTextField to it, which has an
addActionListener for getting the values typed in the
JTextField. I want to use the class created in
another class and retrieve the values typed in the
JTextField, so how do i go about that? I have the
class created below so the problem is how to retrieve
content of val[val] in another class?
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class TextFieldChooser extends JPanel{
int val;
public TextFieldChooser(String str){
val = 0;
setLayout(new FlowLayout());
add(new JLabel(str));
JTextField txtf = new JTextField(5);
txtf.addActionListener(new TextFieldListener());
add(txtf);
}//end constructor
private class TextFieldListener implements
s ActionListener{
public void actionPerformed(ActionEvent e) {
val = Integer.parseInt(e.getActionCommand());
}//end text field listener
public int getValue(){
return val;
}//class -
Easy question: Give access to a class in another class.
Stupid title, but dont know how to express myself :P Sorry for that.
To the problem. Never had this problem before, and I know its a really easy solution to this.
I have my Main class, which creates a MyView class. Inside this class, I make to new classes(or instances of classes i've already made), MyPanel and MyToolsPanel. Now I want to add buttons inside the MyToolsPanel class, and add actionlisteners to these buttons inside MyPanel.
What I'v always done to grant access to MyToolsPanel inside of MyTools, is to simply add a
//this is the MyPanel class
MyToolsPanel mtp;
public void setMtp(MyToolsPanel mtp){
this.mtp = mtp;
}and then in the MyView class which create these to classes, I put a command: mp.setMtp(mtp);
When I run this it doesnt work.. Why? Should be easy to solve, since it obviously is a stupid problem that I just dont see. :P Feeling kind of stupid to ask this question, but this is how it is...
EDIT: I might have to implement actionListener inside the MyToolsPanel class?
Edited by: Stianbl on Sep 28, 2008 4:59 PMone way:
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextField;
* Subclasses JPanel, can send text out via the getText() method
* can hook into button press via addActionListener
* @author Pete
public class PanelCommSender extends JPanel
private JTextField sendingField = new JTextField(12);
private JButton sendButton = new JButton("Send");
public PanelCommSender()
add(sendingField);
add(sendButton);
public void addActionListener(ActionListener al)
// attach this listener to the button
sendButton.addActionListener(al);
* call this to get the text currently in the textfield
* @return String text
public String getText()
return sendingField.getText();
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
* Subclasses JPanel, receives text from another class
* @author Pete
public class PanelCommReceiver extends JPanel
private JTextField showResultsField = new JTextField(12);
public PanelCommReceiver()
showResultsField.setEditable(false);
add(new JLabel("Results from other panel: "));
add(showResultsField);
* call this to set text of textField
* @param text
public void setText(String text)
showResultsField.setText(text);
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JDialog;
import javax.swing.JFrame;
public class PanelCommControl
private static void createAndShowUI()
// create new instances of the receiving and sending panels:
final PanelCommReceiver receivePanel = new PanelCommReceiver();
final PanelCommSender sendPanel = new PanelCommSender();
// let the communicate w/ each other
sendPanel.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
receivePanel.setText(sendPanel.getText());
// place the receiving JPanel into a JFrame
JFrame frame = new JFrame("Receiving Panel");
frame.getContentPane().add(receivePanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(300, 300)); // make it bigger so it can be seen
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
// place the sending JPanel into a JDialog
JDialog dialog = new JDialog(frame, "Sending Panel", false);
dialog.getContentPane().add(sendPanel);
dialog.pack();
dialog.setLocationRelativeTo(null);
dialog.setVisible(true);
public static void main(String[] args)
java.awt.EventQueue.invokeLater(new Runnable()
public void run()
// run the whole show in a thread-safe manner
createAndShowUI();
} -
Calling method from another class problem
hi,
i am having problem with my code. When i call the method from the other class, it does not function correctly?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class Dice extends JComponent
private static final int SPOT_DIAM = 9;
private int faceValue;
public Dice()
setPreferredSize(new Dimension(60,60));
roll();
public int roll()
int val = (int)(6*Math.random() + 1);
setValue(val);
return val;
public int getValue()
return faceValue;
public void setValue(int spots)
faceValue = spots;
repaint();
@Override public void paintComponent(Graphics g) {
int w = getWidth();
int h = getHeight();
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(Color.WHITE);
g2.fillRect(0, 0, w, h);
g2.setColor(Color.BLACK);
g2.drawRect(0, 0, w-1, h-1);
switch (faceValue)
case 1:
drawSpot(g2, w/2, h/2);
break;
case 3:
drawSpot(g2, w/2, h/2);
case 2:
drawSpot(g2, w/4, h/4);
drawSpot(g2, 3*w/4, 3*h/4);
break;
case 5:
drawSpot(g2, w/2, h/2);
case 4:
drawSpot(g2, w/4, h/4);
drawSpot(g2, 3*w/4, 3*h/4);
drawSpot(g2, 3*w/4, h/4);
drawSpot(g2, w/4, 3*h/4);
break;
case 6:
drawSpot(g2, w/4, h/4);
drawSpot(g2, 3*w/4, 3*h/4);
drawSpot(g2, 3*w/4, h/4);
drawSpot(g2, w/4, 3*h/4);
drawSpot(g2, w/4, h/2);
drawSpot(g2, 3*w/4, h/2);
break;
private void drawSpot(Graphics2D g2, int x, int y)
g2.fillOval(x-SPOT_DIAM/2, y-SPOT_DIAM/2, SPOT_DIAM, SPOT_DIAM);
}in another class A (the main class where i run everything) i created a new instance of dice and added it onto a JPanel.Also a JButton is created called roll, which i added a actionListener.........rollButton.addActionListener(B); (B is instance of class B)
In Class B in implements actionlistener and when the roll button is clicked it should call "roll()" from Dice class
Dice d = new Dice();
d.roll();
it works but it does not repaint the graphics for the dice? the roll method will get a random number but then it will call the method to repaint()???
Edited by: AceOfSpades on Mar 5, 2008 2:41 PM
Edited by: AceOfSpades on Mar 5, 2008 2:42 PMOne way:
class Flintstone
private String name;
public Flintstone(String name)
this.name = name;
public String toString()
return name;
public static void useFlintstoneWithReference(Flintstone fu2)
System.out.println(fu2);
public static void useFlintstoneWithOutReference()
Flintstone barney = new Flintstone("Barney");
System.out.println(barney);
public static void main(String[] args)
Flintstone fred = new Flintstone("Fred");
useFlintstoneWithReference(fred); // fred's the reference I"m passing to the method
useFlintstoneWithOutReference();
{code}
can also be done with action listener
{code} private class MyActionListener implements ActionListener
private Flintstone flintstone;
public MyActionListener(Flintstone flintstone)
this.flintstone = flintstone;
public void actionPerformed(ActionEvent arg0)
//do whatever using flinstone
System.out.println(flintstone);
}{code}
Edited by: Encephalopathic on Mar 5, 2008 3:06 PM -
Stop a method from executing until another class does its bit
Hi all,
For my app I have a login screen where to get login success the user must first register. I therefore have two class LoginDialog and Register which is a dialog.
In LoginDialog if the user clicks on Register it brings up a new instance of the Register dialog but continues to process the calling method (which happens to return to another class processing the login). What I require is that when I create a new Register object, the creating method does nothing until the Registration form is completed. I'm not at all au fait with threads so was wondering if there is an easy way to do it.
I have thought of passing the LoginDialog as an argument in the Register constructor and having an empty while loop running in the invoking method (i.e. while (false) do nothing) and creating public access to that boolean variable so that at completion of the registration it sets the boolean variable to true in LoginDialog so it should break out of the while loop and continue. Is that a satisfactory way of pausing and restarting a method?
Cheers,
ChrisHi,
I have a MainFrame class which calls processLogin which creates a new LoginDialog which houses the Register button. When I click on the register button it opens a new Registration screen but LoginDialog returns to MainFrame in the background and says that no user has logged in. What I require is that when the Register object is created after clicking the Register button that LoginDialog waits until the Registration is complete.
Maybie the code will help (sorry if it is a bit lengthy).
Snippet of LoginDialog
public void actionPerformed(ActionEvent event)
if(event.getSource() == ok) {
_username = user.getText();
_password = new String(password.getPassword());
_server = server.getText();
//ensure port number is an integer
try{
_port = Integer.parseInt(port.getText());
catch(NumberFormatException e){
JOptionPane.showMessageDialog(this,
"Please use an integer value only for the port number","Error",
JOptionPane.WARNING_MESSAGE);
//checks username and password length
if((_username.length()==0) || (_password.length() == 0)){
JOptionPane.showMessageDialog(this,
"Please enter a valid username and password","Error",
JOptionPane.WARNING_MESSAGE);
return;
//checks server length
if(_server.length()== 0){
JOptionPane.showMessageDialog(this,
"Invalid server host","Error",
JOptionPane.WARNING_MESSAGE);
return;
try{
db = new DatabaseConnection();
boolean exists = db.doesUserExist(_username, _password);
db.close();
if(exists){
//System.out.println("User exists on database");
this.dispose(); //get rid of login screen now user is confirmed
if(!exists){
_username = null;
_password = null;
this.dispose();
catch(java.sql.SQLException e){
JOptionPane.showMessageDialog(this,
"Unable to connect to database. Please try again.","Error",
JOptionPane.WARNING_MESSAGE);
else if(event.getSource() == cancel) {
//NOTHING
else if(event.getSource() == register){
Register register = new Register();
//while (processRegistration){
this.setVisible(false);
}and Register
//import classes
import java.io.*;
import java.net.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;
public class Register extends JFrame implements ActionListener {
//declare components
JLabel lblHeading;
JLabel lblUserName;
JLabel lblUserPwd;
JLabel lblCnfUserPwd;
JLabel lblFirstName;
JLabel lblLastName;
JLabel lblAge;
JLabel lblEmpId;
JLabel lblEmail;
JLabel lblSex;
String userName;
char[] userPwd;
char[] cnfPwd;
String strUserPwd;
String strCnfUserPwd;
String firstName;
String lastName;
String age;
String empid;
String email;
String sexStr;
Socket toServer;
ObjectInputStream streamFromServer;
PrintStream streamToServer;
JComboBox comboSex;
JTextField txtUserName;
JPasswordField txtUserPwd;
JPasswordField txtCnfUserPwd;
JTextField txtFirstName;
JTextField txtLastName;
JTextField txtAge;
JTextField txtEmpId;
JTextField txtEmail;
Font f;
Color r;
JButton btnSubmit;
JButton btnCancel;
DatabaseConnection db;
boolean exists, entrySuccess;
public Register() {
this.setTitle("Register");
JPanel panel=new JPanel();
//apply the layout
panel.setLayout(new GridBagLayout());
GridBagConstraints gbCons=new GridBagConstraints();
//place the components
gbCons.gridx=0;
gbCons.gridy=0;
lblHeading=new JLabel("Registration Info");
Font f = new Font("Monospaced" , Font.BOLD , 12);
lblHeading.setFont(f);
Color c=new Color(0,200,0);
lblHeading.setForeground(new Color(131,25,38));
lblHeading.setVerticalAlignment(SwingConstants.TOP);
gbCons.anchor=GridBagConstraints.EAST;
panel.add(lblHeading, gbCons);
gbCons.gridx = 0;
gbCons.gridy = 1;
lblUserName = new JLabel("Enter Username");
gbCons.anchor=GridBagConstraints.WEST;
panel.add(lblUserName, gbCons);
gbCons.gridx=1;
gbCons.gridy=1;
txtUserName=new JTextField(15);
panel.add(txtUserName, gbCons);
gbCons.gridx=0;
gbCons.gridy=2;
lblUserPwd=new JLabel("Enter Password ");
panel.add(lblUserPwd, gbCons);
gbCons.gridx = 1;
gbCons.gridy = 2;
txtUserPwd = new JPasswordField(15);
panel.add(txtUserPwd, gbCons);
gbCons.gridx=0;
gbCons.gridy=3;
lblCnfUserPwd=new JLabel("Confirm Password ");
panel.add(lblCnfUserPwd, gbCons);
gbCons.gridx=1;
gbCons.gridy=3;
txtCnfUserPwd=new JPasswordField(15);
panel.add(txtCnfUserPwd, gbCons);
gbCons.gridx=0;
gbCons.gridy=4;
lblEmpId=new JLabel("Employee ID");
panel.add(lblEmpId, gbCons);
gbCons.gridx=1;
gbCons.gridy=4;
txtEmpId=new JTextField(15);
panel.add(txtEmpId, gbCons);
gbCons.gridx=0;
gbCons.gridy=5;
lblFirstName=new JLabel("First Name");
panel.add(lblFirstName, gbCons);
gbCons.gridx=1;
gbCons.gridy=5;
txtFirstName=new JTextField(15);
panel.add(txtFirstName, gbCons);
gbCons.gridx=0;
gbCons.gridy=6;
lblLastName=new JLabel("Last Name");
panel.add(lblLastName, gbCons);
gbCons.gridx = 1;
gbCons.gridy = 6;
txtLastName=new JTextField(15);
panel.add(txtLastName, gbCons);
gbCons.gridx=0;
gbCons.gridy=7;
lblAge=new JLabel("Age");
panel.add(lblAge, gbCons);
gbCons.gridx=1;
gbCons.gridy=7;
txtAge=new JTextField(3);
panel.add(txtAge, gbCons);
gbCons.gridx=0;
gbCons.gridy=8;
lblEmail=new JLabel("Email");
panel.add(lblEmail, gbCons);
gbCons.gridx=1;
gbCons.gridy=8;
txtEmail=new JTextField(20);
panel.add(txtEmail, gbCons);
gbCons.gridx=0;
gbCons.gridy=9;
lblSex=new JLabel("Sex");
panel.add(lblSex, gbCons);
gbCons.gridx = 1;
gbCons.gridy=9;
String [] sexArr = {"Male", "Female"};
comboSex = new JComboBox(sexArr);
comboSex.setSelectedIndex(0);
panel.add(comboSex, gbCons);
JPanel btnPanel=new JPanel();
btnSubmit=new JButton("Submit");
btnPanel.add(btnSubmit);
btnSubmit.addActionListener(this); //add listener to the Submit button
btnCancel=new JButton("Cancel");
btnPanel.add(btnCancel);
btnCancel.addActionListener(this); //add listener to the Cancel button
gbCons.gridx=0;
gbCons.gridy=10;
gbCons.anchor=GridBagConstraints.EAST;
panel.add(btnPanel, gbCons);
getContentPane().add(panel);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setVisible(true);
setSize(450,400);
}//end or Register()
public void actionPerformed(ActionEvent ae) {
Object o = ae.getSource(); //get the source of the event
if(o == btnCancel)
this.dispose();
if(o == btnSubmit){
userName = txtUserName.getText();
userPwd = txtUserPwd.getPassword();
strUserPwd = new String(userPwd);
cnfPwd = txtCnfUserPwd.getPassword();
strCnfUserPwd = new String(cnfPwd);
firstName = txtFirstName.getText();
lastName = txtLastName.getText();
age = txtAge.getText();
empid = txtEmpId.getText();
email = txtEmail.getText();
sexStr = (String)comboSex.getItemAt(0);
db = new DatabaseConnection();
//Now check to see if username and password combination have been
//taken
try{
exists = db.doesUserExist(userName.trim(), strUserPwd.trim());
catch (java.sql.SQLException e){
System.out.println(e);
//Checks that each field has been filled in.
if(userName.length() == 0 || strUserPwd.length() == 0 ||
strCnfUserPwd.length() == 0 || firstName.length() == 0 ||
lastName.length() == 0 || age.length() == 0 || empid.length() == 0
|| email.length() == 0){
JOptionPane.showMessageDialog(this,
"One or more entry has not been filled in. Please go back and try again",
"Message", JOptionPane.ERROR_MESSAGE);
//Ensures that passwords match
if(!strUserPwd.equals(strCnfUserPwd)){
JOptionPane.showMessageDialog(this,
"Passwords do not match. Please go back and try again",
"Message", JOptionPane.ERROR_MESSAGE);
if(exists){
JOptionPane.showMessageDialog(this,
"Username and password combination already exists. Please go back and try again",
"Message", JOptionPane.ERROR_MESSAGE);
if(!exists) {
String userDetails = (userName.trim() + " " + strUserPwd.trim()
+ " " + firstName.trim() + " "
+ lastName.trim() + " " + age.trim() + " " + empid.trim() + " "
+ email.trim() + " " + sexStr.trim());
//System.out.println(userDetails);
//Try to connect to the database and insert the user details.
//If successful then user will be alerted and the registration page
//should be disposed automatically. If for some reason the insert
//was not successful then user is prompted to try again.
try{
entrySuccess = db.registerUser(userDetails);
if(entrySuccess){
JOptionPane.showMessageDialog(this,
"Congratulations, you have successfully registered for the Instant Messenger service!",
"Message", JOptionPane.INFORMATION_MESSAGE);
this.dispose();
if(!entrySuccess){
JOptionPane.showMessageDialog(this,
"There was a problem entering your details. Please try again.",
"Message", JOptionPane.ERROR_MESSAGE);
catch(java.sql.SQLException e){
}//end of else
db.close();
}//end of actionPerformed()
}//end of classCheers,
Chris -
Accessing an Array List from another class
Hi, I was a member on here before, but I forgot my password and my security question is wrong.
My question is how do I access a private arraylist from a different class in the same package?
What I am trying to do is the following (hard to explain).
Make a picking client for a shop, so that when an order is recieved, the picker can click on the orders button, and view all of the current orders that have not been completed. This Pick client has its own user interface, in a seperate class from where the BoughtList array is created, in the cashier client. The boughtlist is created when the cashier puts in the product number into the cashier client and clicks buy. I seem to be having trouble accessing the list from another class. Once the order is completed the cashier clicks bought and the list is reset. There is another class in a different pagage that processes some of the functions of the order, eg newOrder().
Yes it is for Uni so I dont need / want the full answers, jist something to get started. Also please dont flame me, I have done many other parts of this project, just having trouble getting started on this one.
Here is the code for the cashier client. The code for the Pick client is almost the same, I just need to make the code that displays the orders.
package Clients;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.NumberFormat;
import java.util.Locale;
import Catalogue.*;
import DBAccess.*;
import Processing.*;
import Middle.*;
class CashierGUI
class STATE // Cashier states
public static final int PROCESS = 0;
public static final int CHECKED = 1;
class NAME // Names of buttons
public static final String CHECK = "Check";
public static final String BUY = "Buy";
public static final String CANCEL = "Cancel";
public static final String BOUGHT = "Bought";
private static final int H = 300; // Height of window pixels
private static final int W = 400; // Width of window pixels
private JLabel theAction = new JLabel();
private JTextField theInput = new JTextField();
private JTextArea theOutput = new JTextArea();
private JScrollPane theSP = new JScrollPane();
private JButton theBtCheck = new JButton( NAME.CHECK );
private JButton theBtBuy = new JButton( NAME.BUY );
private JButton theBtCancel= new JButton( NAME.CANCEL );
private JButton theBtBought= new JButton( NAME.BOUGHT );
private int theState = STATE.PROCESS; // Current state
private Product theProduct = null; // Current product
private BoughtList theBought = null; // Bought items
private Transaction theCB = new Transaction();
private StockReadWriter theStock = null;
private OrderProcessing theOrder = null;
private NumberFormat theMoney =
NumberFormat.getCurrencyInstance( Locale.UK );
public CashierGUI( RootPaneContainer rpc, MiddleFactory mf )
try //
theStock = mf.getNewStockReadWriter(); // DataBase access
theOrder = mf.getNewOrderProcessing(); // Process order
} catch ( Exception e )
System.out.println("Exception: " + e.getMessage() );
Container cp = rpc.getContentPane(); // Content Pane
Container rootWindow = (Container) rpc; // Root Window
cp.setLayout(null); // No layout manager
rootWindow.setSize( W, H ); // Size of Window
Font f = new Font("Monospaced",Font.PLAIN,12); // Font f is
theBtCheck.setBounds( 16, 25+60*0, 80, 40 ); // Check Button
theBtCheck.addActionListener( theCB ); // Listener
cp.add( theBtCheck ); // Add to canvas
theBtBuy.setBounds( 16, 25+60*1, 80, 40 ); // Buy button
theBtBuy.addActionListener( theCB ); // Listener
cp.add( theBtBuy ); // Add to canvas
theBtCancel.setBounds( 16, 25+60*2, 80, 40 ); // Cancel Button
theBtCancel.addActionListener( theCB ); // Listener
cp.add( theBtCancel ); // Add to canvas
theBtBought.setBounds( 16, 25+60*3, 80, 40 ); // Clear Button
theBtBought.addActionListener( theCB ); // Listener
cp.add( theBtBought ); // Add to canvas
theAction.setBounds( 110, 25 , 270, 20 ); // Message area
theAction.setText( "" ); // Blank
cp.add( theAction ); // Add to canvas
theInput.setBounds( 110, 50, 270, 40 ); // Input Area
theInput.setText(""); // Blank
cp.add( theInput ); // Add to canvas
theSP.setBounds( 110, 100, 270, 160 ); // Scrolling pane
theOutput.setText( "" ); // Blank
theOutput.setFont( f ); // Uses font
cp.add( theSP ); // Add to canvas
theSP.getViewport().add( theOutput ); // In TextArea
rootWindow.setVisible( true ); // Make visible
class Transaction implements ActionListener // Listener
public void actionPerformed( ActionEvent ae ) // Interaction
if ( theStock == null )
theAction.setText("No conection");
return; // No connection
String actionIs = ae.getActionCommand(); // Button
try
if ( theBought == null )
int on = theOrder.uniqueNumber(); // Unique order no.
theBought = new BoughtList( on ); // Bought list
if ( actionIs.equals( NAME.CHECK ) ) // Button CHECK
theState = STATE.PROCESS; // State process
String pn = theInput.getText().trim(); // Product no.
int amount = 1; // & quantity
if ( theStock.exists( pn ) ) // Stock Exists?
{ // T
Product pr = theStock.getDetails(pn); // Get details
if ( pr.getQuantity() >= amount ) // In stock?
{ // T
theAction.setText( // Display
pr.getDescription() + " : " + // description
theMoney.format(pr.getPrice()) + // price
" (" + pr.getQuantity() + ")" // quantity
); // of product
theProduct = pr; // Remember prod.
theProduct.setQuantity( amount ); // & quantity
theState = STATE.CHECKED; // OK await BUY
} else { // F
theAction.setText( // Not in Stock
pr.getDescription() +" not in stock"
} else { // F Stock exists
theAction.setText( // Unknown
"Unknown product number " + pn // product no.
if ( actionIs.equals( NAME.BUY ) ) // Button BUY
if ( theState != STATE.CHECKED ) // Not checked
{ // with customer
theAction.setText("Check if OK with customer first");
return;
boolean stockBought = // Buy
theStock.buyStock( // however
theProduct.getProductNo(), // may fail
theProduct.getQuantity() ); //
if ( stockBought ) // Stock bought
{ // T
theBought.add( theProduct ); // Add to bought
theOutput.setText( "" ); // clear
theOutput.append( theBought.details()); // Display
theAction.setText("Purchased " + // details
theProduct.getDescription()); //
// theInput.setText( "" );
} else { // F
theAction.setText("!!! Not in stock"); // Now no stock
theState = STATE.PROCESS; // All Done
if ( actionIs.equals( NAME.CANCEL ) ) // Button CANCEL
if ( theBought.number() >= 1 ) // item to cancel
{ // T
Product dt = theBought.remove(); // Remove from list
theStock.addStock( dt.getProductNo(), // Re-stock
dt.getQuantity() ); // as not sold
theAction.setText(""); //
theOutput.setText(theBought.details()); // display sales
} else { // F
theOutput.setText( "" ); // Clear
theState = STATE.PROCESS;
if ( actionIs.equals( NAME.BOUGHT ) ) // Button Bought
if ( theBought.number() >= 1 ) // items > 1
{ // T
theOrder.newOrder( theBought ); // Process order
theBought = null; // reset
theOutput.setText( "" ); // Clear
theInput.setText( "" ); //
theAction.setText( "Next customer" ); // New Customer
theState = STATE.PROCESS; // All Done
theInput.requestFocus(); // theInput has Focus
catch ( StockException e ) // Error
{ // Of course
theOutput.append( "Fail Stock access:" + // Should not
e.getMessage() + "\n" ); // happen
catch ( OrderException e ) // Error
{ // Of course
theOutput.append( "Fail Order process:" + // Should not
e.getMessage() + "\n" ); // happen
}(disclaimer: I did not read through your Swing code, as I find that painful)
My question is how do I access a private arraylist from a different class in the same
package?Provide a public accessor method (getMyPrivateArrayList()) -
Help Please ... with calling functions inside listener events
I need the window to update itself before another method inside my listener is called. When I make the call to updateUI() it preforms it's function once my listener event is compelete while I would like to to happend.
paw.updateHasMoved();
temp.updateUI();// -->Want the update to occure before the next line is called
piece.CB.board = ComputersMove(piece.CB.board);okidoi Mr Helpy!
let me try with this
just one more question, the button should be created at
runtime or inside my
movieclip?
Regards
Rick
"Mr Helpy mcHelpson" <[email protected]>
escribió en el mensaje
news:f46tjk$lg1$[email protected]..
> flooring.onLoad = function(success) {
> if (flooring.firstChild.hasChildNodes()) {
>
> you can just do
>
> flooring.onLoad = function(success) {
> if (success) {
>
> you'll need to create a button on top of your image.
This for me is most
> easily done with a predefined custom class, and on the
instantiation of
> your
> image(movieclip) you can define the button actions
contained in the movie
> clip.
>
> make sense?
>
> HmcH
> -
How to Call action Listener from Mouse Listener event
One class (class 1)implements mouse listener and responds to a mouse events.
As part of that response it needs to call a variable set method in another class (class 2)and also have that setMethod call it's own ActionPerformed.
Seems the problem is I don't have aaction event to pass
I only have a mouse event. As follows:
class 1
public void mousePressed(MouseEvent e) {
int y1=Math.abs(e.getY()-y);
this.sourceReference.setVar(y1);
repaint();
class 2
int var;
public void setVar(int y)
var=y;
this.ActionPerformed(?? ); //This is what I want to do
Same question slightly different.
From class 1 I scould first call the setVar method
and then issue a call to class 2's ActionPerformed.
But again I don't seem to have the proper action event e to pass it.
ThanksDo you need any information from an ActionEvent that you'd be calling from the MouseEvent (ie the action command, or somethig) or can you just have the actionPerformed method just call a different method that doesn't need an ActionEvent?
public void actionPerformed(ActionEvent e) {
this.doActionStuff();
public void doActionStuff() {
// does what you want the action event to do
Then from the mousePressed method you can just call the doActionStuff method.
I'm not sure if this helps or not, hope it does.
Scott -
Refer to the document class from another class?
There is a function in my document class that I need to call from inside another class. How can I call myFunction from inside OtherClass? Or refer to myVariable from inside OtherClass?
package {
import flash.display.Sprite;
public class DocumentClass extends Sprite {
public function DocumentClass():void {
_init();
private function _init():void {
var myVariable:int = 0;
function myFunction():void {
//The function I need to access
var myClass = new OtherClass();There's many ways to do it. On a case by case basis a strategy has to be chosen.
In your case, is there literally just one child class that's trying to ask the root class to run the function? Are a bunch of other classes also trying to get at this same function? Flesh out a really good description of what you want to do for a few suggestions.
For fun I'm going to assume other classes may want to call this function and at the same time be really simplistic in the approach by assuming the project is simple and bubbled events won't hurt performance. It doesn't sound like this is a particle situation.. In that case I'd send a simple bubbled event Main can read.
e.g.:
Main:
package
import flash.display.Sprite;
import flash.events.Event;
public class Main extends Sprite
private var _a:Sprite;
public function Main():void
addEventListener(Event.ENTER_FRAME, onEF);
// Called from BClass after added to stage (for event to propagate)
public function SomeFunction():void
// now that this is called, do what you want..
// I'm just going to remove _a (for no special reason)
trace("Main.SomeFunction() - called, removing _a (_b will GC eventually as well)");
removeChild(_a);
_a.removeEventListener("OMGEvent", _handleOMGF);
_a = null;
private function onEF(e:Event):void
removeEventListener(Event.ENTER_FRAME, onEF);
trace("Main.onEF() - Instantiating AClass");
// instantiate a new child, which also will load a child
_a = new AClass();
// listen for events bubbling
_a.addEventListener("OMGEvent", _handleOMGF);
// add to stage
addChild(_a);
// listen to _a to invoke function
private function _handleOMGF(e:Event):void
trace("Main._handleOMGF() - child sent OMG to Main, running Main.SomeFunction()");
SomeFunction();
AClass:
package
import flash.display.Sprite;
import flash.events.Event;
public class AClass extends Sprite
private var _b:BClass;
public function AClass():void
addEventListener(Event.ADDED_TO_STAGE, _onAddedF);
addEventListener(Event.REMOVED_FROM_STAGE, _onRemovedF);
private function _onAddedF(e:Event):void
removeEventListener(Event.ADDED_TO_STAGE, _onAddedF);
trace("AClass._onAddedF() - Instantiating BClass");
// first child on stage, load second child, which
// after it hits the stage will dispatch an event
_b = new BClass();
// we'll listen here for the event just for fun
_b.addEventListener("OMGEvent", _handleOMGF);
// trigger the ADDED_TO_STAGE
addChild(_b);
// listen to _b just for fun
private function _handleOMGF(e:Event):void
trace("AClass._handleOMGF() - Just heard OMG!");
// clean up
private function _onRemovedF(e:Event):void
removeEventListener(Event.REMOVED_FROM_STAGE, _onRemovedF);
removeChild(_b);
_b.removeEventListener("OMGEvent", _handleOMGF);
_b = null;
trace("AClass._onRemovedF() - I cleaned up");
BClass:
package
import flash.display.Sprite;
import flash.events.Event;
public class BClass extends Sprite
public function BClass():void
addEventListener(Event.ADDED_TO_STAGE, _onAddedF);
private function _onAddedF(e:Event):void
removeEventListener(Event.ADDED_TO_STAGE, _onAddedF);
trace("BClass._onAddedF() - Created, dispatching 'OMGEvent' with bubbles");
// dispatch (I extend Sprite, it supports events)
// Note: I set bubbles to true to bubble back to Main (default is false)
dispatchEvent(new Event("OMGEvent", true));
For ease, Example Source (saved down to CS5).
All parents of that child will receive the dispatched event. To use that tactic you'd need to be sure your event is unique (hence using 'OMGEvent') and not have a fiercly complex display list because all those parents of this child will receive this event as well. I find in 99% of the non-particle usage of this, it really just doesn't matter. It's quick and simple.
If you wanted to really direct it rather than bubble, you'd just remove the 'true' parameter from the dispatchEvent() and then each parent of that child would need to be told to listen for the event so it can keep relaying it up the display chain.
I do the latter quite often when a child affects the display of each parent in some way all the way up the display list, capturing custom events at each level, doing what's necessary.
Trace:
Main.onEF() - Instantiating AClass
AClass._onAddedF() - Instantiating BClass
BClass._onAddedF() - Created, dispatching 'OMGEvent' with bubbles
AClass._handleOMGF() - Just heard OMG!
Main._handleOMGF() - child sent OMG to Main, running Main.SomeFunction()
Main.SomeFunction() - called, removing _a (which marks _b for cleanup as well)
AClass._onRemovedF() - I cleaned up
Man, Adobe really needs to get a <pre lang="as3"> with some color coding/formatting.
Maybe you are looking for
-
Hi All, Operating System: Windows 2008 R2 Enterprise SP1 H/w: VMware virtual machine vmx 09 Installed: File server role with "Services for network file system" Server for NFS and Client for NFS services and up and running. But when I try to cre
-
2011 Macbook Pro Hard Drive Upgrade?
Hi. I am looking at upgrading my 2011 Macbook Pro hard drive. I want to get a 7200 RPM hard drive. I have been looking on Newegg and doing some research, and from what I can tell, the 2011 Macbook Pro uses a 3.0GB/s interface. If I were to buy a hard
-
I own a Photosmart Premiyn c309g it's a touchscreen-well it's supposed to be! Quite often I can't get it to touch on; which means I can't access the menu and thus can't copy or scan. Also, the on/off button has never worked. Not sure if any of t
-
Windows vs. Mac Download
I purchased Adobe Elements 12 download for Windows platform. If I also want to install on my Mac, will I need to purchase a separate $80 download for Mac platform?
-
I cannot install Contribute 4 on Windows 7
I have recently upgraded my Windows computer from XP to Windows 7 and get the following message when trying to install Contribute 4 "The wizard was interrupted before Adobe Contribute 4 could be completely installed" Does anyone have any suggestions