Moving ActionListener code to another class
Hi, I got a simple GUI program like the following:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GUI extends JFrame implements ActionListener
private JLabel oneLabel;
private JButton hitButton;
public GUI()
Container c = this.getContentPane();
c.setLayout(new FlowLayout());
setLocation(200,20);
oneLabel = new JLabel("");
hitButton = new JButton("Hit Me");
JPanel mainPanel = new JPanel(new GridLayout(2,1));
mainPanel.add(oneLabel);
mainPanel.add(hitButton);
c.add(mainPanel);
this.setSize(100,100);
setVisible(true);
// Action Listeners
hitButton.addActionListener(this);
public void actionPerformed(ActionEvent event)
try
if (event.getSource() == hitButton)
oneLabel.setText("You hit me");
catch(Exception e)
e.printStackTrace();
Then I got a main class that is used to access the GUI class posted above:
public class Main
public static void main (String[]args)
try
GUI G = new GUI();
catch(Exception evt)
evt.printStackTrace();
What I am trying to do is move the whole actionPerformed method from the GUI class to the Main class and make it work as it was in the GUI class so that the GUI class is only responsible for generating the visual interface. Also do I need to place the addActionListener to the Main class as well? Can anyone tell me how to proceed with this?
Thanks for your inputs.
I have tried editing the Main class like:
import javax.swing.*;
import java.awt.*;
public class Main implements ActionListener <----
COMPILING ERROR
public static void main (String[]args)
try
GUI G = new GUI();
catch(Exception evt)
evt.printStackTrace();
hitButton.addActionListener(G);
public void actionPerformed(ActionEvent event)
try
if (event.getSource() == hitButton)
oneLabel.setText("You hit me");
catch(Exception e)
e.printStackTrace();
It gives me a cannot find symbol error however.
Please, I need to get this done by tonight.If you want ro Refer to G outside the try-block, you have to declare it out side
GUI G = null;
try{
G = new GUI();
catch(Exception evt)
evt.printStackTrace();
if (G != null)
hitButton.addActionListener(G);You should read the turorial about visibilty and some other chapters.
http://java.sun.com/docs/books/tutorial/reallybigindex.html
Greetings Michael
Similar Messages
-
Painting in Applets using another class
hi all
I am trying the simplest of codes, using another class which paints something on the client area.
when I run it it does draw it on the screen but then disappears or is covered. ne suggestions or reasons why this might be happening...
the code is as follows
package test;
import java.awt.*;
import javax.swing.*;
import java.awt.Graphics2D.*;
import java.awt.geom.*;
public class TestApp1 extends JApplet {
private Container container;
public Rectangle rect;
public CTest test1;
public Graphics g;
public void init()
container=getContentPane();
g=container.getGraphics();
Graphics2D g2=(Graphics2D)g;
test1=new CTest(false,g2);
public void run()
container.add(test1);
public void stop()
public void destroy()
package test;
import javax.swing.*;
import java.awt.Graphics;
import java.awt.*;
public class CTest extends JPanel {
protected
Graphics2D m_graphics;
Rectangle m_PlotRect;
public
CTest(boolean resizable,Graphics2D g)
m_graphics =g;
m_PlotRect=new Rectangle(150,50,50,50);
void DrawAxis()
m_graphics.setBackground(Color.white);
m_graphics.setColor(Color.black);
m_graphics.drawRect(
(int)m_PlotRect.getMinX(),
(int)m_PlotRect.getMinY(),
(int)m_PlotRect.getWidth(),
(int)m_PlotRect.getHeight()
public void paint(Graphics g)
super.paint(g);
DrawAxis();
public void paintComponent(Graphics g)
super.paintComponent(g);
DrawAxis();thanx guys
i could solve the problem. thought its good to share it with every one in case some one else falls for the same trap.
what i did was tried to pass the Graphics object to my CTest class and then painted everything on the basis of that.
this is where the code gets freaky.
the correct way of doing it is not passing the graphics object to the CTest class but use the graphics object passed by the system to the paintcomponent function to do all the painting in the class.
I did that and it works well.
cheers
Deepak -
Compiling a class from another class
is it possible to compile a class from the code in another class?
i.e I want to check whether code in a .java file will compile before I use it.
Is there any methods that I could use to do this and could anyone give me advice on HOW to use the methods suggested?
thanks in advance
davidi was looking at that but it seems to only run files, not commands
is there a way to use it with command.com or cmd.exe or something to send commands to it?
also if i used a readline on an inputstream it only returned the first line (i tried running a batch file so the only line it returned was ..> javac testscript.java but i spose if i put
@echo off
javac testscript.java
if exist testscript.class (
echo compiled correctly
) else (
echo compiled incorectly
so the first line returned would either be "compiled correctly" or the compile error, but this would be compiling it to see if it compiles so im not sure if this answers the first question anyway =p -
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? -
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 -
Can't add list element when calling a method from another class
I am trying to call a method in another class, which contains code listmodel.addElement("text"); to add an element into a list component made in that class.
I've put in System.out.println("passed"); in the method just to make sure if the method was being called properly and it displays normally.
I can change variables in the other class by calling the method with no problem. The only thing I can't do is get listmodel.addElement("text"); to add a new element in the list component by doing it this way.
I've called that method within it's class and it added the element with no problem. Does Java have limitations about what kind of code it can run from other classes? And if that's the case I'd really like to know just why.There were no errors, just the element doesnt get added to the list by doing it this way
class showpanel extends JPanel implements ActionListener, MouseMotionListener {
framepanel fp = new framepanel();
--omitted--
public void actionPerformed(ActionEvent e){
if(e.getSource() == button1){
fp.addLayer();
/*is in a different class file*/
class framepanel extends JPanel implements ActionListener{
--omitted--
public void addLayer(){
listmodel.addElement("Layer"+numLayer);
numLayer++;
} -
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 -
Value from JDialog to another class
Hi:
I have a trouble with getting my values from a JDialog box to another class.
Here's what I have:
This is an ftp application. I have a main frame where if the user selects File->New Connection
it pops up a Connect dialog box. The connect dialog box has various fields such as profile name, host address, user name, and so on. In addition, there are three buttons, Add, Connect and Cancel.
After the user types info and clicks Connect, all these information should be sent to the main frame from where it would send the information to another class which would connect to the ftp server.
I have a class called Profile which is used to wrap these information to be sent to the main frame.
Now, how can i get this info to the main frame? Here's the code in main frame:
class MainFrame extends JFrame {
JMenuItem newconnection = new JMenuItem("New Connection", 'N');
newconnection.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Profile p = new Profile();
ConnectDialog con = new ConnectDialog();
p = con.getProfile();
makeNewConnection(p); //this is the method i use to make a new connection
The problem is that by the time i get to the line p = con.getProfile(),
con object no longer exists.
Should i use threads or should i just send the main frame as the parameter to create the Connect dialog. If i use threads, how should i code it, and if i use main frame as the parent frame for connect dialog, how do i get the info to main frame. Please help. Here's the code for ConnectDialog. Also, please advice if ConnectDialog code can be improved since i am new to swing. Thanks for helping a needy student.
public class ConnectDialog extends JDialog{
private MainFrame parent;
private String defaultDownloadPath;
private static Profile currProfile;
private JList profileList;
private JPanel listPanel;
private JPanel infoPanel;
private JPanel labelPanel;
private JPanel buttonPanel;
private JPanel arrangedComponents;
private Vector data;
private JLabel ProfileName;
private JLabel HostAddress;
private JLabel Account;
private JLabel PortNo;
private JLabel login;
private JLabel password;
private JLabel DownLoadPath;
private JButton addButton;
private JButton cancelButton;
private JButton connectButton;
private JButton browseButton;
private JButton clearButton;
private JLabel Anonymous;
private JCheckBox anonymous;
private JTextField profileName;
private JTextField hostAddress;
private JTextField account;
private JTextField portNo;
private JTextField loginName;
private JTextField passwd;
private JTextField downloadPath;
private final int textSize = 20;
private final int fontSize = 12;
private Container cp;
public ConnectDialog(MainFrame main) {
super(main, true);
parent = main;
data = new Vector();
currProfile = new Profile();
profileList = new JList(data);
listPanel = new JPanel();
labelPanel = new JPanel();
infoPanel = new JPanel();
buttonPanel = new JPanel();
arrangedComponents = new JPanel();
ProfileName = new JLabel("Profile Name:");
ProfileName.setForeground(Color.black);
HostAddress = new JLabel("Host Address:");
HostAddress.setForeground(Color.black);
Account = new JLabel("Account:");
Account.setForeground(Color.black);
PortNo = new JLabel("Port:");
PortNo.setForeground(Color.black);
login = new JLabel("Login:");
login.setForeground(Color.black);
password = new JLabel("Password:");
password.setForeground(Color.black);
DownLoadPath = new JLabel("Download Path:");
DownLoadPath.setForeground(Color.black);
addButton = new JButton("Add");
addButton.setMnemonic('A');
addButton.setForeground(Color.black);
cancelButton = new JButton("Cancel");
cancelButton.setForeground(Color.black);
clearButton = new JButton("Clear");
clearButton.setForeground(Color.black);
connectButton = new JButton("Connect");
connectButton.setForeground(Color.black);
connectButton.setMnemonic('C');
browseButton = new JButton("Browse");
browseButton.setForeground(Color.black);
browseButton.setMnemonic('B');
Anonymous = new JLabel("Anonymous: ");
Anonymous.setForeground(Color.black);
anonymous = new JCheckBox();
profileName = new JTextField(textSize);
profileName.setText("");
profileName.setBorder(BorderFactory.createLoweredBevelBorder());
profileName.setBorder(BorderFactory.createLineBorder(Color.black));
profileName.setFont(new Font("Dialog",Font.PLAIN,fontSize));
hostAddress = new JTextField(textSize);
hostAddress.setText("");
hostAddress.setBorder(BorderFactory.createEtchedBorder());
hostAddress.setBorder(BorderFactory.createLineBorder(Color.black));
hostAddress.setFont(new Font("Dialog",Font.PLAIN,fontSize));
account = new JTextField(textSize);
account.setText("");
account.setBorder(BorderFactory.createLoweredBevelBorder());
account.setBorder(BorderFactory.createLineBorder(Color.black));
account.setFont(new Font("Dialog",Font.PLAIN,fontSize));
portNo = new JTextField(5);
portNo.setText("");
portNo.setText("21");
portNo.setBorder(BorderFactory.createEtchedBorder());
portNo.setBorder(BorderFactory.createLineBorder(Color.black));
portNo.setFont(new Font("Dialog",Font.PLAIN,fontSize));
loginName = new JTextField(textSize);
loginName.setText("");
loginName.setBorder(BorderFactory.createEtchedBorder());
loginName.setBorder(BorderFactory.createLineBorder(Color.black));
loginName.setFont(new Font("Dialog",Font.PLAIN,fontSize));
passwd = new JTextField(textSize);
passwd.setText("");
passwd.setBorder(BorderFactory.createEtchedBorder());
passwd.setBorder(BorderFactory.createLineBorder(Color.black));
passwd.setFont(new Font("Dialog",Font.PLAIN,fontSize));
downloadPath = new JTextField(textSize);
downloadPath.setText("");
downloadPath.setBorder(BorderFactory.createEtchedBorder());
downloadPath.setBorder(BorderFactory.createLineBorder(Color.black));
downloadPath.setFont(new Font("Dialog",Font.PLAIN,fontSize));
cp = this.getContentPane();
this.setBounds(200,200,600,300);
this.setResizable(false);
cp.setLayout(new BorderLayout());
setListPanel();
setLabelPanel();
setButtonPanel();
setActionListeners();
this.setBackground(Color.lightGray);
this.setVisible(true);
this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
public String getDefaultDownloadPath() {
return defaultDownloadPath;
// public Profile getProfile() {
// try {
// this.wait();
// } catch (Exception e) {}
// return currProfile;
public void setListPanel() {
profileList.setFont(new Font("Dialog", Font.PLAIN, 12));
profileList.setBackground(Color.white);
profileList.setForeground(Color.black);
profileList.setPrototypeCellValue("MMMMMMMMM");
listPanel.setPreferredSize(profileList.getPreferredScrollableViewportSize());
listPanel.setBorder(BorderFactory.createEtchedBorder());
listPanel.setBorder(BorderFactory.createLineBorder(Color.black));
listPanel.setBackground(Color.white);
listPanel.add(profileList);
cp.add(listPanel, "West");
public void setLabelPanel() {
arrangedComponents = new JPanel();
arrangedComponents.setLayout(new BorderLayout());
labelPanel = new JPanel();
labelPanel.setLayout(new BoxLayout(labelPanel, BoxLayout.Y_AXIS));
labelPanel.setAlignmentX(JPanel.LEFT_ALIGNMENT);
JPanel row1 = new JPanel();
row1.add(ProfileName);
labelPanel.add(row1);
JPanel row2 = new JPanel();
row2.add(HostAddress);
labelPanel.add(row2);
JPanel row3 = new JPanel();
row3.add(Account);
labelPanel.add(row3);
JPanel row4 = new JPanel();
row4.add(PortNo);
labelPanel.add(row4);
JPanel row5 = new JPanel();
row5.add(login);
labelPanel.add(row5);
JPanel row6 = new JPanel();
row6.add(password);
labelPanel.add(row6);
JPanel row7 = new JPanel();
row7.add(DownLoadPath);
labelPanel.add(row7);
infoPanel.setLayout(new BoxLayout(infoPanel,BoxLayout.Y_AXIS));
infoPanel.setAlignmentX(JPanel.LEFT_ALIGNMENT);
row1 = new JPanel();
row1.add(profileName);
row1.add(profileName);
infoPanel.add(row1);
row2 = new JPanel();
row2.add(hostAddress);
row2.add(hostAddress);
infoPanel.add(row2);
row3 = new JPanel();
row3.add(account);
infoPanel.add(row3);
row4 = new JPanel();
row4.setLayout(new FlowLayout());
row4.add(portNo);
row4.add(Box.createHorizontalStrut(57));
row4.add(Anonymous);
row4.add(anonymous);
infoPanel.add(row4);
row5 = new JPanel();
row5.add(loginName);
infoPanel.add(row5);
row6 = new JPanel();
row6.add(passwd);
infoPanel.add(row6);
row7 = new JPanel();
row7.setLayout(new FlowLayout());
row7.add(downloadPath);
row7.add(browseButton);
infoPanel.add(row7);
arrangedComponents.add(labelPanel, "West");
arrangedComponents.add(infoPanel, "Center");
cp.add(arrangedComponents, "Center");
public void setButtonPanel() {
buttonPanel.setLayout(new FlowLayout());
buttonPanel.add(addButton);
buttonPanel.add(connectButton);
buttonPanel.add(cancelButton);
buttonPanel.add(clearButton);
cp.add(buttonPanel, "South");
public void setActionListeners() {
anonymous.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(anonymous.isSelected()) {
loginName.setText("anonymous");
passwd.setText("your email here");
else {
loginName.setText("");
passwd.setText("");
addButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(profileName.getText() != "" && !data.contains(profileName.getText())){
data.add(profileName.getText());
profileList.setListData(data);
connectButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
connectButtonPressed();
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JButton b = (JButton) e.getSource();
ConnectDialog c = (ConnectDialog) b.getTopLevelAncestor();
c.dispose();
clearButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
profileName.setText("");
hostAddress.setText("");
account.setText("");
portNo.setText("");
loginName.setText("");
passwd.setText("");
downloadPath.setText("");
browseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFrame browseFrame = new JFrame("browse for folder");
browseFrame.setBounds(230,230,200,200);
JDirectoryChooser fileChooser = new JDirectoryChooser();
fileChooser.setFileSelectionMode(JDirectoryChooser.DIRECTORIES_ONLY);
int option = fileChooser.showDialog(browseFrame);
if(option==JFileChooser.APPROVE_OPTION) {
File f = fileChooser.getSelectedFile();
defaultDownloadPath = f.getAbsolutePath();
downloadPath.setText(defaultDownloadPath);
public void connectButtonPressed() {
if(!profileName.getText().equals("") && !hostAddress.getText().equals("") &&
!loginName.getText().equals("") && !passwd.getText().equals("")) {
currProfile.setProfileName(profileName.getText());
currProfile.setHostAddress(hostAddress.getText());
currProfile.setAcct(account.getText());
currProfile.setUserName(loginName.getText());
currProfile.setPassword(passwd.getText());
currProfile.setDownloadPath(downloadPath.getText());
parent.setProfile(currProfile);
this.dispose();
else {
JFrame f = new JFrame("Error!");
JOptionPane.showMessageDialog(f, "Some fields empty!", "", JOptionPane.ERROR_MESSAGE);
}If the dialog is modal then you can just call show and wait for it to close by the user, then grab the info:
ConnectDialog dialog = new ConnectDialog();
dialog .show();
Profile profile = con.getProfile();
makeNewConnection( profile ); -
How to add objects to panel in one class from another class
Hi this is what i am trying to do. I have a drag and adrop tool working where the users and select objects on a small panel and drag them to another panel called the tpan. What i want to do is create another class, which creates objects and now i want to display these objects on the tpan. So say i have a class DisplayTpan(), this class is used to display the objects which have been dragged from the small panel, and objects on this panel have mouselisteners attached, so that these objects can be moved around on the tpan. I have created another class called creatObj(), and from this class i want to add objects to the tpan. The DisplayTpan class extends a Jpanel, would this be he case for the CreateObj() class? In the CreateClass i have made a call to DisplayTpan t = new DisplayTPan();
t.add(object);
But this does not add the object to the panel, any ideas on how it should be done?
Problem number two i have is say, I have two objects created on that oanel, i now want to draw a line t connect the two objects, this is just simply a call to the drawLine function but how would it be possible to add a ,mouselistener to that line, so it can be extended moved around etc? Any help much appreciated thanks.Try to convert the PL/SQL code from Forms trigger into a PL/SQL library(.PLL),
and then attach that PLL in your forms.
Note that all Forms objects should be referenced indirectly, for example,
you have to rewrite
:B1.DEPT_CODE := :B2.DEPT_CODE;
:B3.TOTAL_AMOUNT := 100;
==>
copy('B2.DEPT_NO','B1.DEPT_NO');
copy('100','B3.TOTAL_AMOUNT');
This is the best way to share PL/SQL code among Oracle Forms. -
How to add objects to panel from another class?
Hi this is what i am trying to do. I have a drag and adrop tool working where the users and select objects on a small panel and drag them to another panel called the tpan. What i want to do is create another class, which creates objects and now i want to display these objects on the tpan. So say i have a class DisplayTpan(), this class is used to display the objects which have been dragged from the small panel, and objects on this panel have mouselisteners attached, so that these objects can be moved around on the tpan. I have created another class called creatObj(), and from this class i want to add objects to the tpan. The DisplayTpan class extends a Jpanel, would this be he case for the CreateObj() class? In the CreateClass i have made a call to DisplayTpan t = new DisplayTPan();
t.add(object);
But this does not add the object to the panel, any ideas on how it should be done?
Problem number two i have is say, I have two objects created on that oanel, i now want to draw a line t connect the two objects, this is just simply a call to the drawLine function but how would it be possible to add a ,mouselistener to that line, so it can be extended moved around etc? Any help much appreciated thanks.As for your first problem...too confusing...too tired...mb tomorrow it will make sense :)
Fer the second...no need to add a mouse listener to each line. There are a couple options that spring to mind, the easiest I can think of is just check to see if the mouse click intersects with any of the lines (bit of geometry).
The second, ugly but a hella allot more accurate and better (me thinks), is to create a bounding box around the line, so the user doesn't have to click right right on the line. I created this bounding box by painting the pixels with a special key to correspond to that line. The other nice thing about this key is the fact that the lookup is quick.
The first step was the create a array of integers the size of the surface. Whenever a line is drawn on the graphical surface, do a corresponding line in the integer array, and create the bounding box inside this invisible array. Now whenever the user clicks just do a lookup into this array and check to see which line was selected...then go to town.
If you want a more detailed explination, i'll post some code later. -
Moving Scriptlet Code to backing bean when converting from JSP - Facelets
Hello!
We are converting our application from jsf1.2 to 2.0 and all jsps are being converted to XHTML. Some are trivial while others had very complex scriptlets.
I would like to know what are some of the recommended ways of moving Scriptlet Code to backing bean when converting from JSP -> Facelets.
I have thought about listeners, actionListeners, putting code getXXXX() of the backing bean and then calling #{bean.XXXX} but not sure whats the best way.
I do appreciate the response!
Eg of a jsp page:
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<%@ taglib uri="/WEB-INF/xxx-jsf.tld" prefix="l" %>
<%@ taglib uri="/WEB-INF/yyy-pp.tld" prefix="p" %>
<%@ page import="com.ttyy.search.beans.jsf.AdvancedSearchFormManagedBean" %>
<%@ page import="com.kkee.util.*"%>
<%
AdvancedSearchFormManagedBean advancedSearchFormManagedBean = (AdvancedSearchFormManagedBean) request.getSession().getAttribute("AdvancedSearchFormManagedBean");
if (advancedSearchFormManagedBean == null) {
advancedSearchFormManagedBean = new AdvancedSearchFormManagedBean();
request.getSession().setAttribute("AdvancedSearchFormManagedBean", advancedSearchFormManagedBean);
advancedSearchFormManagedBean.initializeForAdvancedSearchOptions();
advancedSearchFormManagedBean.setQuickSearch();
request.setAttribute("portletHeader", "Hello " + advancedSearchFormManagedBean.getPerson().getFirstname() + ", check out the latest programs in your practice areas and jurisdictions");
%>
<h:form id="MYCenterForm">
<p:portletRenderer portletSetName="test of portlet"
portletContainer="#{PortletContainerManagedBean}"
id="MYCenter"
portletScope = "TEST_SCOPE"
suppressIfNoData="true"
portletSkinName="SOME_SKIN">
<f:facet name="persistenceToolkit">
<h:commandLink id="persistenceToolkitLink"
actionListener="#{PortletContainerManagedBean.persistPortletSetStateListener}">
<h:outputText value="Save State Of Portlet Set" id="persistenceToolkitLinkText"/>
</h:commandLink>
</f:facet>
</p:pagePortletSetRenderer>
</h:form>
<%
String flag = PropertyItems.getInstance().getPropertyItem("response.time.flag");
if("1".equals(flag)){
ResponseTime rt = (ResponseTime) session.getAttribute("responseTime");
if(rt!=null){
rt.setDesc("my cle loaded");
long now = System.currentTimeMillis();
long start = rt.getStart() + rt.getTotal();
rt.setInterval(now-start);
rt.setTotal(rt.getTotal()+rt.getInterval());
LogUtil.log(rt.toString(), LogUtil.DEBUG_LEVEL);
session.setAttribute("responseTime", rt);
%>That helps.
This could be another topic question but itst kind of related to what i am doing right now. while converting JSP to facelet (in jsf2) I came across another issue.
<h:commandLink id="Save" rendered="#{RegistrationBean.isNOTInOrigionalRegistrationMode}" action="#{RegistrationBean.updateProfile2Submit}" styleClass="#{portalSkinManagedBean.contentPortletSkin.strongTextStyle}">
<l:htmlSkinnedImage id="SaveImage" style="border:0;" url="save.gif" alt="Save Information"/>
</h:commandLink>When I click on the generated link, I get this. And this is happening for all the h:commandLink in the application.
http://localhost:9080/registration/updateProfile2.jsf[request.getQueryString()=null][request.getRequestedSessionId()=F1CCE237DD81D301F1C4DBA6910FFD8A][request.isRequestedSessionIdFromCookie()=true][request.isRequestedSessionIdFromURL()=false][request.isRequestedSessionIdValid()=true]Parameters:[rolePracticeAreasForm:title=rolePracticeAreasForm:primaryPracticeArea=10002javax.faces.ViewState=-2943345291093118815:-4400303399130292206rolePracticeAreasForm:practiceAreasMod2=10148.1rolePracticeAreasForm:practiceAreasMod1=10002.1rolePracticeAreasForm:Save=rolePracticeAreasForm:SaverolePracticeAreasForm=rolePracticeAreasFormrolePracticeAreasForm:otherField=rolePracticeAreasForm:fromMyAccount=1]||
javax.servlet.ServletException: Index: 0, Size: 0
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:325)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at com.legaledcenter.util.urlrewrite.UrlRewriteFilter.doFilter(UrlRewriteFilter.java:250)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.orm.hibernate3.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:198)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:75)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at com.jscape.framework.galileo.support.upload.UploadFilter.doFilter(UploadFilter.java:71)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:849)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:454)
at java.lang.Thread.run(Thread.java:619)
Caused by: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.RangeCheck(ArrayList.java:547)
at java.util.ArrayList.get(ArrayList.java:322)
at javax.faces.component.AttachedObjectListHolder.restoreState(AttachedObjectListHolder.java:161)
at javax.faces.component.UIComponentBase.restoreState(UIComponentBase.java:1427)
at com.sun.faces.application.view.StateHolderSaver.restore(StateHolderSaver.java:121)
at com.sun.faces.application.view.StateManagementStrategyImpl$4.invokeContextCallback(StateManagementStrategyImpl.java:289)
at javax.faces.component.UIComponent.invokeOnComponent(UIComponent.java:1253)
at javax.faces.component.UIComponentBase.invokeOnComponent(UIComponentBase.java:672)
at javax.faces.component.UIComponent.invokeOnComponent(UIComponent.java:1262)
at javax.faces.component.UIComponentBase.invokeOnComponent(UIComponentBase.java:672)
at javax.faces.component.UIComponent.invokeOnComponent(UIComponent.java:1262)
at javax.faces.component.UIComponentBase.invokeOnComponent(UIComponentBase.java:672)
at javax.faces.component.UIComponent.invokeOnComponent(UIComponent.java:1262)
at javax.faces.component.UIComponentBase.invokeOnComponent(UIComponentBase.java:672)
at javax.faces.component.UIComponent.invokeOnComponent(UIComponent.java:1262)
at javax.faces.component.UIComponentBase.invokeOnComponent(UIComponentBase.java:672)
at com.sun.faces.application.view.StateManagementStrategyImpl.restoreView(StateManagementStrategyImpl.java:284)
at com.sun.faces.application.StateManagerImpl.restoreView(StateManagerImpl.java:177)
at com.sun.faces.application.view.ViewHandlingStrategy.restoreView(ViewHandlingStrategy.java:119)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.restoreView(FaceletViewHandlingStrategy.java:434)
at com.sun.faces.application.view.MultiViewHandler.restoreView(MultiViewHandler.java:143)
at com.sun.faces.lifecycle.RestoreViewPhase.execute(RestoreViewPhase.java:199)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.RestoreViewPhase.doPhase(RestoreViewPhase.java:110)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:312)
... 22 more
********** Message End *************Thanks -
Accessing Members in Another Class
How would I access a member from another class? In the actionPerformed method, I want to be able to access objects such as filemenu in the Main class. Here's most of my code:
class fileEvent implements ActionListener
{ public void actionPerformed(ActionEvent e,JMenuItem& item)
public class Main extends JFrame implements ActionListener, ItemListener {
/** Creates a new instance of Main */
public Main() {
this.setTitle("Cross-platform Map Editor");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JInternalFrame drawingframe;
JDesktopPane desk;
JPanel drawingpanel = new JPanel();
JMenuBar menubar = new JMenuBar();
JMenu filemenu = new JMenu("File");
JMenu editmenu = new JMenu("Edit");
JMenu mapmenu = new JMenu("Map");
JMenu tilesmenu = new JMenu("Tiles");
JMenu toolsmenu = new JMenu("Tools");
JMenu windowmenu = new JMenu("Window");
JMenu aboutmenu = new JMenu("Help");
JMenuItem fileItem1 = new JMenuItem("New...",KeyEvent.VK_N);
fileItem1.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.ALT_MASK));
fileItem1.addActionListener(new fileEvent(),fileItem1);
JMenuItem fileItem2 = new JMenuItem("Open...");
JMenuItem fileItem3 = new JMenuItem("Save");
JMenuItem fileItem4 = new JMenuItem("Save As...");
JMenuItem fileItem5 = new JMenuItem("Exit");
JMenuItem editItem1 = new JMenuItem("Undo");
JMenuItem editItem2 = new JMenuItem("Redo");
JMenuItem editItem3 = new JMenuItem("Cut");
JMenuItem editItem4 = new JMenuItem("Copy");
JMenuItem editItem5 = new JMenuItem("Paste");
JMenuItem editItem6 = new JMenuItem("Select All");
filemenu.add(fileItem1);
filemenu.add(fileItem2);
filemenu.add(fileItem3);
filemenu.add(fileItem4);
filemenu.add(fileItem5);
editmenu.add(editItem1);
editmenu.add(editItem2);
editItem2.add(new JSeparator());
editmenu.add(editItem3);
editmenu.add(editItem4);
editItem4.add(new JSeparator());
editmenu.add(editItem5);
menubar.add(filemenu);
menubar.add(editmenu);
menubar.add(mapmenu);
menubar.add(tilesmenu);
menubar.add(toolsmenu);
menubar.add(windowmenu);
menubar.add(aboutmenu);
this.setJMenuBar(menubar);
JButton drawingbutton1 = new JButton("Pencil");
JButton drawingbutton2 = new JButton("Line");
JButton drawingbutton3 = new JButton("Paint Pucket");
JButton drawingbutton4 = new JButton("Recntangle");
JButton drawingbutton5 = new JButton("Filled Rectangle");
drawingpanel.add(drawingbutton1);
drawingpanel.add(drawingbutton2);
drawingpanel.add(drawingbutton3);
drawingpanel.add(drawingbutton4);
drawingpanel.add(drawingbutton5);
drawingframe = new JInternalFrame("Drawing", true,true,true,true);
drawingframe.add(drawingpanel);
drawingframe.setSize(200,300);
drawingframe.setVisible(true);
desk = new JDesktopPane();
desk.add(drawingframe);
this.add(desk);
this.setSize(500,500);
this.setVisible(true);
/code]You don't want your Main class to have accessor methods or public variables... that's the worst dependency you can have.
Anyways, think in terms of objects. When one object has a reference to another object, it can access all of its public data and methods.
I'd recommend reading up on the basics:
http://java.sun.com/docs/books/tutorial/java/index.html -
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()) -
Using a class that has a main from another class
Can I call a class that has a main from another classes public methods?
Yes, you can, although strictly speaking you won't be calling that classes "main" method, you will simply be calling and initializing the class through it's constructor, the "main" method will be ignored. If you have code inside your main method that you want executed as well consider moving it inside your constructor and simply using the "main" method as an application initializer:
public static void main( String args[] ) {
new MyClass();
This way you can use your class as an application or call it from another class and not have any duplicate code inside your "main" method and constructor. You can also take this further and have it call the applet initialization so that you can launch it any way you like, I suspect this is a bit beyond what you were asking.
Does this solve your problem? -
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);
}
Maybe you are looking for
-
Hi, I have an entity object with some attributes, one of them is called "CREATED_ON", which i have specified as a history column (created on). I have specified a format type of Simple Date in my Control hint and a format of dd-MM-yyyy. I then created
-
Mail not fetching new data every 15 with 3g turned off
I had to turn 3g off in order to improve my reception and battery life. It seems to help somewhat, however I notice that the Mail application does not fetch new mail every 15 minutes like its setup to do. It works fine in 3g mode, just doesnt do it w
-
Dear Sap, we have around 53 consigment fillup deliveries which are showing the VF04 , because as the item categroy is revelent for billing in these documents. after that we chnaged setting and transpoted to production clinet. Now New Documents (con
-
I am trying to control a Tektronix 370B curve tracer using LabView via a GPIB interface. However, there are no drivers available for download for the 370B. There is one available for the 370A, but it is not compatible with the 370B and I have been un
-
Where are the proxy settings. can't access my school net.
I need to change the proxy settings to access my school net!