Results 1 to 11 of 11
  1. #1
    bubbless is offline Member
    Join Date
    Mar 2009
    Posts
    81
    Rep Power
    0

    Default addActionListener

    Hi all.
    I'm having a problem, again. :(
    I've tried to rewrite my little converter with the MVC pattern and everything is working exept for the actionlisteners.
    When I run it, I see the GUI but when I try one of the buttons, nothing happens.

    Assistent.java

    Java Code:
    public class Assistent {
    
    	/**
    	 * @param args
    	 */
    	public static void main(String[] args) {
    		AssistentView View = new AssistentView();
    		AssistentController Controller = new AssistentController(View);
    		View.Window.setVisible(true);
    	}
    }
    AssistentView.java

    Java Code:
    import java.awt.BorderLayout;
    import java.awt.GridLayout;
    
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTabbedPane;
    import javax.swing.JTextField;
    
    
    public class AssistentView {
    	JFrame Window = new JFrame("Window");
    	JLabel LCelsius = new JLabel("Celsius:");
    	JLabel LKelvin = new JLabel("Kelvin:");
    	JLabel LFahrenheit = new JLabel("Fahrenheit:");
    	JTextField TCelsius = new JTextField(10);
    	JTextField TKelvin = new JTextField(10);
    	JTextField TFahrenheit = new JTextField(10);
    	String CCelsius;
    	String CKelvin;
    	String CFahrenheit;
    	JButton BConvert = new JButton("Convert");
    	JButton BReset = new JButton("Reset");
    	JPanel PTemperature = new JPanel();
    	GridLayout Row1 = new GridLayout(4,1);
    	GridLayout Row2 = new GridLayout(4,1);
    	JPanel PRow1 = new JPanel(Row1);
    	JPanel PRow2 = new JPanel(Row2);
    	BorderLayout BLayout = new BorderLayout();
    	JPanel Layout = new JPanel(BLayout);
    	JTabbedPane TabbedPane = new JTabbedPane();
    	
    	AssistentView() {
    		PRow1.add(LCelsius);
    		PRow1.add(LKelvin);
    		PRow1.add(LFahrenheit);
    		PRow1.add(BReset);
    		PRow2.add(TCelsius);
    		PRow2.add(TKelvin);
    		PRow2.add(TFahrenheit);
    		PRow2.add(BConvert);
    		Row1.setVgap(5);
    		Row2.setVgap(5);
    		Layout.add(PRow1, BorderLayout.WEST);
    		Layout.add(PRow2, BorderLayout.CENTER);
    		BLayout.setHgap(5);
    		PTemperature.add(Layout, BorderLayout.NORTH);
    		TabbedPane.addTab("Temperature", PTemperature);
    		Window.setContentPane(TabbedPane);
    		Window.setSize(400,400);
    		Window.setLocationRelativeTo(null);
    		Window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    	}
    	
    	public void reset() {
    		TCelsius.setText("");
    		TKelvin.setText("");
    		TFahrenheit.setText("");
    	}
    	
    	public void setValue(JTextField A, Double B) {
    		A.setText(Double.toString(B));
    	}
    	
    	public double getInput(JTextField A) {
    		String ATemp = A.getText();
    		Double Result = Double.parseDouble(ATemp);
    		return Result;
    	}
    }
    AssistentController.java

    Java Code:
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    
    public class AssistentController implements ActionListener {
    	AssistentView AV = new AssistentView();
    	AssistentModel AM = new AssistentModel();
    	double DCelsius;
    	double DKelvin;
    	double DFahrenheit;
    	
    	AssistentController(AssistentView View) {
    		AssistentView AV = View;
    		AV.BConvert.addActionListener(this);
    		AV.BReset.addActionListener(this);
    	}
    	
    	public void actionPerformed(ActionEvent e) {
    		if(e.getSource() == AV.BConvert) {
    			if(!AV.CCelsius.equals("")) {
    				DCelsius = AV.getInput(AV.TCelsius);
    				DKelvin = DCelsius + 273.15;
    				DFahrenheit = ((DCelsius * 9) / 5) + 32;
    			} else if(!AV.CKelvin.equals("")) {
    				DKelvin = AV.getInput(AV.TKelvin);
    				DCelsius = DKelvin - 273.15;
    				DFahrenheit = (DCelsius *(9/5))+32;
    			} else if(!AV.CFahrenheit.equals("")) {
    				DFahrenheit = AV.getInput(AV.TFahrenheit);
    				DCelsius = (DFahrenheit - 32.0) * 5.0 / 9.0;
    				DKelvin = DCelsius + 273.15;
    			}
    			AV.setValue(AV.TCelsius, DCelsius);
    			AV.setValue(AV.TKelvin, DKelvin);
    			AV.setValue(AV.TFahrenheit, DFahrenheit);
    		} else if(e.getSource() == AV.BReset) {
    			AV.reset();
    		}
    	}
    }

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Hey, can we see your model code as well?

    Best of luck.

  3. #3
    mtyoung is offline Senior Member
    Join Date
    Dec 2008
    Location
    Hong Kong
    Posts
    473
    Rep Power
    6

    Default

    e.getSource() return Object
    while BConvert is JButton,
    they never '=='

  4. #4
    bubbless is offline Member
    Join Date
    Mar 2009
    Posts
    81
    Rep Power
    0

    Default

    Hehe, model is quite empty, I'm still learning the MVC pattern.
    Mtyoung, I think it worked before I used the MVC pattern with the same actionlistener.

    AssistentModel.java

    Java Code:
    public class AssistentModel {
    }
    Edit.
    I used an else { } after the actionlistener, so when the action isn't BConvert or BReset and I added a System.out.println() and he showed it, so he doesn't think those are the right buttons.

    When i use only = instead of ==, it says the left-hand side of an assignment must be a variable.
    Last edited by bubbless; 03-14-2009 at 04:08 PM.

  5. #5
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    I probably shouldn't do this, but I tried to create your app using MVC and this is what I had. Sorry about the lack of comments. As it's quite a bit bigger than I had planned, it may be too big of a bite for others to chew. Also, it's in zip format, but it's actually also a jar file.
    Attached Files Attached Files

  6. #6
    paul pasciak is offline Senior Member
    Join Date
    Jul 2008
    Posts
    125
    Rep Power
    0

    Default This debugging shows the actionListener is installed.

    The following System.out.println() methods show
    that the actionsListeners are properly installed.
    Notice that I didn't need to know about the model
    to test this part of your code.

    Java Code:
    public class AssistentController implements ActionListener{
      AssistentView AV = new AssistentView();
      AssistentModel AM = new AssistentModel();
      double DCelsius;
      double DKelvin;
      double DFahrenheit;
      
      AssistentController(AssistentView View){
        AssistentView AV = View;
        AV.BConvert.addActionListener(this);
        AV.BReset.addActionListener(this);
      }
      
      public void actionPerformed(ActionEvent e){
    System.out.println("Action performed");
        if(e.getSource() == AV.BConvert){
          if(!AV.CCelsius.equals("")){
            DCelsius = AV.getInput(AV.TCelsius);
            DKelvin = DCelsius + 273.15;
            DFahrenheit = ((DCelsius * 9) / 5) + 32;
    System.out.println("a");
          } else if(!AV.CKelvin.equals("")){
            DKelvin = AV.getInput(AV.TKelvin);
            DCelsius = DKelvin - 273.15;
            DFahrenheit = (DCelsius *(9/5))+32;
    System.out.println("b");
          } else if(!AV.CFahrenheit.equals("")){
            DFahrenheit = AV.getInput(AV.TFahrenheit);
            DCelsius = (DFahrenheit - 32.0) * 5.0 / 9.0;
            DKelvin = DCelsius + 273.15;
    System.out.println("c");
          }
          AV.setValue(AV.TCelsius, DCelsius);
          AV.setValue(AV.TKelvin, DKelvin);
          AV.setValue(AV.TFahrenheit, DFahrenheit);
    System.out.println("d");
        }
        else if(e.getSource() == AV.BReset){
          AV.reset();
    System.out.println("e");
        }
      }
    }
    
    public class AssistentModel{
    }

  7. #7
    bubbless is offline Member
    Join Date
    Mar 2009
    Posts
    81
    Rep Power
    0

    Default

    Wow, you must have put some time in this.
    I really appreciate this, thank alot.
    I'll have a look at it.

  8. #8
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    I hope that you are familiar with enums and HashMaps as I use an enum to hold the different temperature scales (Kelvin, Celsius, Fahr...). I use the values() array that can be obtained from the enum to create Strings for the the JLabels also place the JTextFields into a HashMap using the same Strings as the keys.

  9. #9
    bubbless is offline Member
    Join Date
    Mar 2009
    Posts
    81
    Rep Power
    0

    Default

    I now see I posted this in the wrong thread. :)
    You know I meant your post in the other thread.

    I'm familiar with enums but not with hashmaps.
    I'll look it up tomorrow.

    I've taken a look at it but it looks a little confusing right now.
    Is it normal to use six different classes?
    I thought it would be main, model, view and controller.

    I've changed my program to the way you did it.
    The actionlisteners in the controller and then add them in the main but it still doesn't work.

    I really appreciate this but I think it's just too complicated for me right now.

  10. #10
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Again, sorry for the large number of classes. Let me try to explain their purposes:

    TempScale.java
    this is an enum that defines CELSIUS("Celsius:"), KELVIN("Kelvin:"), FAHRENHEIT("Fahrenheit:"); and associates text strings with each enum (see parameter). This is used by the model to create JLabels and also used to create a HashMap<String, JTextField> of jtextfields. An array of the enum can be obtained easily via TempScale.values(). This is also used by the Control to get jtextfields from view.

    TemperaturePanelInter.java
    This is an interface that encapsulates the public constants and methods used in the View. While this isn't necessary, it does help loosen coupling between the model and the control.

    TemperaturePanel.java
    This is the view class that creates a TemperaturePanel. The jpanel can be extracted from this class via the getComponent method. I like to use this rather than extend JPanel as it (somewhat) hides most of JPanel from the other classes. Again, the TempScale enum is used by the model to create JLabels and also used to create a HashMap<String, JTextField> of jtextfields. Think of the hashmap like an array, but instead of using a number to get the jtextfield item out of the array, I use the String derived from the enum. On further thought, the map would have been cleaner if I just used the enum itself and not the String.

    TemperatureFrame.java
    Creates JFrame with which to show the app.

    TemperatureModel.java
    This is the model class. Again, this could have been nothing more than a static method as it really has no state -- it has no class fields. This uses the enum to know the scale of the input data (the temp entered by the user), and the temp-scale of the output data (the other empty fields). It initially converts all input data into kelvin, and then converts the kelvin temp to whatever type is requested by the output type. The reason for this is that it prevents me from having to write out 12 equations for each possible combination of input and output.

    TemperatureControl.java
    The control, of course. It has references to the view and to the model, and both of the references are set using setters. It implements the ActionListener interface, and its meat is in an actionPerformed method. This method first determines which button has been pressed by matching the ActionEvent's actionCommand String with the button strings. The button strings are stored as constants in the view's interface, TemperaturePanelInter. So if the actionCommand matches TemperaturePanelInter.RESET, then I call resetFields() on the model. If the actionCommand matches TemperaturePanelInter.CONVERT, I try to do a conversion. Here is the innards of this method with comments:
    Java Code:
    for (TempScale inputTempScale : TempScale.values())
    This iterates through the enum, looping through CELSIUS, KELVIN, and FAHRENHEIT.
    Java Code:
    String text = tempPanel.getFieldText(inputTempScale.toString());
    This attempts to get the text contained in the JTextField that corresponds to the TempScale type that's being iterated above. The getFieldText in the view uses the HashMap to get the JTextField corresponding to the enum type and return the text held (if any).
    Java Code:
    if (text != null && !text.isEmpty())
    If there's any text held by the jtextfield...
    Java Code:
    double temperature = Double.parseDouble(
            tempPanel.getFieldText(inputTempScale.toString()));
    again, get the text and convert it to a double. This is done within a try catch block so as to catch non-numeric input.
    Java Code:
    for (TempScale outputTempScale : TempScale.values()) 
    {
       if (outputTempScale != inputTempScale)
    So, now that I've got the input data, I need to calculate the output data. I again iterate through the enum. If the input enum == the output enum, I do nothing. I don't want to convert Kelvin to Kelvin or Celsius to Celsius.
    Java Code:
    double result = model.calc(inputTempScale, outputTempScale, temperature);
    Otherwise, I use my model's calc method to do my calculation. I pass the input temp type and output temp type and input temperature value into the method and it will return the converted temperature double value in the result variable.
    Java Code:
    tempPanel.setFieldText(outputTempScale.toString(), format.format(result));
    I then place this result, formatted so it shows only 2 decimal places, into the view's corresponding output jtextfield. Again, I use the enum to figure out which JTextField to send this result to.

    TemperatureMain.java
    puts it all together:
    Java Code:
    public class TemperatureMain
    {
    
      private static void createAndShowUI()
      {
        TemperatureFrame frame = new TemperatureFrame();  // my JFrame
        TemperaturePanelInter tempPanel = new TemperaturePanel();  // the "View"
        TemperatureControl control = new TemperatureControl(); // the control
        TemperatureModel model = new TemperatureModel();  // the model
        
        control.setTemperaturePanel(tempPanel);  // add the view to the control
        control.setTemperatureModel(model);  // add the model to the control
        frame.addTab("Temperature", tempPanel.getComponent());  // add the view to the jframe
        tempPanel.addActionListener(control);  //add the control to the model
        
        frame.setVisible(true);
      }
    
      public static void main(String[] args)
      {
        java.awt.EventQueue.invokeLater(new Runnable()
        {
          public void run()
          {
            createAndShowUI();
          }
        });
      }
    }

  11. #11
    bubbless is offline Member
    Join Date
    Mar 2009
    Posts
    81
    Rep Power
    0

    Default

    Your don't have to apologize. :)
    I'm starting to understand it now.
    I'll rewrite the whole program tomorrow while having the things you did in the back of my head.

    Thanks again for doing this.

Similar Threads

  1. Replies: 3
    Last Post: 03-26-2009, 10:31 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •