here is my problem in details >>>>>>>>>>>>
hi
i just posted about my problem in new to java
but it seems useless to talk without details and here i will put the details that i belive it is relevant to my problem,
i've developed a program that enables a Car dealer to buy and sell cars and if there are no entered cars ths selling part will be disabled.
So i've added acode to disable the selling part as long as no cars entered
here where the code exists :
public MyDealer()
{
//construct components
lab1 =new JLabel ("Car model:");
lab2 =new JLabel ("Engine size :");
lab3 =new JLabel ("Car colour:");
lab4 =new JLabel ("Buying price:");
lab5 =new JLabel ("Ref. number:");
lab6 =new JLabel ("Selling price:");
txtF1 =new JTextField (5);
txtF2 =new JTextField (5);
txtF3 =new JTextField (5);
txtF4 =new JTextField (5);
txtF5 =new JTextField (5);
txtF6 =new JTextField (5);
btn1 =new JButton ("Buy a car");
btn2 =new JButton ("Sell a car");
txtA =new JTextArea (5, 5);
txtA.setEditable(false);
if(txtA.getText().equals("")){
btn2.setEnabled(false);
txtF5.setVisible(false);
txtF6.setVisible(false);
}else{
btn2.setEnabled(true);
txtF5.setVisible(true);
txtF6.setVisible(true);
}
And here is the code of the action that will make else statement true and therefore the components btn2, txtF5 and txtF6 will be enabled :
ActionListener a =new ActionListener(){
publicvoid actionPerformed(ActionEvent e){
String s1 =new String(txtF1.getText()) ;// Car model field
double d1 = Double.parseDouble(txtF2.getText());//Engine size field
String s2=new String (txtF3.getText());// Car colour field
double d2 = Double.parseDouble(txtF4.getText());// Buying price field
//assigning textfields inputs to its correspondent variables
// Note that car reference number will be genereted automatically
// when we assign Car attributes , So no need to enter
aCar4sale.model =s1;
aCar4sale.engineSize = d1;
aCar4sale.color =s2;
aCar4sale.purchase =d2;
txtA.setText("car#"+aDealer.toString());
txtF1.setText("");
txtF2.setText("");
txtF3.setText("");
txtF4.setText("");
}
};
btn1.addActionListener(a);
the problem is the following code should disables : (btn2, txtF5 and txtF6) unless txtA has a text .
and when i run the program and enter data to the textfilds of Buying part and press btn1 , the component (txtA )displays a text but inspite of this btn2,txtF5 and txtF6 still disabled :
if(txtA.getText().equals("")){
btn2.setEnabled(false);
txtF5.setVisible(false);
txtF6.setVisible(false);
}else{
btn2.setEnabled(true);
txtF5.setVisible(true);
txtF6.setVisible(true);
# 1
that block of code will only execute once (in the constructor)sounds like you should be using a DocumentListener to execute the code
# 2
> that block of code will only execute once (in the
> constructor)
>
> sounds like you should be using a DocumentListener to
> execute the code
what is the difference between DoucumentListener and ActionListener so it can solve the problem ?
another Q you said the constructor block runs for one time ,soHow if else statment runs usually ? in other words where are they supposed to be written ?
# 3
an actionlistener is fired when you click a button, hit enter on a textfield etc,
basically, a specific action fires it.
your description is you want the button/s disabled if no text is entered
if(txtA.getText().equals(""))
so, as soon as text is entered (could be just the letter 'a') you want the buttons enabled.
what happens if I type in 'a' then backspace?
a document Listener listens to changes in the document, and will enable/disable
the button/s according to the condition. in the above example, when 'a' is typed
the buttons/will be enabled, but when backspace is next pressed (to return
the text to "") the button/s will be disabled
# 4
the text area ( txtA ) was dispalying a text on it ,but the buttons still disabled
# 5
> the text area ( txtA ) was dispalying a text on it ,but the buttons still disabledwell, you have a couple of choices1) wait for a mind-reader to read the thread2) post your code so we can see what you've done
# 6
Ok Here is my full code
the code expected to run a gui that enables a car dealer to" buy a car" (storing the cars entered and make them ready for next operation selling ) , And "selling a car" (since car object entered the selling price wil be added and reference number ,if the dealer want to sell a car he has to enter the referencenumber and matching selling price) if there are no car enetered the selling part wil be disabled .
package cardealer;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.Hashtable;
import java.util.Enumeration;
/**
*
Title: Used-car dealership
*
*
Description: program to maintain hash table of cars for sale to be used by
* a car dealer
*
*
Copyright: Copyright (c) 2007
*
*
Company:
*
* @author Mahdi Alfaili
* @version 1.0
*/
public class MyDealer extends JPanel
{
private JLabel lab1;
private JLabel lab2;
private JLabel lab3;
private JLabel lab4;
private JLabel lab5;
private JLabel lab6;
private JTextField txtF1;
private JTextField txtF2;
private JTextField txtF3;
private JTextField txtF4;
private JTextField txtF5;
private JTextField txtF6;
private JButton btn1;
private JButton btn2;
private JTextArea txtA;
Car4Sale aCar4sale = new Car4Sale(); //both intialized so we can
Dealer aDealer= new Dealer();//retreat with theirs classes
public MyDealer()
{
//construct components
lab1 = new JLabel ("Car model:");
lab2 = new JLabel ("Engine size :");
lab3 = new JLabel ("Car colour:");
lab4 = new JLabel ("Buying price:");
lab5 = new JLabel ("Ref. number:");
lab6 = new JLabel ("Selling price:");
txtF1 = new JTextField (5);
txtF2 = new JTextField (5);
txtF3 = new JTextField (5);
txtF4 = new JTextField (5);
txtF5 = new JTextField (5);
txtF6 = new JTextField (5);
btn1 = new JButton ("Buy a car");
btn2 = new JButton ("Sell a car");
txtA = new JTextArea (5, 5);
txtA.setEditable(false);
if(txtA.getText().equals("")){
btn2.setEnabled(false);
txtF5.setVisible(false);
txtF6.setVisible(false);
}else{
btn2.setEnabled(true);
txtF5.setVisible(true);
txtF6.setVisible(true);
}
//adjust size and set layout
setPreferredSize (new Dimension (421, 468));
setLayout (null);
//add components
add ( lab1);
add (lab2);
add (lab3);
add (lab4);
add (lab5);
add (lab6);
add (txtF1);
add (txtF2);
add (txtF3);
add (txtF4);
add (txtF5);
add (txtF6);
add (btn1);
add (btn2);
add (txtA);
//set component bounds
lab1.setBounds (0, 26, 100, 25);
lab2.setBounds (0, 66, 100, 25);
lab3.setBounds (0, 106, 100, 25);
lab4.setBounds (0, 146, 100, 25);
lab5.setBounds (200, 26, 100, 25);
lab6.setBounds (200, 66, 100, 25);
txtF1.setBounds (100, 26, 100, 25);
txtF2.setBounds (100, 66, 100, 25);
txtF3.setBounds (100, 106, 100, 25);
txtF4.setBounds (100, 146, 100, 25);
txtF5.setBounds (300, 26, 100, 25);
txtF6.setBounds (300, 66, 100, 25);
btn1.setBounds (20, 191, 100, 25);
btn2.setBounds (223, 191, 100, 25);
txtA.setBounds (21, 243, 380, 200);
ActionListener a = new ActionListener(){
public void actionPerformed(ActionEvent e){
String s1 = new String(txtF1.getText()) ; // Car model field
double d1 = Double.parseDouble(txtF2.getText()); //Engine size field
String s2= new String (txtF3.getText()); // Car colour field
double d2 = Double.parseDouble(txtF4.getText());// Buying price field
//assigning textfields inputs to its correspondent variables
// Note that car reference number will be genereted automatically
// when we assign Car attributes , So no need to enter
aCar4sale.model =s1;
aCar4sale.engineSize = d1;
aCar4sale.color =s2;
aCar4sale.purchase =d2;
txtA.setText("car#"+aDealer.toString());
txtF1.setText("");
txtF2.setText("");
txtF3.setText("");
txtF4.setText("");
}
};
btn1.addActionListener(a);
//here is the method across GUI that enables us to see if the entered
//selling price (d3) equals aCar4Sale's selling price or not
a = new ActionListener(){
public void actionPerformed(ActionEvent e){
String s3= new String(txtF5.getText()); // Ref. number field ,Note that
// is in String type to compare it with the hashtable key aCar4sale.vrn
double d3 = Double.parseDouble(txtF6.getText());// Selling price field
aCar4sale.vrn=s3; //assigning s3 to object key so we can retrieve
//its object value by hashtable(theCarlist) to
//see wether d3 equals aCar4Sale's selling price or not
if( aCar4sale.getSelling()== d3){
aDealer.theCarList.remove(aCar4sale.vrn);
}// if they are both eqaulled the object key will be removed from
// the hashtable, so the corresponding object value
else{
JOptionPane.showMessageDialog(null,
"The price does not match","ERROR",JOptionPane.ERROR_MESSAGE);
}
}
};
btn2.addActionListener(a);
}
public static void main (String[] args)
{
JFrame frame = new JFrame ("car dealer");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new MyDealer());
frame.pack();
frame.setVisible (true);
}
}
class Dealer extends Car4Sale{
Hashtable theCarList ;
public Dealer (){
theCarList = new Hashtable() ;
}
public void addCar4Sale (Car4Sale aCar4Sale){
theCarList.put(aCar4Sale.vrn,aCar4Sale);
}
public String toString(){
Car4Sale aCAr4Sale;
String str="";
Enumeration h= theCarList.keys();
while (h.hasMoreElements()){
aCAr4Sale =(Car4Sale)theCarList.get(h.nextElement());
str += aCAr4Sale +"\n";
}
return str;
}
}
class Car {
int referenceNumber ;
double engineSize;
String model, color;
public static int carCounter ;
public Car (){
carCounter++;
referenceNumber = carCounter;
}
public Car(int r, double e, String m, String c) {
referenceNumber = r;
engineSize = e;
model = m;
color = c ;
}
public void setReferenceNumber(int r){
referenceNumber = r;
}
public void setEngineSize(double e) {
engineSize = e;
}
public void setModel(String m) {
model = m;
}
public void setColor(String c) {
color = c;
}
public int getReferenceNumber(){
return referenceNumber;
}
public double getEngineSize() {
return engineSize;
}
public String getModel() {
return model;
}
public String getColor() {
return color;
}
}
class Car4Sale extends Car {
double purchase ; double selling ;
String vrn = Integer.toString(referenceNumber);// to use it as a key in hashtable
public double getSelling(){
selling = (purchase += (purchase / 100) *15);
return selling ;
}
public String toString(){
String w =(""+(referenceNumber)+") \t Car Model"+model+
"\t engine Size"+engineSize+"\t car colour"+color+
"\t Buying price"+purchase);
return w;
}
}
Message was edited by:
scrolldown
Message was edited by:
scrolldown
# 7
You still haven't added a [url= http://java.sun.com/docs/books/tutorial/uiswing/events/documentlistener.html]DocumentListener[/url] like suggested in replies 1 and 3. Unless you do, your if statement will only get run once when you create a MyDealer, then never again.
# 8
i was just asking a bout the difference, why mydealer constructor runs once with actionlistener and run more than one time in documentlistener ?
# 9
In addition i found from the examples in the link that document listener just added to actionlistener So where to add it in my code ?
# 10
> i was just asking a bout the difference, why
> mydealer constructor runs once with actionlistener
> and run more than one time in documentlistener ?
I think you are confusing [url=http://www.ccnyddm.com/AdvJava/java_constructor_tutorial.htm]constructor[/url]s with methods.
> In addition i found from the examples in the link
> that document listener just added to actionlistener
> So where to add it in my code ?
What do you mean by "document listener just added to actionlistener"?
# 11
This is what i meant :
textField = new JTextField(20);
textField.addActionListener(new MyTextActionListener());
textField.getDocument().addDocumentListener(new MyDocumentListener());
textField.getDocument().putProperty("name", "Text Field");
textArea = new JTextArea();
textArea.getDocument().addDocumentListener(new MyDocumentListener());
textArea.getDocument().putProperty("name", "Text Area");
# 12
> This is what i meant :
>
> textField = new JTextField(20);
> textField.addActionListener(new MyTextActionListener());
> textField.getDocument().addDocumentListener(new MyDocumentListener());
> textField.getDocument().putProperty("name", "Text Field");
>
>textArea = new JTextArea();
> textArea.getDocument().addDocumentListener(new MyDocumentListener());
> textArea.getDocument().putProperty("name", "Text Area");
>
>
I believe you also are confused with the concept of [url=http://java.sun.com/docs/books/tutorial/uiswing/events/intro.html]Listeners[/url]. You can have more than one listener on the same Object, but even so, this is not the case in the code you have referenced. This adds an ActionListener to the JTextField, then adds a DocumentListener to the underlying Document for this JTextField.
In your case you don't need an ActionListener, you only need a DocumentListener.
# 13
And where is the confuse between constructor and methods in my code as you mentioned before .
# 14
Not in your code, in your mind. If you don't understand how constructors work you are not going to be able to program in Java much longer.
# 15
so the problem is that i chose a method not suitable for my purpose, am I?
# 16
Assuming you are referring to reply 12, yes. It seems to me you somehow think that the if statement inserted after your txtA is created is somehow associated with the txtA. Not only that, but you are under the impression that constructors behave like functions (which is not true). But even so, you need to add a DocumentListener to your JTextField (actually to the underlying Document), which will execute your if statement when the Document model is changed.
Here's how you should add the DocumentListener to your JTextField:txtA.getDocument().addDocumentListener(new DocumentListener() {
public void insertUpdate(DocumentEvent evt) {
// do something here
}
public void removeUpdate(DocumentEvent evt) {
// do something here
}
public void changedUpdate(DocumentEvent evt) {
// do something here
}
});
Message was edited by:
ignignokt84
# 17
here's simple demo of a document listener - type/paste anything into the textArea
and the button becomes enabled.
clear the textArea (highlight all/delete) and the button becomes disabled.
you'll have to decide if this is the behaviour you are after.
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
class Testing
{
JTextArea ta = new JTextArea(5,10);
JButton btn = new JButton("OK");
public void buildGUI()
{
btn.setEnabled(false);
JFrame f = new JFrame();
f.getContentPane().add(new JScrollPane(ta),BorderLayout.CENTER);
f.getContentPane().add(btn,BorderLayout.SOUTH);
f.pack();
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
ta.getDocument().addDocumentListener(new DocumentListener(){
public void changedUpdate(DocumentEvent e){setButtonStatus();}
public void removeUpdate(DocumentEvent e){setButtonStatus();}
public void insertUpdate(DocumentEvent e){setButtonStatus();}
});
}
public void setButtonStatus()
{
btn.setEnabled(ta.getDocument().getLength() > 0);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable(){
public void run(){
new Testing().buildGUI();
}
});
}
}
# 18
just to make sure that i am in th right way.
I think adding this code for the constructor and deleting if-else statment will solve the problem
txtA.getDocument().addDocumentListener(new DocumentListener() {
public void insertUpdate(DocumentEvent evt) {
btn2.setEnabled(true);
txtF5.setVisible(true);
txtF6.setVisible(true);
}
public void removeUpdate(DocumentEvent evt) {
btn2.setenabled(false);
txtF5.setVisible(false);
txtF6.setVisible(false);
}
};
Am i right ?
# 19
> Am i right ?
only if you want the following behaviour (test it)
type into the textArea the following letters
a
b
c
d
after you type the 'a', the button will be enabled, and visible
now hit the backspace key (so text displayed is just 'abc')
button is now disabled/invisible
is that what you really want?
# 20
here is my last edition but the required function still not working, where is the wrong this time?
public class MyDealer extends JPanel
{
private JLabel lab1;
private JLabel lab2;
private JLabel lab3;
private JLabel lab4;
private JLabel lab5;
private JLabel lab6;
private JTextField txtF1;
private JTextField txtF2;
private JTextField txtF3;
private JTextField txtF4;
private JTextField txtF5;
private JTextField txtF6;
private JButton btn1;
private JButton btn2;
private JTextArea txtA;
Car4Sale aCar4sale = new Car4Sale(); //both intialized so we can
Dealer aDealer= new Dealer();//retreat with theirs classes
public MyDealer()
{
//construct components
lab1 = new JLabel ("Car model:");
lab2 = new JLabel ("Engine size :");
lab3 = new JLabel ("Car colour:");
lab4 = new JLabel ("Buying price:");
lab5 = new JLabel ("Ref. number:");
lab6 = new JLabel ("Selling price:");
txtF1 = new JTextField (5);
txtF2 = new JTextField (5);
txtF3 = new JTextField (5);
txtF4 = new JTextField (5);
txtF5 = new JTextField (5);
txtF6 = new JTextField (5);
btn1 = new JButton ("Buy a car");
btn2 = new JButton ("Sell a car");
txtA = new JTextArea (5, 5);
txtA.setEditable(false);
//adjust size and set layout
setPreferredSize (new Dimension (421, 468));
setLayout (null);
//add components
add ( lab1);
add (lab2);
add (lab3);
add (lab4);
add (lab5);
add (lab6);
add (txtF1);
add (txtF2);
add (txtF3);
add (txtF4);
add (txtF5);
add (txtF6);
add (btn1);
add (btn2);
add (txtA);
//set component bounds
lab1.setBounds (0, 26, 100, 25);
lab2.setBounds (0, 66, 100, 25);
lab3.setBounds (0, 106, 100, 25);
lab4.setBounds (0, 146, 100, 25);
lab5.setBounds (200, 26, 100, 25);
lab6.setBounds (200, 66, 100, 25);
txtF1.setBounds (100, 26, 100, 25);
txtF2.setBounds (100, 66, 100, 25);
txtF3.setBounds (100, 106, 100, 25);
txtF4.setBounds (100, 146, 100, 25);
txtF5.setBounds (300, 26, 100, 25);
txtF6.setBounds (300, 66, 100, 25);
btn1.setBounds (20, 191, 100, 25);
btn2.setBounds (223, 191, 100, 25);
txtA.setBounds (21, 243, 380, 200);
ActionListener a = new ActionListener(){
public void actionPerformed(ActionEvent e){
String s1 = new String(txtF1.getText()) ; // Car model field
double d1 = Double.parseDouble(txtF2.getText()); //Engine size field
String s2= new String (txtF3.getText()); // Car colour field
double d2 = Double.parseDouble(txtF4.getText());// Buying price field
//assigning textfields inputs to its correspondent variables
// Note that car reference number will be genereted automatically
// when we assign Car attributes , So no need to enter
aCar4sale.model =s1;
aCar4sale.engineSize = d1;
aCar4sale.color =s2;
aCar4sale.purchase =d2;
txtA.setText("1"+aDealer.toString());
txtF1.setText("");
txtF2.setText("");
txtF3.setText("");
txtF4.setText("");
}
};
btn1.addActionListener(a);
//here is the method across GUI that enables us to see if the entered
//selling price (d3) equals aCar4Sale's selling price or not
a = new ActionListener(){
public void actionPerformed(ActionEvent e){
String s3= new String(txtF5.getText()); // Ref. number field ,Note that
// is in String type to compare it with the hashtable key aCar4sale.vrn
double d3 = Double.parseDouble(txtF6.getText());// Selling price field
aCar4sale.vrn=s3; //assigning s3 to object key so we can retrieve
//its object value by hashtable(theCarlist) to
//see wether d3 equals aCar4Sale's selling price or not
if( aCar4sale.getSelling()== d3){
aDealer.theCarList.remove(aCar4sale.vrn);
}// if they are both eqaulled the object key will be removed from
// the hashtable, so the corresponding object value
else{
JOptionPane.showMessageDialog(null,
"The price does not match","ERROR",JOptionPane.ERROR_MESSAGE);
}
}
};
btn2.addActionListener(a);
txtA.getDocument().addDocumentListener(new DocumentListener() {
public void insertUpdate(DocumentEvent evt) {
btn2.setEnabled(true);
txtF5.setVisible(true);
txtF6.setVisible(true);
}
public void removeUpdate(DocumentEvent evt) {
btn2.setEnabled(false);
txtF5.setVisible(false);
txtF6.setVisible(false);
}
public void changedUpdate(DocumentEvent e) {
}
});
}
public static void main (String[] args)
{
JFrame frame = new JFrame ("car dealer");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new MyDealer());
frame.pack();
frame.setVisible (true);
}
}
class Dealer extends Car4Sale{
Hashtable theCarList ;
public Dealer (){
theCarList = new Hashtable() ;
}
public void addCar4Sale (Car4Sale aCar4Sale){
theCarList.put(aCar4Sale.vrn,aCar4Sale);
}
public String toString(){
Car4Sale aCAr4Sale;
String str="";
Enumeration h= theCarList.keys();
while (h.hasMoreElements()){
aCAr4Sale =(Car4Sale)theCarList.get(h.nextElement());
str += aCAr4Sale +"\n";
}
return str;
}
}
class Car {
int referenceNumber ;
double engineSize;
String model, color;
public static int carCounter ;
public Car (){
carCounter++;
referenceNumber = carCounter;
}
public Car(int r, double e, String m, String c) {
referenceNumber = r;
engineSize = e;
model = m;
color = c ;
}
public void setReferenceNumber(int r){
referenceNumber = r;
}
public void setEngineSize(double e) {
engineSize = e;
}
public void setModel(String m) {
model = m;
}
public void setColor(String c) {
color = c;
}
public int getReferenceNumber(){
return referenceNumber;
}
public double getEngineSize() {
return engineSize;
}
public String getModel() {
return model;
}
public String getColor() {
return color;
}
}
class Car4Sale extends Car {
double purchase ; double selling ;
String vrn = Integer.toString(referenceNumber);// to use it as a key in hashtable
public double getSelling(){
selling = (purchase += (purchase / 100) *15);
return selling ;
}
public String toString(){
String w =(""+(referenceNumber)+") \t Car Model"+model+
"\t engine Size"+engineSize+"\t car colour"+color+
"\t Buying price"+purchase);
return w;
}
}
# 21
anybody no why the added documentListener didnt do what expected from it
# 22
If you want the buttons disabled/invisible at startup, you need to set them that
way in the constructor.
Put the disable/invisible code into a separate method, then call that method
from the constructor and the documentListener.
as you programatically add/delete items to/from the textField, the documentListener
will dis/enable accordingly
# 23
yes it did work as expexted, may be it is my humble experience in java . i have to exercise more to be familiar wirh java.
anyway i still facing problem with this code because i am expecting hashtable (theCarList) to be shown on (txtA) but is see nothing but "1" that i initialize it here in the block of ( btn1) Action :
txtA.setText("1"+aDealer.toString());
i need to see this hashtable on txtA to check wether my program running succesfully or not. Because the purpose is to show the available cars for sale and when the dealer sells prticular car it should be removed from the hashtable and this will show me if the hashtable working properly either
# 24
> i need to see this hashtable on txtA t......where do you add anything to 'aDealer'?
# 25
here is where i initialize attributes of aCar4Sale wich is inherited by aDealer :
ActionListener a = new ActionListener(){
public void actionPerformed(ActionEvent e){
String s1 = new String(txtF1.getText()) ; // Car model field
double d1 = Double.parseDouble(txtF2.getText()); //Engine size field
String s2= new String (txtF3.getText()); // Car colour field
double d2 = Double.parseDouble(txtF4.getText());// Buying price field
//assigning textfields inputs to its correspondent variables
// Note that car reference number will be genereted automatically
// when we assign Car attributes , So no need to enter
aCar4sale.model =s1;
aCar4sale.engineSize = d1;
aCar4sale.color =s2;
aCar4sale.purchase =d2;
txtA.setText("1"+aDealer.toString());
txtF1.setText("");
txtF2.setText("");
txtF3.setText("");
txtF4.setText("");
}
};
btn1.addActionListener(a);
aDealer is where hashtable intialized and hashtable depends on aCar4Sale
# 26
i found some errors regarding aCar4Sale reference there were more than one reference and they should be the same . anyway i fixed them but the problem still existing, the hashtable didnt appear . and this is the last edition:
package cardealer;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.Hashtable;
import java.util.Enumeration;
public class MyDealer extends JPanel
{
private JLabel lab1;
private JLabel lab2;
private JLabel lab3;
private JLabel lab4;
private JLabel lab5;
private JLabel lab6;
private JTextField txtF1;
private JTextField txtF2;
private JTextField txtF3;
private JTextField txtF4;
private JTextField txtF5;
private JTextField txtF6;
private JButton btn1;
private JButton btn2;
private JTextArea txtA;
Car4Sale aCar4Sale = new Car4Sale(); //both intialized so we can
Dealer aDealer= new Dealer();//retreat with theirs classes
public MyDealer()
{
//construct components
lab1 = new JLabel ("Car model:");
lab2 = new JLabel ("Engine size :");
lab3 = new JLabel ("Car colour:");
lab4 = new JLabel ("Buying price:");
lab5 = new JLabel ("Ref. number:");
lab6 = new JLabel ("Selling price:");
txtF1 = new JTextField (5);
txtF2 = new JTextField (5);
txtF3 = new JTextField (5);
txtF4 = new JTextField (5);
txtF5 = new JTextField (5);
txtF5.setVisible(false);
txtF6 = new JTextField (5);
txtF6.setVisible(false);
btn1 = new JButton ("Buy a car");
btn2 = new JButton ("Sell a car");
btn2.setEnabled(false);
txtA = new JTextArea (5, 5);
txtA.setEditable(false);
txtA.getDocument().addDocumentListener(new DocumentListener() {
public void insertUpdate(DocumentEvent evt) {
btn2.setEnabled(true);
txtF5.setVisible(true);
txtF6.setVisible(true);
}
public void removeUpdate(DocumentEvent evt) {
btn2.setEnabled(false);
txtF5.setVisible(false);
txtF6.setVisible(false);
}
public void changedUpdate(DocumentEvent e) {
}
});
//adjust size and set layout
setPreferredSize (new Dimension (421, 468));
setLayout (null);
//add components
add ( lab1);
add (lab2);
add (lab3);
add (lab4);
add (lab5);
add (lab6);
add (txtF1);
add (txtF2);
add (txtF3);
add (txtF4);
add (txtF5);
add (txtF6);
add (btn1);
add (btn2);
add (txtA);
//set component bounds
lab1.setBounds (0, 26, 100, 25);
lab2.setBounds (0, 66, 100, 25);
lab3.setBounds (0, 106, 100, 25);
lab4.setBounds (0, 146, 100, 25);
lab5.setBounds (200, 26, 100, 25);
lab6.setBounds (200, 66, 100, 25);
txtF1.setBounds (100, 26, 100, 25);
txtF2.setBounds (100, 66, 100, 25);
txtF3.setBounds (100, 106, 100, 25);
txtF4.setBounds (100, 146, 100, 25);
txtF5.setBounds (300, 26, 100, 25);
txtF6.setBounds (300, 66, 100, 25);
btn1.setBounds (20, 191, 100, 25);
btn2.setBounds (223, 191, 100, 25);
txtA.setBounds (21, 243, 380, 200);
ActionListener a = new ActionListener(){
public void actionPerformed(ActionEvent e){
String s1 = new String(txtF1.getText()) ; // Car model field
double d1 = Double.parseDouble(txtF2.getText()); //Engine size field
String s2= new String (txtF3.getText()); // Car colour field
double d2 = Double.parseDouble(txtF4.getText());// Buying price field
//assigning textfields inputs to its correspondent variables
// Note that car reference number will be genereted automatically
// when we assign Car attributes , So no need to enter
aCar4Sale.model =s1;
aCar4Sale.engineSize = d1;
aCar4Sale.color =s2;
aCar4Sale.purchase =d2;
txtA.setText("1"+aDealer.toString());
txtF1.setText("");
txtF2.setText("");
txtF3.setText("");
txtF4.setText("");
}
};
btn1.addActionListener(a);
//here is the method across GUI that enables us to see if the entered
//selling price (d3) equals aCar4Sale's selling price or not
a = new ActionListener(){
public void actionPerformed(ActionEvent e){
String s3= new String(txtF5.getText()); // Ref. number field ,Note that
// is in String type to compare it with the hashtable key aCar4sale.vrn
double d3 = Double.parseDouble(txtF6.getText());// Selling price field
aCar4Sale.vrn=s3; //assigning s3 to object key so we can retrieve
//its object value by hashtable(theCarlist) to
//see wether d3 equals aCar4Sale's selling price or not
if( aCar4Sale.getSelling()== d3){
aDealer.theCarList.remove(aCar4Sale.vrn);
}// if they are both eqaulled the object key will be removed from
// the hashtable, so the corresponding object value
else{
JOptionPane.showMessageDialog(null,
"The price does not match","ERROR",JOptionPane.ERROR_MESSAGE);
}
}
};
btn2.addActionListener(a);
}
public static void main (String[] args)
{
JFrame frame = new JFrame ("car dealer");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new MyDealer());
frame.pack();
frame.setVisible (true);
}
}
class Dealer extends Car4Sale{
Hashtable theCarList ;
public Dealer (){
theCarList = new Hashtable() ;
}
public void addCar4Sale (Car4Sale aCar4Sale){
theCarList.put(aCar4Sale.vrn,aCar4Sale);
}
public String toString(){
Car4Sale aCar4Sale;
String str="";
Enumeration h= theCarList.keys();
while (h.hasMoreElements()){
aCar4Sale =(Car4Sale)theCarList.get(h.nextElement());
str += aCar4Sale +"\n";
}
return str;
}
}
class Car {
int referenceNumber ;
double engineSize;
String model, color;
public static int carCounter ;
public Car (){
carCounter++;
referenceNumber = carCounter;
}
public Car(int r, double e, String m, String c) {
referenceNumber = r;
engineSize = e;
model = m;
color = c ;
}
public void setReferenceNumber(int r){
referenceNumber = r;
}
public void setEngineSize(double e) {
engineSize = e;
}
public void setModel(String m) {
model = m;
}
public void setColor(String c) {
color = c;
}
public int getReferenceNumber(){
return referenceNumber;
}
public double getEngineSize() {
return engineSize;
}
public String getModel() {
return model;
}
public String getColor() {
return color;
}
}
class Car4Sale extends Car {
double purchase ; double selling ;
String vrn = Integer.toString(referenceNumber);// to use it as a key in hashtable
public double getSelling(){
selling = (purchase += (purchase / 100) *15);
return selling ;
}
public String toString(){
String w =(""+(referenceNumber)+") \t Car Model"+model+
"\t engine Size"+engineSize+"\t car colour"+color+
"\t Buying price"+purchase);
return w;
}
}
# 27
> aDealer is where hashtable intialized and hashtable depends on aCar4Sale but where do you haveaDealer.addCar4Sale(...)
# 28
> > aDealer is where hashtable intialized and hashtable> depends on aCar4Sale > > but where do you have> aDealer.addCar4Sale(...)should i replace it with :txtA.setText("1"+aDealer.toString());
# 29
i just fixed it and now the information that i entered appears on txtA, But when i enter new information it override on the same object, and when i try to delete it by" sell a car" Action, the error massage when the price is not matched appear even if the price is matching .and this is the block in response for "sell a car":
a = new ActionListener(){
public void actionPerformed(ActionEvent e){
String s3= new String(txtF5.getText()); // Ref. number field ,Note that
// is in String type to compare it with the hashtable key aCar4sale.vrn
double d3 = Double.parseDouble(txtF6.getText());// Selling price field
aCar4Sale.vrn=s3; //assigning s3 to object key so we can retrieve
//its object value by hashtable(theCarlist) to
//see wether d3 equals aCar4Sale's selling price or not
if( aCar4Sale.getSelling()== d3){
aDealer.theCarList.remove(aCar4Sale.vrn);
}// if they are both eqaulled the object key will be removed from
// the hashtable, so the corresponding object value
else{
JOptionPane.showMessageDialog(null,
"The price does not match","ERROR",JOptionPane.ERROR_MESSAGE);
}
}
};
btn2.addActionListener(a);
i was expecting when i enter new information it goes for new object but i dont know why it didnt . selling price of each object = %115 of Buying price
Message was edited by:
scrolldown
# 30
> the error massage when the price is not matched appear even if the price is matching
debugging 101
if the problem is occurring here
if( aCar4Sale.getSelling()== d3){
add a couple of System.out.println()
System.out.println(aCar4Sale.getSelling());
System.out.println(d3);
if( aCar4Sale.getSelling()== d3){
# 31
your addition just let me check wether they are really equalled or not, but it didnt solve the problem. the error message still appearing even if they are equalled.Message was edited by: scrolldown
# 32
this line in hashtable (theCarList) is enabling (theCarList) to have new object so why it is overriding the existing aCar4Sale?:aCar4Sale =(Car4Sale)theCarList.get(h.nextElement());
# 33
at this stage it's probably a whole lot easier to post a working example of what I
think you're trying to do
this is a heavily stripped down version of your code, just enough in the classes
to make them work
run the program, the 3 hard-coded cars appear, select the first one 'Jaguar',
then type 11500 into the textfield and click the button - the car will be removed.
(I changed the display to a JList - easier to select a car)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.*;
class MyDealer extends JPanel
{
private JLabel labSellPrice = new JLabel ("Selling price:",JLabel.CENTER);
private JTextField txtSellPrice = new JTextField (10);
private JButton btnSell = new JButton ("Sell a car");
Dealer aDealer= new Dealer();
JList list = new JList();
public MyDealer()
{
setPreferredSize (new Dimension (421, 468));
setLayout (new BorderLayout());
JPanel p = new JPanel(new GridLayout(3,1));
p.add (labSellPrice);
p.add (txtSellPrice);
p.add (btnSell);
JPanel p1 = new JPanel();
p1.add(p);
add(new JScrollPane(list),BorderLayout.CENTER);
add(p1,BorderLayout.EAST);
ActionListener a = new ActionListener(){
public void actionPerformed(ActionEvent e){
if(list.getSelectedIndex() < 0)
{
JOptionPane.showMessageDialog(null,"No car selection");
return;
}
Car4Sale aCar4sale = (Car4Sale)list.getSelectedValue();
try
{
double sellPrice = Double.parseDouble(txtSellPrice.getText());
if( aCar4sale.getSelling() == sellPrice){
aDealer.theCarList.remove(aCar4sale.vrn);
loadJList();
}
else{
JOptionPane.showMessageDialog(null,
"The price does not match","ERROR",JOptionPane.ERROR_MESSAGE);
}
}
catch(NumberFormatException nfe){JOptionPane.showMessageDialog(null,"Invalid sell price data");}
}
};
btnSell.addActionListener(a);
loadSomeCars();
loadJList();
}
public void loadSomeCars()
{
aDealer.addCar4Sale(new Car4Sale("J123","Jaguar",10000.00));
aDealer.addCar4Sale(new Car4Sale("M789","Mustang",15101.00));
aDealer.addCar4Sale(new Car4Sale("RR007","Rolls Royce",99999.99));
}
public void loadJList()
{
DefaultListModel listModel = new DefaultListModel();
Enumeration h = aDealer.theCarList.keys();
while (h.hasMoreElements()){
listModel.addElement(aDealer.theCarList.get(h.nextElement()));
}
list.setModel(listModel);
}
public static void main (String[] args)
{
JFrame frame = new JFrame ("car dealer");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new MyDealer());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class Dealer
{
Hashtable theCarList = new Hashtable();
public void addCar4Sale (Car4Sale aCar4Sale)
{
theCarList.put(aCar4Sale.vrn,aCar4Sale);
}
public String toString()
{
Car4Sale aCAr4Sale;
String str="";
Enumeration h= theCarList.keys();
while (h.hasMoreElements()){
aCAr4Sale =(Car4Sale)theCarList.get(h.nextElement());
str += aCAr4Sale +"\n";
}
return str;
}
}
class Car
{
String vrn;
String model;
}
class Car4Sale extends Car
{
double purchasePrice;
double sellingPrice;
public Car4Sale(String v, String m, double pp)
{
vrn = v; model = m; purchasePrice = pp;
sellingPrice = purchasePrice * 1.15;
}
public double getSelling(){return sellingPrice;}
public String toString(){return model;}
}
# 34
thank you sir for this favour,
i tried it and i have found nothing new . the same problem still exists.
I've enetered the exact prices but instead of removing the car object ,the error message appears.
i tried to keep on remove method only in this part to see if ti is working but unfortunately it seems not working this way i dont Know why ?
may be there is special way to remove hashtable object from outside its class .
what do u think ?
# 35
> may be there is special way to remove hashtable object from outside its class
removing an item from the hashtable works fine in the example I posted, so,
in theory, it should also work fine in your code.
in my example, the Jaguar had a purchase price of 10000, so a sell price was 11500,
and this worked fine. Not so for the others, because doubles are tricky when using ==.
e.g. 14.000000 is not equal to 14.000001, even though 14 == 14
in the example I posted, change the try block in the actionListener to this
try
{
//double sellPrice = Double.parseDouble(txtSellPrice.getText());
String sellPrice = txtSellPrice.getText();
//if( aCar4sale.getSelling() == sellPrice){
if( aCar4sale.getSelling().equals(sellPrice)){
aDealer.theCarList.remove(aCar4sale.vrn);
loadJList();
}
else{
JOptionPane.showMessageDialog(null,
"The price does not match","ERROR",JOptionPane.ERROR_MESSAGE);
}
}
catch(NumberFormatException nfe){JOptionPane.showMessageDialog(null,"Invalid sell price data");}
and in class Car4Sale, change this
//public double getSelling(){return sellingPrice;}
public String getSelling(){return new java.text.DecimalFormat("0.00").format(sellingPrice);}
basically, using DecimalFormat() to round the double value into a 2 digit string
now, in the example, the Mustang and Rolls Royce remove OK, but the
Jaguar works only if you enter 11500.00 (instead of 11500 previously)
the == of the doubles could be your problem, experiment, see how you go
# 36
Actually i dont know what is happening?
action block always taking action on the last statement so that error message appears whatever you enter. And when i delete this statement and keep on remove statement only nothing happened either.
finally, i tried to replace equals with == but system refuses saying double can not be dereferenced.
Message was edited by:
scrolldown
# 37
> but system refuses saying double can not be dereferenced.did you try changing the the values to Strings, and compare using .equals()?