1. Welcome to the new MacRumors forums. See our announcement and read our FAQ

Can anyone help with this ActionListener in my java program?

Discussion in 'Mac Programming' started by maxtoncollins1, Mar 21, 2012.

  1. macrumors newbie

    #1
    I'm trying to create a program to convert inches to centimeters. I made one that displayed the info in the console. (You'd type in a number of inches and it'd display how many centimeters that'd be) Now i'm trying to make one using java swing and i have a window that pops up but I am completely stuck on getting the action listener. Can anyone offer any advice or correct my code?
    Here's the code:
    Code:
    import javax.swing.*;
    
    import java.awt.Color;
    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    public class Cw extends JFrame implements ActionListener {
    
    	private JButton convert;
    	JTextArea text = new JTextArea(1,20);
    	private int conversion = 0;
    	
    	
    	
    	public Cw() {
    		setLayout(new FlowLayout());
    		setVisible(true);
    		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		setSize(400,200);
    		convert = new JButton("Convert");
    		add(convert);
    		add(text);
    		convert.addActionListener(this);
    
    		
    	}
    
    
    
    public void actionPerformed(ActionEvent e) {
    	Object source = e.getSource();
    	
    		}
    
    		
    	}
    
    
     
  2. macrumors 603

    #2
    What tutorial or book are you using? Or are you taking a class?


    Step 1 is to make the action do something simple, like show the text that's in the text field. That's a simple yet observable action. If you don't know how to do it, then you need to study how user input in Swing works. Not the button-click user input, just plain old text entered in a text field.

    Step 2 is to make the action validate the contents of the text field. I.e. is it numeric? Presumably you had to do that in the terminal oriented program.

    Step 3 is to convert the text to a number and perform the calculation. Again, you did that in the terminal program, right?

    Step 4 is to figure out how and where to display the result of the calculation. Study Swing again, and look for a component that can display text, or numbers converted to text.
     

Share This Page