GUI/Swing

Hello,
I'm trying to get the hang of GUI and Swing. I post the code of the concerned class (and a screenshot), but I think reading the comments will suffice.
Short story: It works removing posts with the remove button, because then I am able to backtrack with .parent(). But with the popup menu, this won't work (I suspect it is a stupid method anyway) although the panel doesn't object when I "add" the popupmenu.
I suspect the code is a mess in other respects as well; I know OO in theory but have almost none experience, so be patient but feel free to give hints : )
Dump: http://s3.postimage.org/350d6da23/dump2.png
package itemframe;
import java.text.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class ItemPanel extends JPanel {
     private JPopupMenu popMenu = new JPopupMenu("Edit");
     private JLabel topic;
     private JLabel category;
     private JLabel description;
     private JLabel priority;
     private JLabel date;
     private class EventHandler implements ActionListener {
          public void actionPerformed(ActionEvent event) {
               String command = event.getActionCommand();
               ItemFrame origoFrame;
               ItemPanel origoPanel;
               if (event.getSource() instanceof JButton) {
                    JButton origoButton = (JButton)event.getSource();
                    origoPanel = (ItemPanel)origoButton.getParent().getParent().getParent();
                    origoFrame = (ItemFrame)origoButton.getTopLevelAncestor();
                    if (command.equals("Edit")) origoPanel.popMenu.show(origoButton, 5, 5);
                    else if (command.equals("Remove")) origoFrame.removeItem(origoPanel);
               else if (event.getSource() instanceof JMenuItem) {
                    JMenuItem origoMenuItem = (JMenuItem)event.getSource();
                    // HERE I don't succeed in getting origoPanel/Frame as above
                    // as I get null if I try the same method
                    if (command.equals("Remove")) ; origoFrame.removeItem(origoPanel);
                    else if (command.equals("Description")) {
                         String eventName = JOptionPane.showInputDialog(origoFrame, "Description:", "");
                         setDescription(eventName);
                         origoFrame.validate();
     public void setDescription(String description) {
          this.description.setText(description);
     public ItemPanel() {
          EventHandler eventHandler = new EventHandler();
          (popMenu.add("Description")).addActionListener(eventHandler);
          popMenu.add("Topic");
          popMenu.add("Category");
          popMenu.add("Date");
          popMenu.add("Priority");
          popMenu.addSeparator();
          java.net.URL imgURL = ItemPanel.class.getResource("removeSmall.png");
          ImageIcon removeIcon = new ImageIcon(imgURL);
          (popMenu.add(new JMenuItem("Remove", removeIcon))).addActionListener(eventHandler);
          add(popMenu);
          topic = new JLabel("Topic");
          category = new JLabel("Category");
          description = new JLabel("Description of event");
          priority = new JLabel("0");
          Date now = new Date();
          date = new JLabel(DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM).format(now));
          setBorder(new LineBorder(Color.lightGray, 1));
          imgURL = ItemPanel.class.getResource("edit.png");
          ImageIcon editIcon = new ImageIcon(imgURL);
          JButton editButton = new JButton("Edit", editIcon);
          JButton removeButton = new JButton("Remove");
          removeButton.addActionListener(eventHandler);
          editButton.addActionListener(eventHandler);
          BorderLayout innerBorder = new BorderLayout();
          innerBorder.setHgap(5);
          JPanel inner = new JPanel(innerBorder);
          GridLayout buttonsGrid = new GridLayout(2, 1);
          buttonsGrid.setVgap(5);
          JPanel data = new JPanel(new GridLayout(5, 1));
          data.add(topic);
          data.add(date);
          data.add(category);
          data.add(priority);
          data.add(description);
          JPanel buttons = new JPanel(buttonsGrid);
          buttons.add(editButton);
          buttons.add(removeButton);
          inner.add(data, BorderLayout.WEST);
          inner.add(buttons, BorderLayout.EAST);
          add(inner);
}Edited by: 831834 on Jan 27, 2011 10:56 AM

Why all of that complicated getParent() anyway? EventHandler is an inner class, so you have full access to the variables of the outer class. ItemPanel.this gives you access to the ItemPanel that encloses the EventHandler instance. +origoPanel is always the same as ItemPanel.this+ . If getTopLevelAncestor is properly giving you the frame, then the following should work.
if (event.getSource() instanceof JButton) {
   if (command.equals("Edit")) {
     JButton origoButton = (JButton)event.getSource();
     popMenu.show(origoButton, 5, 5);
   else if (command.equals("Remove")) {
      // Might also be able to use ItemPanel.this.getParent() instead of getTopLevelAncestor()?
      // I don't know your full hierarchy.
      ((ItemFrame)ItemPanel.this.getTopLevelAncestor()).removeItem(ItemPanel.this);
else if (event.getSource() instanceof JMenuItem) {
   if (command.equals("Description")) {
      String eventName = JOptionPane.showInputDialog(origoFrame, "Description:", "");
      setDescription(eventName);
      ((ItemFrame)ItemPanel.this.getTopLevelListener()).validate();
}If Remove should do the same regardless of whether it's from the JButton or from the JMenuItem, then you don't need to repeat that "if" check twice--just do the check for "Remove" outside the loop. If you are using action commands, you probably don't need to test the type of the source (JButton vs. JMenuItem), anyway, unless you have the same action commands on both types that should do different things based on type (if they should do different things, it's probably a bad design). Then you only need the source if you actually need to act on the source. In your code, I don't think you need to know that origoButton is a JButton--just a JComponent or Component or something (whatever the first parameter of JPopupMenu.show is).

Similar Messages

  • To intercept all exception of GUI Swing?

    Blank I tried a method in order to intercept all the exception that can be verified to the inside of a GUI Swing without necessarily to mapping all the code of blocks try & catch.
    I was just trying an interface of the class java.lang.Exception in order to try to make a override of the methods, if there is someone that has already experienced this technique.
    THANKS

    bah, you can throw every exception to the caller method,
    and that one can forward it, too
    I have never tried this, but maybe you can forward all exceptions to
    the main() method, and there should be enough only one try-catch block.
    but then you have declare most of your methods to throw something.
    I advise you to handle errors at least in a very primitive manner,
    only using System.err if you do not want to create some user-friendly,
    GUI-based error treatment.
    println is very good for debugging and development, use it, really.
    First, you can ignore all the exceptions in your code,
    and if something goes wrong, just read your console output
    for more debug info.

  • GUI swing objects mass quantity color change(fore&back)

    Alright here is what I am trying to achieve:
    I have almost 300 items in my GUI,
    I want to change the font and background color of EVERYTHING at once.
    I added the items to the GUI for my little application over the course of a few weeks of scripting so it was easy to add line after line of:
    *****.setBackGround(back);
    *****.setForeGround(fore);
    where back and fore are colors set via some menu option and are being changed very often.
    I am thinking "look and feel" is the way to go, but before I learn something that may not help me I would like a little advice.
    I tried making an arraylist of type Object and then calling them in a loop but alas java doesn't believe me that every object in the array has both setBac... and setFore...
    any advice/comments are appreciated.
    -Jake(Actingrude)

    I guess before I continue looking around for a solution, am I right to assume that a "look and feel" would effect ALL of my swing components and have the ability to set the color scheme of everything with just 1 method call, rather than two for each swing object?Create a [url http://sscce.org]SSCCE to test the suggestions that have been made. If you have problems then you can post your SSCCE and we might be able to help you out.
    The basic code for changing the properties of all text fields should be something like:
    UIManager.put("TextField.foreground", new ColorUIResource(...));
    UIManager.put("TextField.background", new ColorUIResource(...));You would need code like that for all components you wish to change.
    Read the section from the Swing tutorial on [url http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html]How to Set the Look and Feel. I think you need to invoke the updateComponentTreeUI() method.

  • GUI/swing application doesn't appear under W2K

    Hi, all,
    I wrote a Java GUI application with JDK1.4.1_01, when I run it on Win2K Professional (SP3) the
    GUI doesn't appear without any exception.
    But when I ran the same application under XP and Win98, the GUI application run ok and the GUI appears.
    What is the problem?
    regards,
    Adam

    First I thought you had several jre's installed and windows used the wrong one when you type java ...
    Now I think it has to be someting wrong in your code.
    Can you try someting that should work?
    Compile and run the following code:
    javac testPanel.java
    java testPanel
    import javax.swing.*;
    import java.awt.*;
    public class testPanel extends Thread{
         public static void main(String[] args) {
              try{
                   // get out of the static context
                   new testPanel().start();
                   new testPanel().start();
                   new testPanel().start();
              }catch(Exception e){
                   e.printStackTrace();
         public void run(){
              // Create a container with a flow layout, which arranges its children
              // horizontally
              Panel panel = new Panel();
              // A container can also be created with a specific layout
              panel = new Panel(new FlowLayout(FlowLayout.RIGHT));
              // Add several buttons to the container
              panel.add(new Button("A"));
              panel.add(new Button("B"));
              panel.add(new Button("C"));
              // Create frame with a text area in the center
              Frame frame = new Frame();
              Component comp = new TextArea();
              frame.add(comp, BorderLayout.CENTER);
              // Add the container to the bottom of the frame
              frame.add(panel, BorderLayout.SOUTH);
              // Show the frame
              int width = 300;
              int height = 300;
              frame.setSize(width, height);
              frame.setVisible(true);
    }

  • GUI/swing application doesn't appear under Win2K

    Hi, all,
    I wrote a Java GUI application with JDK1.4.1_01, when I run it on Win2K Professional (SP3) the
    GUI doesn't appear without any exception.
    But when I ran the same application under XP and Win98, the GUI application run ok and the GUI appears.
    What is the problem?
    regards,
    Adam

    I wrote a Java GUI application with JDK1.4.1_01, when
    I run it on Win2K Professional (SP3) the
    GUI doesn't appear without any exception. Maybe it 's shy. Have you thought about coaxing it out with a little biscuit?

  • GUI swing class help needed

    hi, i just need some help to create a bar kind of object (like a bar of battery shown in mobile phones).
    the information i have is in percentage from 0-100%. and what i have planned is that:
    the bar will be split into four:
    from 0-25: one bar will be colored green.
    26-49 "
    50-74 "
    75-100
    the bar information will be from the battery left percentage as mentioned above.
    also if the battery is below 25% the GUI should give an alert (possible red screen with big "alert"..)
    I started doing the frame but got stuck on the bar. pls can you help.
    im looking for nothing complex like make it very accurate to each value of infor. thanks

    Hi,
    You can use a JProgressBar (min 0 max 4)...
    Or make a custom bar with some filled rectangles ...
    Olek
    Edited by: Olek on Oct 11, 2007 10:01 AM

  • Help on Gui(Swing) design

    OK here is my situation:
    Scenario:
    I have a class i call mainwindow: it holds three other classes. TopPanel, midpanel, and bottompanel, all of which only hold your basic components(Jbuttons, JtextArea...so on). The main window just sets all these up and places them in the mainwindow. Also, i have another class called mainListener which implements an ActionListener which is its sole purpose is to react to actions. The important factor here is that whenever an item in the toppanel or midpanel performs an action, the action will put text on the bottom panels textArea.
    My questions are:
    1) Is this design practical? or is the overkill, too many class for one simple thing.
    2) One problem i have been having is getting the class to talk to eachother, when i click on and item, the mainListener class does listen, but i can't return an action to the bottomPanel to write to its textarea. How do i make communication Happen.
    3) One solution i thought about was to forget about the separate listener class, implement the listener directly on the mainWindow class, and finally use fully qualified names to reference to the separate object in the window.
    Another solution i was thinking about is letting each of the individual class implement its own ActionListener interface, but how would i go about letting them communicate with each other?
    If anyone has any suggestions, please share them with me. Any input to help in my design would be greatly appreaciated. Thanks in advanced.

    In your bottom panel class, add a method which will receive the text and then add it to the JTextArea.
    public void setBottomText(String s)
         myTextArea.setText(s);
    }and call it from the listener class.
    Mark

  • Non-gui/swing event in java possible ?

    Dear Members :
    Is it possible in java to raise and catch business events, as is possible in other languages, I know.
    For instance - when I create a vehicle instance, that will trigger an event which will add that vehicle to vehicle_list(List) - something like that ? I am aware of Observer/Observable, but that is only if the source changes.
    Could someone please explain with syntax if that's possible, I mean, tackling any kind of business events in java ?
    Thanks in advance
    Atanu

    There is no out of the box event model... and be careful how you phrase these things... and in you are pedantic enough the pattern reveals itself.
    What notifies the sales people that a new car is ready? It's not the Car itself is it? How about the factory? You're getting warmer... Who else does the factory tell? Maybe the tax man?
    Yeah... Observe/r/able was a good first thought.
    And... You might want to look into the Spring framework... I think you're groping for AOP.
    Cheers. Keith.

  • SWING-gUI

    i have heard that for building complex GUI Swing is better than SWT.
    Is it so. if why?
    What do we mean by abstraction level

    i have heard that for building complex GUI Swing is
    better than SWT.I heard the opposite. shrug
    What do we mean by abstraction levelThe level of the abstract (as opposed to detailed) view of a proble.
    Sincerely,
    your dictionary.

  • Swing-complex GUI

    i have heard that for building complex GUI Swing is better than SWT.
    Is it so. if why?
    What do we mean by abstraction level

    Dear Josh,
    This is a 64K question - The answer depends on whom you asked the question and what "is better" means. Sun's fans will definetely say Swing is easier to learn and use. IBM's fans and the Eclipse community would of course love SWT better.
    The abstraction level in Swing - the hierachy of classes / interfaces to represent elements in the GUI problem space - is flexible but yet general enough that programmers are not "constrained" to the a particular type of design.

  • Facing problem in Java Swing

    Hi Sir,
    I am using a java GUI Object for taking user name and password (in fields of user name and password) and would like to send the information to a server (in the form of Xml file) on the click of 'Ok' button. The database of registered user is stored on server. If the entered users name or passwords are not correct, the server will send a failure notification to the client (terminal where we typed user name and password). If this is successful, it gives a success notification.
    I am doing this using Swings. Also I want all the communication taking place between the server and the client in the form of XML files. being a new to Swings I am facing certain difficulty.
    I will appreciate your suggestions and help in this regard.
    Thanks and regards,
    Sarib

    817439 wrote:
    Could you please tell me under which category I should post this query. I could not find JAVA Swing section anywhetre in forum home.Steps
    1. Determine what it is that you want the database to do and what you want your code to do. This does NOT involve writing code.
    2. Learn JDBC
    3. Write JDBC classes that does ONLY the database functionality from 1. If it has GUI (swing) code then it is wrong.
    4. Unit test it.
    5. Learn Swing
    6. Write GUI (swing) code that uses the code from 3.
    7. Test it.
    There is a forum for JDBC - steps 2,3,4.
    There is a forum for Swing - steps 5, 6, 7.

  • Creating GUI component that includes other components

    Hello, I need to create an UNIVERSAL FORM (panel) consisting of several textboxes and labels. These textboxes and labels will be defined in XML. I want it as a GUI JavaBean. It should be made from a panel with some layout and it should consist other components. Here are my questions:
    1) What class to derive from? JPanel?
    2) Well, when I override a GUI Swing component I must implement a paint method but this is a bit strange. I just want to set up the textboxes -- I do not need any special painting. A question appears -- is JavaBean technology good for this situation? Is there any better solution?

    I mean why this doesn`t work:
    public class Uniform extends JComponent implements
    Serializable {
         private String xmlContent;
         private int type;
         private JPanel panel;
         public Uniform() {
              panel = new JPanel(new GridLayout(1,2));
              panel.add(new JTextField("A"));
              panel.add(new JTextField("B"));
         public void paint(Graphics g) {
              panel.paint(g);
    }Is it a good solution? How would you solve the
    problem?
    Thanks for your ideas.If you mean by 'dont' work' that your text boxes and panel doesn't appear, then it's because you're missing this line in your constructor:
    public Uniform() {
      this.add (panel, BorderLayout.CENTER);
    }Regards,
    Devyn

  • GUI Developer job in Armonk, NY

    Hello everybody, i am looking for a GUI/Swing/Struts Developer for a financial services firm in Armonk, NY. This would be a 12 month contract, however it is likely to be extended. If you have a minimum of 2 years Java software development and you are a expert in GUI, SWING, Struts and have a valid work permit for the States, please contact me through email: [email protected]

    http://java.sun.com/siteinfo/conduct.html
    I quote -
    There is no place in these message boards for slander, third-party commercial advertisements (including links) or unauthorized information disclosure.
    1.2 While it is not our intent to monitor Your online communications, Sun reserves the right to edit or remove content that we become aware of and determine to be harmful, offensive or otherwise in violation of these Terms. Sun may also remove Content that contains third-party commercial advertisements, is inaccurate or includes unauthorized disclosure or personal information. Violation of these restrictions ("Restrictions") may also result in the termination or suspension of your account. These Restrictions apply to all content provided to or through the Services, including email messages, newsgroup postings, chat, and personal or business web pages.

  • Socket write in GUI Client

    I have a GUI Swing client that is communicating with a Server with Sockets.
    Currently, when a message needs to be sent ( Socket.write ), I am just passing the message to my thread-safe sendMessage() method.
    I have an application currently calling this from the Event Thread without issue, but I have heard that this could create a possible dead-lock, but I haven't been able to pinpoint the reasoning behind this.
    What pitfalls occur if this method, which writes to the Socket's OutputStream directly, is called from the GUI Event Thread?
    Thanks in Advance.

    Thank you all for the input.
    I think what I will do is dispatch a new Thread to do the sendMessage if it is invoked from within the GUI Event Thread.
    Which would be better? Create a new anonymous thread or use SwingUtilities.invokeLater ?
    1)
         void actionPerformed( ActionEvent e )
                 new Thread( new Runnable() { void run() { sendMessage(data); } } ).start();
         }2)
         void actionPerformed( ActionEvent e )
                 SwingUtilities.invokeLater( new Runnable() { void run() { sendMessage(data); } } );
         }

  • Swing Form = JNI = Delphi DLL = Delphi Form works but small issue

    Hi all
    I'm trying to call a delphi dll from a java form.
    This is the procedure
    swing button action => jni => call procedure in delphi dll => create delphi formThis works for me but the problem is when click the button it create the delphi form by calling the dll but it's stucked for ever(frame not the whole form). Never return to do something else. Means that it's stay remain in clicked postion.
    I do not know whether the problem exist with the swings' single threaded behavior. I have used another thread to call natives. But the problem persist.
    So can any one suggest any answer.
    Wish U all HAPPY NEW YEAR!
    Here is the compact code
    native calls
    public class LoadLib
        public native void createForm();
        public native void forward();
        static
            System.loadLibrary("testjni");
    }calling class
    import javax.swing.*;
    import java.awt.event.ActionEvent;
    import java.awt.Container;
    import java.awt.event.ActionListener;
    public class RUNClient extends JFrame {
         JFrame frame = new JFrame();
         JFrame frame2 = new JFrame();
         LoadLib lib = new LoadLib();
         JButton b1 = new JButton("OK");
         JButton b2 = new JButton("Forwad");
         private RUNClient() {
              frame.setLayout(null);
              frame.add(b1);
              frame.add(b2);
              b1.setBounds(110, 80, 80, 20);
              b2.setBounds(110, 50, 80, 20);
              b1.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        lib.createForm();     // create form in dll
                        // after this call frame is stucked
              b2.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        lib.forward();          // call another native to do some in created form
                        // this cannot be called because frame is stuck
              // other frame operation
         public static void main(String args[]) {
              new RUNClient();
    }delphi code
    library testjni;
    uses
      JNI,Unit1;
      var
      f : TForm1;
    procedure Java_LoadLib_createForm(PEnv: PJNIEnv; Obj: JObject); {$IFDEF WIN32} stdcall; {$ENDIF} {$IFDEF LINUX} cdecl; {$ENDIF}
    begin
    try
      f := TForm1.Create(nil);
      f.ShowModal;    
       finally
         f.Free;
         f.Release;
       end;
    end;
    procedure Java_LoadLib_forward(PEnv: PJNIEnv; Obj: JObject); {$IFDEF WIN32} stdcall; {$ENDIF} {$IFDEF LINUX} cdecl; {$ENDIF}
    begin
    Form1.Top := Form1.Top - 50;
    end;
    exports
      Java_LoadLib_createForm,
      Java_LoadLib_forward;
    begin
    end.

    Hi deshan,
    To realize the problem you should know principles of Java GUI (SWING or AWT) implementation in JVM:
    1) Java GUI is implemented in a single thread with EventQueue static object, which is created with JVM when Java Application GUI starts.
    2) Any painting or event calls are done on this thread (the same approach was used by Microsoft in .NET GUI).
    3) While your code handles an event EventQueue waits for return from your event method. Some calls to GUI components can stick the whole Java GUI (this is the problem of SUN Java architecture, I did not have this in Microsoft Java). To avoid this problem you should use InvokeLater method that works like PostMessage to the main thread in Windows Application. InvokeLater generate an event that is posted to EventQueue and your code passed to InvokeLater method will be executed asynchronously in GUI Thread.
    4) If you call any Java (SWING or AWT) component from the thread other than EventQueue thread you must synchronize these calls with locks by the object got from getTreeLock() method of the component you call. But you should be accurate with locks because they can cause deadlocks.
    Your code does not return from Click Event where you try to create some GUI component but EventQueue is still waiting for “return” and the main GUI thread is suspended.

Maybe you are looking for

  • Displaying fields from a Z Table on CRM UI

    Hello Experts I am trying to display fields from a custom table onto a CRM UI form view. 1. I created a custom GENIL root object & Search object ie. ZCUSTOMER. & ZCUSTSEARCH 2. Tested this in the GENIL BROWSER to ensure that I could enter update valu

  • Variable to use as list of numbers for "in" clause

    Hello. I am writing a proc that needs to dequeue an unknown number of messages from an advanced queue, and then query a standard table, returning a cursor. I have coded most of it, but I run into trouble when there is more than one message to be dequ

  • Clock time issue in c3560 Logs:

    Hi my name Izhar, I am facing the issue with C3560 switch. i have set the clock which is showing correctly but in Logging it's getting the incorrect time. please any one help. acc-ingles-up-00#sh clock 10:08:36.366 UTC Thu Jul 5 2012 below the logs :

  • Skype to skype problem

    Hello skypers! Im having a problem with my skype after getting forced into updating my windows from 8 to 8.1. It appears that my skype have some latency connecting to calls - not only incomming calls but also my own. Scenerio: I am calling a friend w

  • Getting external swf to stay visible?

    Hi I have an external swf that contains a button that controls my main swf's timeline. I can get it to navigate fine, but as soon as it navigates, my external swf disappears, because my main swf is no longer on the frame my external swf was imported