Hello guys, I'm fairly new to Java. I have been asked to create a simple GUI (JLabel, JTextField and 3 JButtons)
I have managed to create the GUI but I'm having trouble with making the buttons work.

Here is my actionPerformed method:

    public void actionPerformed(ActionEvent evt)  
    {
        if(evt.getSource().equals(printButton)) // This is the first button. It should print the text in the JTextField
        {
            System.out.println(inResult.getText());
        }

        if (bgColour) // The second button (colourButton) should set the JTextField background to Red/White
        {
            bgColour = false;
            inResult.setBackground( Color.white );    
        } 
        else

        {
            bgColour = true;
            inResult.setBackground( Color.red );    
        }

        if (disableText) // ...and the last button (editableButton) should enable/disable the JTextField
        {
            disableText = false;
            inResult.setEditable(true);
        }
        else
        {
            disableText = true;
            inResult.setEditable(false);
        } 

I would like to add that if I only include the code for the second or third button, they work. I'm not sure if I can have more than one statement in my actionPerformed method, because if I use 'if, else if' only the first button is triggered'.
Thanks in advance! :)

Recommended Answers

All 8 Replies

Your second and third if tests should look like the first one
if(evt.getSource().equals(theAppropriateJBUtton)
then inside those if blocks you can test bgColor or disabledText as appropriate

Thanks for the quick reply JamesCherrill. Here is my updated code:
The JTextField background changes to red when I press Editable and only changes back to white when I press Colour. The Print button does not seem to be working again.
Any suggestions what the problem might be?

public void actionPerformed(ActionEvent evt)
{
if(evt.getSource().equals(printButton))
{
System.out.println(inResult.getText());
}

    if (evt.getSource().equals(colourButton))
    {
        bgColour = false;
        inResult.setBackground( Color.white );    
    } 
    else

    {
        bgColour = true;
        inResult.setBackground( Color.red );    
    }

    if (evt.getSource().equals(editableButton))
    {
        disableText = false;
        inResult.setEditable(true);
    }
    else
    {
        disableText = true;
        inResult.setEditable(false);
    }

You have lost the original if tests on bgColor and textEditable. You need them both...

if (this is the disable button) {
    if (disableText) {
        disableText = false;
        inResult.setEditable(true);
    else {
        disableText = true;
        inResult.setEditable(false)
    }
}

Thank you very much! I really appreciate your help! :)

One last question: Is there a way to print the contents of a JTextField by pressing enter?

Thanks for the link JamesCherrill
"For example,i enter text in a textfield and hit "enter",i want to send this to a textArea"

I don't think you understood me correctly. The person who started the thread is saying that when he presses the Enter key he wants the text to move from the inPut to outPut JTextField.
I have only got one JTextField; I want the text to be printed out System.out.println(); whenever the Enter key is pressed.

Thanks

I think I know what you mean.
What you need to take a look at is called KeyListener.
This is provided by oracle's tutorials: KeyListeners
Make sure to read through and you will probably understand how KeyListeners work.

Here is a Code-Snippet to get you started:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Class01 extends JFrame implements KeyListener // important
{
    private JPanel contentPane;
    private JTextField textField;

    public Class01()
    {
        contentPane = new JPanel();
        contentPane = (JPanel) this.getContentPane();
        contentPane.setLayout(null);
        contentPane.setBackground(Color.lightGray);
        contentPane.setOpaque(true);
        contentPane.setVisible(true);

        textField = new JTextField();
        textField.setSize(100,20);
        textField.addKeyListener(this);  // The interesting part.
        textField.setOpaque(true);
        textField.setVisible(true);

        setTitle("Java Tutorial - KeyListener");
        setSize(400,300);
        setResizable(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);

        addComponent(contentPane, textField, 150,100, 100, 20);
    }

    // Simple method only for this tutorial, should however, not be used
    // otherwise because of it's inconvenience.
    // With another word: Absolute positioning.
    //-----------------------------------------------------------------
    public void addComponent(Container container,
        Component c, int x, int y, int width, int height)
    {
        c.setBounds(x,y,width,height);
        container.add(c);
        validate();
    }



    // KeyListener Events

    public void keyPressed(KeyEvent e)  // The interesting part.
    {
        if (e.getKeyCode() == KeyEvent.VK_ENTER) // If enter buttons is pressed.
        {
            System.out.println(textField.getText()); // prints the textfield content.
        }
    }

    // Not used but needs to be implemented, or exception will occur.
    public void keyTyped(KeyEvent e) {}
    public void keyReleased(KeyEvent e) {}


    public static void main(String[] args)
    {
        java.awt.EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                JFrame.setDefaultLookAndFeelDecorated(true);
                JDialog.setDefaultLookAndFeelDecorated(true);
                try
                {
                    UIManager.setLookAndFeel(
                        "com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
                        // Look And Feel for Windows
                }
                catch (Exception ex)
                {
                    ex.printStackTrace();
                }

                new Class01();
            }
        });
     }      
 }

Whenever you type something in the textField and press Enter
it will print out the content of the TextField.
This is a just a basic sample of what you can do with KeyListeners.

Hope this was helpful.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.