Swinging to nowhere...


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 11 of 11

Thread: Swinging to nowhere...

  1. #1
    Join Date
    May 2005
    Posts
    115

    Swinging to nowhere...

    This is just a test program..

    What i want to do is that when the user clicks Exit in the menu bar, a string or a label will appear in panel 2...but it doesn't work...what is wrong with my code?
    Code:
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import java.awt.BorderLayout;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import javax.swing.JMenu;
    import javax.swing.JMenuItem;
    import javax.swing.JMenuBar;
    import javax.swing.JLabel;
    
    public class test2 extends JFrame{
    	private static final int WIDTH=300;
    	private static final int HEIGHT=200;
    
    	private JPanel p1=new JPanel();
    	private JPanel p2=new JPanel();
    
    	public test2(){
    		super();
    		setSize(WIDTH,HEIGHT);
    		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		setLayout(new BorderLayout());
    
    		JLabel l=new JLabel("Label 1");
    		p1.add(l);
    
    		JMenuItem exit=new JMenuItem("Exit");
    		exit.addActionListener(new ActionListener(){
    			public void actionPerformed(ActionEvent e){
    				//System.exit(0);
    				JLabel l2=new JLabel("Exit clicked");
    				p2.add(l2);
    			}
    		});
    	
    		add(p1, BorderLayout.NORTH);
    		add(p2, BorderLayout.SOUTH);
    
    
    
    		JMenuBar bar=new JMenuBar();
    		bar.add(exit);
    		setJMenuBar(bar);
    	}
    
    	public static void main(String[] args){
    		test2 t=new test2();
    		t.setVisible(true);
    	}
    }

  2. #2
    Join Date
    Jan 2005
    Posts
    61
    You hadn't implemented the ActionListener class, and also hadn't used the getSouce() method that comes with it. Here is how I would do it:
    Code:
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import java.awt.BorderLayout;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import javax.swing.JMenuItem;
    import javax.swing.JMenuBar;
    import javax.swing.JLabel;
    
    public class Test2 extends JFrame implements ActionListener{
        
            private static final int WIDTH=300;
            private static final int HEIGHT=200;
    
            private JPanel p1=new JPanel();
            private JPanel p2=new JPanel();
            private JLabel l2 = new JLabel("Exit Clicked");
            private JLabel l=new JLabel("Label 1");
            private JMenuItem exit=new JMenuItem("Exit");
            
            public Test2(){
                super();
                setSize(WIDTH,HEIGHT);
                setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                this.getContentPane().setLayout(new BorderLayout());
                
                p1.add(l);
                this.getContentPane().add(p1, BorderLayout.NORTH);
                this.getContentPane().add(p2, BorderLayout.SOUTH);
    
    
    
                JMenuBar bar=new JMenuBar();
                bar.add(exit);
                setJMenuBar(bar);
                setVisible(true);
    
                
                exit.addActionListener(this);
            }
                    
                    
                        public void actionPerformed(ActionEvent e){
                            if(e.getSource()==exit) {
                                //System.exit(0);
                                p2.add(l2);
                                repaint();
                                validate();
                            }
                        }
                
        
                
        
    
        public static void main(String[] args){
                Test2 t=new Test2();
        }
    }
    I'm sure there are neater ways of doing it, but this works anyway

  3. #3
    Join Date
    May 2005
    Posts
    115
    ic..thx...another question...

    I have already finished coding the application. Now i want to create a GUI for it. Currently everything is displayed in dos. How do i convert all the System.out.println messages to my GUI without totally messing up the rest of the code?

    I've tried creating a panel in my GUI class as static and final..and with my application class changing System.out.println into GUI.display.setText ..but it doesn't work..

    2) Is there another way to create text in GUI besides label? Especially when i have a whole chunk of output i want to display in my GUI...

    thx in advance...

  4. #4
    Join Date
    May 2005
    Posts
    115
    will808, what does repaint() and validate() do?

  5. #5
    Join Date
    Jan 2005
    Posts
    61
    OK, firstly repaint() and validate() might not be necessary in what I posted above - you could try commenting out those lines and see if it still works. Basically it repaints the contentPane (or whatever panel you tell it to repaint). I'm still learning swing, but I find it helps sometimes - and certainly never seems to hurt.

    So to move your System.out messages into the GUI, you have a couple of options. I'm not too sure what you're aiming to achieve, but some or all of the below might help:

    You need a component to display the text - this could be label, TextField, TextArea or lots of things. Assuming your output is all text, you could look at the following:

    aJLabel.setText("Something has happened");
    aJTextField.setText("Something else has happened");
    aJTextArea.setText("And now something else which is so big I'm going to need a huge area to fit all the information into");

    Obviously you need to declare these components before you use them, and add them to your panel(s) before adding the panel(s) to the contentPane, but all you are really doing is setting the text in a component rather than using System.out.

    It sounds as though you have the rest of it running, so I'm guessing your output messages are related to events? If that's the case, wherever you have a System.out, just comment out that line and add one of the above.

    If you want to display other data types than Strings, you'll need to cast the data type to a String before you can add it as a String to the component.

  6. #6
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560

    Other ways.

    Just a short remark or two, ActionListener is not a class, its an
    interface, there is a slight difference

    And, just for stating the obvious; the getSource() method comes with
    all java.util.EventObject descendants, like the ActionEvent.

    repaint() invokes a component's paint/update methods, the component
    is redrawn. The same thing happends if you minimize/restore a frame.

    validate() recalculates the bounds of the "innards" of a container and
    repaints it if required...
    but hey, haven't you got any java doc available.?

    Here is a basic setup that uses a textfield for user input and a
    non editable textarea for output.
    Code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    
    public class GUIInOut extends JFrame implements ActionListener {
      BorderLayout borderLayout1 = new BorderLayout();
      BorderLayout borderLayout2 = new BorderLayout();
      GridLayout gridLayout1 = new GridLayout();
      JPanel outPan = new JPanel();
      JPanel inputPan = new JPanel();
      JButton enterBtn = new JButton();
      JTextField inputTF = new JTextField();
      JScrollPane outScroller = new JScrollPane();
      JTextArea outTA = new JTextArea();
    
      public GUIInOut() {
        try {
          jbInit();
          enterBtn.addActionListener(this);
          outTA.setText("Enter something\n");
        }
        catch (Exception e) {
          e.printStackTrace();
        }
      }
      /**
       * Handle button click
       */
      public void actionPerformed(ActionEvent e) {
        if (e.getSource() == enterBtn) {
          String entry = inputTF.getText().trim();
          if (entry.length() == 0) {
            JOptionPane.showMessageDialog(this,
                                          "That was nothing",
                                          "No Input",
                                          JOptionPane.ERROR_MESSAGE);
            return;
          }
          else {
            report(entry);
          }
        }
      }
    
      /**
       * "Processing" user input
       */
      private void report(String txt) {
        outTA.append("You entered:\n" + txt +"\n");
        outTA.append("Enter something more\n");
      }
    
      /**
       * GUI setup
       */
      private void jbInit() throws Exception {
        this.getContentPane().setLayout(borderLayout1);
        enterBtn.setText("Enter");
        inputPan.setLayout(borderLayout2);
        outPan.setLayout(gridLayout1);
        outTA.setBackground(Color.lightGray);
        outTA.setEditable(false);
        this.getContentPane().add(outPan, BorderLayout.CENTER);
        outPan.add(outScroller, null);
        outScroller.getViewport().add(outTA, null);
        this.getContentPane().add(inputPan, BorderLayout.SOUTH);
        inputPan.add(inputTF, BorderLayout.CENTER);
        inputPan.add(enterBtn, BorderLayout.EAST);
      }
    
      public static void main(String[] args) {
        GUIInOut gio = new GUIInOut();
        gio.setBounds(20, 20, 400, 300);
        gio.addWindowListener(new WindowAdapter() { // ensure proper termination
          public void windowClosing(WindowEvent e) {
            JOptionPane.showMessageDialog(null,"CYA");
            System.exit(0);
          }
        });
        gio.setVisible(true);
      }
    }
    eschew obfuscation

  7. #7
    Join Date
    Jan 2005
    Posts
    61
    I'll get back in my box

  8. #8
    Join Date
    May 2005
    Posts
    115
    Quote Originally Posted by will808
    Obviously you need to declare these components before you use them, and add them to your panel(s) before adding the panel(s) to the contentPane, but all you are really doing is setting the text in a component rather than using System.out.
    So does it mean that after the panel has already been added to the frame i can't edit the panel with setText() etc? meaning the code frame.add(something) has to be at the end of the code?

  9. #9
    Join Date
    May 2005
    Posts
    115
    Quote Originally Posted by will808
    It sounds as though you have the rest of it running, so I'm guessing your output messages are related to events? If that's the case, wherever you have a System.out, just comment out that line and add one of the above.
    However, all my System.outs are spread across a few classes. They are not centralized in 1 class.

    Does that mean that for my GUI class, i should set the displaying label, textarea or watever as static, so that the System.outs from those classes can access using
    Code:
    GUI.displayLabel.setText("Something to display..")
    ?

  10. #10
    Join Date
    May 2005
    Posts
    115
    To sjalle,

    Can you explain these methods?

    1) printStackTrace();
    2) trim();
    3) Can u explain the 4 arguments for JOptionPane? Only the String "There was nothing" was used, where was "No input"?

    Thx sjalle...

  11. #11
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560

    One thing at the time...

    Obviously you need to (...) add them to your panel(s) before adding the panel(s) to the contentPane....
    Wrong, you can add a container into another container, and so forth, and
    then add components/containers into these again, in any order you choose,
    but the layoutmanagers have to be set for a container prior to adding
    any components/containers into it.

    The setText method can be invoked every time you want to set/change some
    text in a text component. A panel is not a text component, it is a container,
    like a frame, scrollpane, tabbedpane etc. The method has no relevance for
    the GUI setup. The method is there for using the GUI.

    Does that mean that for my GUI class, i should set the displaying label, textarea or watever as static
    Two ways to do this (at least).

    1: supply the other classes with constructors or setter methods for handing
    over the pointer (variable name) of the GUI class, and declaring the
    report method in the code I posted as public. E.g. if you in the
    main method do this:
    Code:
    GUI gui=new GUI();
    OtherClass oc=new OtherClass(gui);
    and in OtherClass you code like:
    Code:
    public class OtherClass {
      private GUI theGUI=null;
      public OtherClass (GUI theGUI) {
        this.theGUI=theGUI;
      }
      private void someMethod() {
        theGUI.report("This is a message from OtherClass");
      }
      .
      .
    }
    2. You could declare outTA and the report method as static and use the
    GUI report method anywhere in the application like GUI.report("blabla");

    printStackTrace is a public method that applies to all exceptions, it
    prints out the calling stack right down to the statement where the exception
    occurred.

    trim() is a String method, it removes all leading and trailing blanks. It
    is especially important when converting numeric strings to numbers, - the
    static parse<type> methods of Integer, Float and Double throws
    NumberFormatException when they encounter these blanks in the number
    string.

    JOptionPane.showMessage(...)
    param1: the "parent" component (null if there is none),
    param2: the message
    param3: the dialog titlebar text (you missed that one..., check again )
    param4: the message type


    PS: again I advise you to study the free and excellent javadoc from Sun, and
    how to use it.
    Last edited by sjalle; 09-05-2005 at 04:07 AM.
    eschew obfuscation

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center