Results 1 to 5 of 5
  1. #1
    Join Date
    Sep 2008
    Location
    Raleigh
    Posts
    8
    Rep Power
    0

    Default Swing Question, can you help?

    Ok, so I'm trying to understand Swing a bit better. I've created a container and all that good stuff, but what I'm trying to accomplish is:

    Creating a button that will add text on to the Frame when pressed. I accomplished this by defining the following:

    public void display() {
    JLabel dis = new JLabel("Acknowledged");
    add(dis);
    setVisible(true);
    }

    public void actionPerformed(ActionEvent evt) {
    String cmd = evt.getActionCommand();

    if (cmd == "Show") {
    display();
    }

    So here's the brain-tickler, When I press the button it does display the text as a JLabel in a FlowLayout fashion. When I press the button again it adds another in another, and another, and so on.

    So here's the question: What can I try to only have the button display one Jlabel only, and then do nothing when it's pressed again? Input would be greatly appreciated because I'm a noob to Java, it's my first computer programming language.

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

    Default

    Have a JLabel class field and set the text of that label on button press.

    for instance
    Java Code:
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    import javax.swing.JButton;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    
    public class FuSwing
    {
      private JPanel mainPane = new JPanel();
      private JLabel myLabel = new JLabel("One");
    
      public FuSwing()
      {
        ButtonListener btnListener = new ButtonListener();
        JButton oneButton = new JButton("One");
        JButton twoButton = new JButton("Two");
        oneButton.addActionListener(btnListener);
        twoButton.addActionListener(btnListener);
        
        mainPane.add(myLabel);
        mainPane.add(oneButton);
        mainPane.add(twoButton);
      }
    
      public JComponent getMainComponent()
      {
        return mainPane;
      }
      
      private class ButtonListener implements ActionListener
      {
        public void actionPerformed(ActionEvent e)
        {
          myLabel.setText(e.getActionCommand());
        }
      }
    
      private static void createAndShowUI()
      {
        JFrame frame = new JFrame("FuSwing");
        frame.getContentPane().add(new FuSwing().getMainComponent());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      }
    
      public static void main(String[] args)
      {
        java.awt.EventQueue.invokeLater(new Runnable()
        {
          public void run()
          {
            createAndShowUI();
          }
        });
      }
    }
    Last edited by Fubarable; 09-20-2008 at 09:21 PM.

  3. #3
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,306
    Rep Power
    25

    Default

    to only have the button display one Jlabel only, and then do nothing when it's pressed again?
    You need to follow the program flow to understand why you are having the problem
    What happens when the button is pressed, the display method is called and a new label is added to the container. For every button push a new label is added. ON and ON and ON.

    But you only want ONE button added on the first button press.
    So you need some logic to see if it is the first button press or a later button press. Several ways to do that. One is to use a boolean that is false to start with and which you set true after the first time. Another way would be to use a counter that you increment every call to display. Its value would be 0 only on the first call.

  4. #4
    Join Date
    Sep 2008
    Location
    Raleigh
    Posts
    8
    Rep Power
    0

    Thumbs up

    Wow, thanks for that Code Fubarable. There are alot of new concepts and ways in your code that I'd like to learn by further studying your code.

    Also big thanks to you Norm, your answer made perfect sense, especially at the noob level of programming I'm at right now.

    Below is a simple Swing GUI I wrote with both of ya'lls suggestions, so I could experiment with MouseListeners. I commented the hell out of it so ya'll could understand my personal understanding of the code I'm writing, as I write it. Hopefully, ya'll can spot an error in my personal logic with in the comments, and point it out so I can correct it to better learn/understand the language.

    Also I guess the comments can help noobs like myself learn MouseListeners like I did. I do have some logic questions at the bottom of the code if ya'll can help me out with them.

    You might want to copy and paste it into your IDE to read it better because with it displayed on the forum, it looks messier than my room, and more confusing than my ex-wife!

    Here's the code:

    package swingaction;

    /* This is a simple Swing GUI example/program that uses Mouse listeners. The idea is to
    * create a simple GUI that ties a mouse listener to a button and displays a JLabel that
    * Acknowledges the event (which is the mouse click in this case). The event also has a
    * counter (Thanks Norm!) that counts how many times the mouse button is clicked, and
    * displays that count with the acknowledgment. */

    import javax.swing.*; //Lines 7-9 imports all thats needed to make the GUI program.
    import java.awt.event.*;
    import java.awt.*;

    public class mouselisteners extends JFrame implements MouseListener {
    /* Line 13 is the start of the CLASS FILE & mouselisteners class/object/whatever-
    * -it's-called that extends-to/inherits-from the JFrame super class and implements
    * the MouseListener Interface. */

    JLabel dis = new JLabel("I'm a JLabel! "); // Line 19 Creates a JLabel that displays "I'm a JLabel!".
    //The JLabel text can also be " " which will display no text on the JLabel.

    JButton show = new JButton("Show"); // Creates the button named "Show"

    int count = 0; /*
    * Creates a integer variable that will be recognized with
    * in all methods and such within the class
    */

    mouselisteners() { // Start Constructor method
    super("Array Test"); // lines 31-34 is standard code to build/display the frame
    setSize(600, 600);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setVisible(true);

    show.addMouseListener(this); /*
    * Arms the show button with a listener that
    * will listen for a mouse event. Normally
    * this line of code is right under the
    * instantiation (creation) of the "Show"
    * button for better understanding, however,
    * the instantiation of the "Show" button
    * has to be outside the constructor method,
    * so other methods within the class file can
    * resolve (recognize) them. Line 36's code
    * has to be with in the constructor method
    * for reasons I personally don't know yet,
    * it just has to be?
    */

    FlowLayout flo = new FlowLayout(); /*
    * Creates (instantiates) the layout
    * of how the components (buttons,
    * labels etc.) will appear on the
    * frame.
    */

    setLayout(flo); // Applies the Layout to to frame.

    add(show); // Applies the button created on line 23 to the frame.
    add(dis); // Applies the JLabel created on line 19 to the frame.
    setVisible(true); // Makes the Applied components visible on the frame.

    } // End constructor method

    public void display() { // Start the writing the Display() method.
    count++; // Increments the counter up be one.
    dis.setText("Acknowledged Mouse click on mouse click " + count + "."); /*
    * Ok, line 68 was tricky for me, I just learned the .setText() method,
    * and used it within this program. "dis" is the name of the Jlabel,
    * created on line 19, so "dis.setText" means: apply the .setText() method
    * on the dis Jlabel. What .setText() does for you is it replaces any
    * old text of the JLabel into new text that you specify inside the
    * parenthesis that follows "setText" (Anything within the parenthesis
    * is known as an "argument"), so in this case, the JLabel named "dis"
    * now longer displays: "I'm a JLabel", it now displays: "Acknowledged
    * mouse click on mouse click " along with the current count of the
    * mouse clicks followed by a "." (period) to make the JLabel look
    * grammatically correct. (Thanks for the .setText() idea Fubarable!)
    */

    } // End Display() method.

    public void mousePressed(MouseEvent e) {
    // No code needed for a mouse button press.
    }

    public void mouseReleased(MouseEvent e) {
    // No code needed for a mouse button release.

    }

    public void mouseEntered(MouseEvent e) {
    // No code needed for mouse mousing on something.

    }

    public void mouseExited(MouseEvent e) { // No code needed for mouse mousing off of something

    }

    public void mouseClicked(MouseEvent e) {// Code is needed for a mouse click!
    System.out.println("Mouse click detected at mouse click: " + count
    + "\n" + "Performing the Display() method. \n \n");
    /*
    * Line 105 and 106 was only written to tell me in my IDE that a mouse
    * click was was heard by the mouseListener code written on line 36,
    * then tells me what the mouseClicked(MouseEvent e) on line 104 method is going
    * to do as a result of mouse being heard. The code for line 104 and 105 does
    * not display in the GUI, it displays in the IDE Console.
    */

    display(); // performs the Display() method written starting at line 66.
    } // end mouselisteners class/object/whatever-it's-called

    public static void main(String[] args) { /*
    * The Main statement. The Computer
    * actually starts reading the
    * program here when it is run.
    */
    mouselisteners run = new mouselisteners(); /*
    * Line 123 tells the
    * computer to construct all
    * thats written in lines
    * 13-116 which, in essence,
    * displays the GUI for user
    * to interact with.
    */
    } // End main Statement
    } // End CLASS FILE Program
    So Logical question are:

    1. Why does show.addMouseListener(this); have to be in the constructer method?

    2. What is The code thats after the Imports and before the Main statement
    called? Is it a Object? a Class? Both?

    3. Was there any logical errors I made in the comments? Like, did I write the code right, but explained the reasoning behind it wrong?

    If ya'll know an answer to any of that I'll have your babies! Also, if there's any other approaches/ideas/tweaks that would optimize the code please lemme know to better help me learn.

    Once again, thanks guys for your replys, and knowledge, it's really really appreciated (more than you know!), and greatly helps my self-education of Java and computer programming.

  5. #5
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,306
    Rep Power
    25

    Default

    1 - it doesn't have to be in the constructor but should be placed somewhere so that it is executed before it is needed/used. The Constructor is a good place.
    2- Read a textbook for the definitions you'll need to discuss program layout and syntax. main starts with lower case letter.
    Java is case sensitive so watch your spellings.

    Refering to line numbers in your code will be a maintenance problem to keep them up to date.

Similar Threads

  1. Question mark colon operator question
    By orchid in forum Advanced Java
    Replies: 9
    Last Post: 12-19-2010, 08:49 AM
  2. What is next to Swing
    By javaplus in forum AWT / Swing
    Replies: 1
    Last Post: 01-13-2008, 10:16 PM
  3. AWT or Swing
    By bugger in forum AWT / Swing
    Replies: 4
    Last Post: 11-22-2007, 09:44 AM
  4. map javax.swing.text.Element to javax.swing.text.View
    By elizabeth in forum New To Java
    Replies: 1
    Last Post: 07-30-2007, 07:02 PM
  5. swing?? why use it
    By javaforme44a in forum AWT / Swing
    Replies: 3
    Last Post: 07-18-2007, 07:51 AM

Posting Permissions

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