View Full Version : Can anyone help with this ActionListener in my java program?

Mar 21, 2012, 06:35 PM
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:

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());
convert = new JButton("Convert");


public void actionPerformed(ActionEvent e) {
Object source = e.getSource();



Mar 21, 2012, 07:41 PM
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.