ActionListener confusion

Hi all, I'm new to the Java world, and was wondering if you could give me a few pointers on my program. I'm having a difficult time understanding the object oriented programming, even though I've been through the tutorial here several times. Any help would be greatly appreciated!
I'll set up the scenario before I ask any questions. I'm writing an applet, and I have two separate classes, one is called "testingg" and the other is called "fight". In the testingg class, I define 2 panels. The first panel has two buttons. The second panel is set up with a cardLayout, and switches it's content when you push one of the two buttons located in the first panel. At first, everything worked out great, but as I started adding more and more content to my program, it started getting a little out of control length wise, and I decided to put some of my code into the "fight" class. Now here's my long list of problems:
1. While experimenting with the program, I added a total of 6 buttons to the left panel in my "testingg" class. Each button corresponded to a separate 'card' in my cardLayout. So what I ended up having was 6 buttons, with 6 different actionListeners, with 6 different cards. Even with only 6 buttons, it was getting tedious to write a new event handler for every single button. Is there a way that I could use just one ActionListener for all of my buttons? If so, how does this work?
2. As I stated before, I decided to start putting some of my code into my "fight" class, to reduce some of the confusion in my large program. Lets say I place all of my ActionListeners into the fight class, but leave everything else in my testingg class. What happens if I want to do more than just chaning the 'card' when a button is pressed, and I want to let's say update two textAreas and a label. Is it possible, using just one ActionListener for several different buttons, to update the two textAreas, the label, and change the card? (Sorry this entire question is probably very confusing)
3. I've heard about different patterns such as Observer/Observable, mediator, etc. Would any of these help me out with my current situation? If so, where would I find a good tutorial on these subjects?
Once again, any help would be greatly appreciated, and let me know if I need to clarify anything further.
Thanks, huja

1. While experimenting with the program, I added a
total of 6 buttons to the left panel in my "testingg"
class. Each button corresponded to a separate 'card'
in my cardLayout. So what I ended up having was 6
buttons, with 6 different actionListeners, with 6
different cards. Even with only 6 buttons, it was
getting tedious to write a new event handler for every
single button. Is there a way that I could use just
one ActionListener for all of my buttons? If so, how
does this work? Yes. Write an ActionListener class that knows how to handle 6 buttons and use an instance of this class in the addActionListener() of the buttons. For example, the actionPerformed() would have case statements for each button.
Or, you might be able to write a class with functionality that allows an instance of it to be used with any button since it sounds like you do about the same thing with each button. For example, a variable in the class would reference the card it needs to manage, passing the card to the class in a constructor. To me, this seems to fit what you are trying to do. You might want to extend the Button class to achieve this.
2. As I stated before, I decided to start putting
some of my code into my "fight" class, to reduce some
of the confusion in my large program. Lets say I
place all of my ActionListeners into the fight class,
but leave everything else in my testingg class. What
happens if I want to do more than just chaning the
'card' when a button is pressed, and I want to let's
say update two textAreas and a label. Is it possible,
using just one ActionListener for several different
buttons, to update the two textAreas, the label, and
change the card? (Sorry this entire question is
probably very confusing)Yes with (for example) case statements for each button inside the actionPerformed method.

Similar Messages

  • Can I use a for loop to add anonymous ActionListener objects?

    I have a setListener() method that has the following inside:
    for(int k = 0; k < buttons.length; k++)
        buttons[k].addActionListener(new ActionListener()
            public void actionPerformed(ActionEvent e)
                g2.setColor(colors[k]);
    }I have a JButton array and a Color array and I was hoping I could add them quickly in one shot rather than manually adding an anonymous ActionListener 9 times (I have 9 components). It tells me I need to make k final for an inner class and when I tested it by removing the for loop and keeping k as a final integer, it works. Is there a medium such that I can achieve what I want more or less while respecting Java's syntax?
    Any input would be greatly appreciated!
    Thanks in advance!

    s3a wrote:
    The local variable exists on the stack for as long as the method is executing. Once the method ends, that variable no longer exists. The newly created object, however, can continue to exist long after the method has ended. So when it's referring to variable X, it cannot refer to the same X as the one in the method, because that variable may no longer exist.Sorry for picking on little details but I am still not fully satisfied.
    Earlier I questioned if the local variable changed, but now let's say that that variable no longer exists at all, why does that even matter if the inner class copied the value and is keeping it for itself? What do you mean? The variable that existed in the method ceased to exist when the method ended. The inner class, however, can continue to live on, and can continue to refer to what we see as the same variable. However, it obviously can't be the same variable, since, in the world of the inner class, it still exists, while in the world of the method, it does not.
    This is completely independent of whether the variable changes or not. Regardless or whether the variable changes we still need two copies--one that goes away when the method's stack frame is popped, and one that lives on as long as the inner object does.
    Then, because there are two copies, the designers decided that the variable has to be final, so that they wouldn't have to mess with the complexity of keeping two variables in sync.
    That explanation leads me to believe that there is no copy and that there is some kind of "permanent umbilical cord" between the inner class and the local variable.Wrong. There has to be a copy. How else could the inner class keep referring to it after the method ends?
    Also, does marking it as final force it to be a permanent constant "variable" even if it's not a field "variable"? Or, similarly, does making a "variable" final make Java pretend that it is a field "variable"?Making a variable final does exactly one thing: It means the value can't change after it's been initialized. This is true of both fields and locals.
    As for the "pointless" byte-counting, I really don't see how it's confusing unless you're an absolute beginner. If I see somebody using a byte, I assume they have a real reason to do so, not pointless byte-hoarding. Then when I see that it's just a loop counter, I wonder WTF they were thinking, and have to spend some time determining if there's a valid reason, or if they're just writing bad code. Using a byte for a loop counter is bad code.
    I could then ask, why are people not using long instead of int and saying that that's using int is too meticulous?Part of it is probably historical. Part of it is because at 4 bytes, and int is exactly on word on the vast majority of hardware that Java has targeted since it came out. 8-byte words are becoming more common (64-bit hardware) but still in the minority.

  • JComboBox event confusion: not enough generated? :-(

    Hi,
    I am slightly confused about the events generated by the combobox.
    I have a combobox and and actionlistener registered on it. If I programmatically use setSelectedIndex on the combobox, and event is generated and the actionlistener is triggered. If I do a setSelectedIndex on the same combobox within the code of the action listener, no event is generated, though the index does get updated. Though I am happy it doesn't generate that event, I don't understand why it doesn't. Anyone?
    Rene'

    Instead of using ActionListener you should use ItemListener for combo box. This is an example
    comboBox.addItemListener(new java.awt.event.ItemListener() {
         public void itemStateChanged(ItemEvent e) {
         try {
         JComboBox box = (JComboBox) e.getSource();
         System.out.println(box.getSelectedItem());
         } catch (ArrayIndexOutOfBoundsException exp) {}
    });Note: Item Listener only listens when you change something in Combo Box. If you click on a combo box, and selects the same value, item listeners doesn't call.
    Hope this helps.

  • Very confused beginner here...

    Hello everyone. I'm new to the board here. I am currently a junior meteorology major with a minor in computer science at Millersville University. To incorporate both my minor and major, I decided to make a computer program that scrolls weather watches and warnings across the bottom of a computer screen (much like they do on television). I am a beginner at Java, only using it for a few months. I really feel like I have bitten off more than I can chew with this program. However, I am dedicated in working through this problem. Below is a copy of the code I am using for this. I keep getting errors, however. I had it working perfectly, besides the fact that a) it never updated and b) it would never scroll more than one watch or warning, meaning it would just loop one over and over. I have also included the errors that I receive during this. Any help would be greatly appreciated. I am sorry if the code looks a bit trashy and disorganized. These are just some things, being a rookie, that I am going to have to learn how to clean up. Thanks
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.Timer;
    import javax.swing.*;
    import java.applet.Applet;
    import java.applet.AudioClip;
    import java.net.*;
    import de.nava.informa.core.ChannelIF;
    import de.nava.informa.core.ItemIF;
    import de.nava.informa.impl.basic.ChannelBuilder;
    import de.nava.informa.parsers.FeedParser;
    public class WxScroll extends JFrame implements ActionListener {
         private static final long serialVersionUID = 1L;
         int count = 0;
         JLabel scrollLabel;
         String scroll, watwarstring, text;
         Label label;
         ItemIF item;
         Component newText;
         String watwar[];
         String newscroll, oldText;
         ChannelIF channel;
         Collection items;
         final TimerTask task;
         java.util.Timer timercheck;
         ChannelBuilder channelb;
         URL url;
         public WxScroll() {
              final Color red = new Color(255, 0, 0);
              final Color yellow = new Color(255, 255, 0);
              final Color orange = new Color(255, 165, 0);
              final Color darkred = new Color(205, 38, 38);
              final Color orangered = new Color(255, 69, 0);
              final Color darkmagenta = new Color(139, 0, 139);
              final Color blueviolet = new Color(138, 43, 226);
              final Color lime = new Color(50, 205, 50);
              final Color goldenrod = new Color(205, 155, 29);
              final Color deeppink = new Color(255, 20, 147);
              final Color lightsteelblue = new Color(176, 196, 222);
              final Color yellowgreen = new Color(154, 205, 50);
              final Color limegreen = new Color(34, 139, 34);
              final Color burlywood = new Color(222, 184, 135);
              final Color paleturquoise = new Color(102, 139, 139);
              final Color springgreen = new Color(0, 238, 118);
              final Color seagreen = new Color(46, 139, 87);
              final Color greenyellow = new Color(127, 255, 0);
              final Color steelblue = new Color(54, 100, 139);
              final Color royalblue = new Color(65, 105, 225);
              final Color hotpink = new Color(255, 105, 180);
              final Color tan = new Color(205, 133, 63);
              final Color skyblue = new Color(135, 206, 250);
              final Color palevioletred = new Color(219, 112, 147);
              final Color slateblue = new Color(0, 127, 255);
              final Color coral = new Color(255, 127, 0);
              final Color cornflower = new Color(100, 149, 237);
              final Color maroon = new Color(176, 48, 96);
              try {
                   URL url = new URL("file:misslebeep2.wav");
                   AudioClip ac = Applet.newAudioClip(url);
                   ac.play();
              } catch (Exception e) {
              timercheck = new java.util.Timer();
              task = new TimerTask() {
                   public void run() {
                        try {
                             channel = FeedParser
                                       .parse(
                                                 channelb = new ChannelBuilder(),
                                                 url = new URL(
                                                           "http://www.weather.gov/alerts/wwarssget.php?zone=COZ041"));
                        catch (Exception e) {
                             System.out.println("exception");
                        finally {
                             items = channel.getItems();
                             scrollLabel = new JLabel(newscroll);
                             for (Iterator i = items.iterator(); i.hasNext();) {
                                  count++;
                                  ItemIF item = (ItemIF) i.next();
                                  scroll = item.getDescription();
                                  newscroll += scroll
                                            .replaceAll("<br>", " ")
                                            .replaceAll(
                                                      "Issuing Weather Forecast Office Homepage",
                                            .replaceAll("</a>", " ")
                                            .replaceAll(
                                                      "<a href=http://www.nws.noaa.gov/er/ctp>",
                             if (newscroll.contains("There are no active"))
                                  scrollLabel.setVisible(false);
                             else {
                                  scrollLabel.setBackground(red);
                                  if (newscroll.contains("Tornado warning".toUpperCase()))
                                       scrollLabel.setBackground(red);
                                  if (newscroll.contains("Severe thunderstorm warning"
                                            .toUpperCase()))
                                       scrollLabel.setBackground(orange);
                                  if (newscroll.contains("Flash Flood Warning"
                                            .toUpperCase()))
                                       scrollLabel.setBackground(darkred);
                                  if (newscroll
                                            .contains("Blizzard Warning".toUpperCase()))
                                       scrollLabel.setBackground(orangered);
                                  if (newscroll.contains("ice storm warning"
                                            .toUpperCase()))
                                       scrollLabel.setBackground(darkmagenta);
                                  if (newscroll.contains("short term".toUpperCase()))
                                       scrollLabel.setBackground(burlywood);
                                  if (newscroll.contains("heavy snow warning"
                                            .toUpperCase()))
                                       scrollLabel.setBackground(blueviolet);
                                  if (newscroll.contains("heavy sleet warning"
                                            .toUpperCase()))
                                       scrollLabel.setBackground(skyblue);
                                  if (newscroll.contains("flood warning".toUpperCase()))
                                       scrollLabel.setBackground(lime);
                                  if (newscroll.contains("high wind warning"
                                            .toUpperCase()))
                                       scrollLabel.setBackground(goldenrod);
                                  if (newscroll
                                            .contains("red flag warning".toUpperCase()))
                                       scrollLabel.setBackground(deeppink);
                                  if (newscroll.contains("wind chill warning"
                                            .toUpperCase()))
                                       scrollLabel.setBackground(lightsteelblue);
                                  if (newscroll.contains("freeze warning".toUpperCase()))
                                       scrollLabel.setBackground(Color.cyan);
                                  if (newscroll.contains("snow watch".toUpperCase()))
                                       scrollLabel.setBackground(Color.cyan);
                                  if (newscroll.contains("flood statement".toUpperCase()))
                                       scrollLabel.setBackground(yellowgreen);
                                  if (newscroll.contains("tornado watch".toUpperCase()))
                                       scrollLabel.setBackground(yellow);
                                  if (newscroll.contains("severe thunderstorm watch"
                                            .toUpperCase()))
                                       scrollLabel.setBackground(palevioletred);
                                  if (newscroll.contains("flash flood watch"
                                            .toUpperCase()))
                                       scrollLabel.setBackground(limegreen);
                                  if (newscroll.contains("freezing rain".toUpperCase()))
                                       scrollLabel.setBackground(slateblue);
                                  if (newscroll
                                            .contains("freezing drizzle".toUpperCase()))
                                       scrollLabel.setBackground(slateblue);
                                  if (newscroll.contains("sleet advisory".toUpperCase()))
                                       scrollLabel.setBackground(slateblue);
                                  if (newscroll.contains("winter weather advisory"
                                            .toUpperCase()))
                                       scrollLabel.setBackground(burlywood);
                                  if (newscroll.contains("wind chill advisory"
                                            .toUpperCase()))
                                       scrollLabel.setBackground(paleturquoise);
                                  if (newscroll.contains("heat advisory".toUpperCase()))
                                       scrollLabel.setBackground(coral);
                                  if (newscroll.contains("flood advisory".toUpperCase()))
                                       scrollLabel.setBackground(springgreen);
                                  if (newscroll.contains("snow advisory".toUpperCase()))
                                       scrollLabel.setBackground(paleturquoise);
                                  if (newscroll.contains("wind advisory".toUpperCase()))
                                       scrollLabel.setBackground(tan);
                                  if (newscroll.contains("frost advisory".toUpperCase()))
                                       scrollLabel.setBackground(cornflower);
                                  if (newscroll.contains("flood watch".toUpperCase()))
                                       scrollLabel.setBackground(seagreen);
                                  if (newscroll.contains("blizzard watch".toUpperCase()))
                                       scrollLabel.setBackground(greenyellow);
                                  if (newscroll.contains("winter storm watch"
                                            .toUpperCase()))
                                       scrollLabel.setBackground(steelblue);
                                  if (newscroll.contains("winter storm warning"
                                            .toUpperCase()))
                                       scrollLabel.setBackground(hotpink);
                                  if (newscroll.contains("high wind watch".toUpperCase()))
                                       scrollLabel.setBackground(goldenrod);
                                  if (newscroll.contains("excessive heat watch"
                                            .toUpperCase()))
                                       scrollLabel.setBackground(maroon);
                                  if (newscroll.contains("freeze watch".toUpperCase()))
                                       scrollLabel.setBackground(royalblue);
                                  if (newscroll
                                            .contains("wind chill watch".toUpperCase()))
                                       scrollLabel.setBackground(royalblue);
                                  if (newscroll.contains("excessive heat watch"
                                            .toUpperCase()))
                                       scrollLabel.setBackground(maroon);
                                  if (newscroll.contains("excessive heat watch"
                                            .toUpperCase()))
                                       scrollLabel.setBackground(maroon);
                                  if (newscroll.contains("excessive heat watch"
                                            .toUpperCase()))
                                       scrollLabel.setBackground(maroon);
                                  scrollLabel.setFont(new Font("Arial", Font.BOLD, 40));
                                  getContentPane().add(scrollLabel, BorderLayout.SOUTH);
                                  scrollLabel.setOpaque(true);
                                  scrollLabel.setForeground(Color.white);
         // create 2nd timer. give time of 1000ms.
         // event.getsource...in action performed
         timercheck.scheduleAtFixedRate(task, 1000, 10000);
         Timer timer = new Timer(120,this);
         //javax.swing.Timer timer = new javax.swing.Timer(120, this);
         timer.start();
         public void actionPerformed(ActionEvent event) {
              oldText = scrollLabel.getText();
              StringBuffer newText = new StringBuffer(oldText.substring(1) + oldText.substring(0, 1));
              String text = newText.toString();
              scrollLabel = new JLabel (text);
              //scrollLabel.setText(newText.toString());
         public static void main(String[] args) {
              Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
              int y = (14 * screen.height) / 15;
              WxScroll frame = new WxScroll();
              JLabel title = new JLabel("WxScroll");
              JPanel titlePanel = new JPanel();
              titlePanel.setPreferredSize(new Dimension(0, 0));
              titlePanel.add(title);
              frame.setLocation(0, y);
              // paint component method, drawstring,
              frame.setUndecorated(true);
              frame.setAlwaysOnTop(true);
              frame.getContentPane().add(titlePanel);
              frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
              frame.pack();
              frame.setVisible(true);
    }The errors i receive are:
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
         at WxScroll.actionPerformed(WxScroll.java:289)
         at javax.swing.Timer.fireActionPerformed(Unknown Source)
         at javax.swing.Timer$DoPostEvent.run(Unknown Source)
         at java.awt.event.InvocationEvent.dispatch(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)

    I don't know. There are classes your code requires (e.g., everything in the de.nava.informa packages) that I don't have, so I can't really compile or run your code.
    I will say this: it's a confused mess. There's too much code and too little abstraction. This is typical of beginning object-oriented programmers.
    When you start seeing LOTS of repeated stuff like this:
                      if (newscroll.contains("Tornado warning".toUpperCase()))
                         scrollLabel.setBackground(red);
                      }alarm bells should start ringing in your head. It appears that a Map with a String as key and Color as value is wanted. I can make all that code collapse into something MUCH smaller. If I externalize all those awful Color declarations into a File that's read on startup (e.g., taking in the key message and the RGB values and initializing the Map), now I have something that I can change more easily. AND there's less code to manage.
    I see URLs, applet, TimerTask, HTML - the kitchen sink.
    I can't tell you what this class is about.
    Be lazier - write less code. That's what good programmers do.
    Try to think more abstractly.
    %

  • Button actionListener gives exception

    Dear All,
    I have created a sample page in jsf2.0 in netbeans6.9 which gives me following error when i click the submit button.. I am quite confused because my code seems correct.
    registration.jsp
    <h:form>
    Name:
    <h:inputText value="#{loginBean.userName}" label="Name"></h:inputText>
    <h:message for="Name" ></h:message>
    Password:
    <h:inputSecret value="#{loginBean.password}" label="Password"></h:inputSecret>
    <h:message for="Password" ></h:message>
    <h:commandButton value="Login" actionListener="#{loginBean.processAction}">
    </h:commandButton>
    </h:form>
    faces-config.xml
    <faces-config>
    <managed-bean>
    <managed-bean-name>loginBean</managed-bean-name>
    <managed-bean-class>com.beans.LoginBean</managed-bean-class>
    <managed-bean-scope>request</managed-bean-scope>
    </managed-bean>
    </faces-config>
    backing bean class
    package com.beans;
    import javax.faces.application.FacesMessage;
    import javax.faces.context.FacesContext;
    import javax.faces.event.AbortProcessingException;
    import javax.faces.event.ActionEvent;
    import javax.faces.event.ActionListener;
    public class LoginBean{
    private String userName;
    private String password;
    /** Creates a new instance of LoginBean */
    public LoginBean() {
    public String getPassword() {
    return password;
    public void setPassword(String password) {
    this.password = password;
    public String getUserName() {
    return userName;
    public void setUserName(String userName) {
    this.userName = userName;
    public void processAction(ActionEvent event) {
    if(userName.equals("sa") && password.equals("sa")){
    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Login sucessfull."));
    Exception
    org.apache.jasper.JasperException: /registration.jsp(31,12) A literal value was specified for attribute actionListener that is defined as a deferred method with a return type of void. JSP.2.3.4 does not permit literal values in this case
    at org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:40)
    Please can any one put some light in this problem..
    Regards,
    Santosh
    NetBeans IDE 6.9.1
    Server : Apache Tomcat 6.0.29

    I don't see anything wrong. The problem may be somewhere else, such as in the deployment or in the web.xml.

  • ActionListener Difficulty

    Hi !!
    I'm a student working on an assignment and I'm kind of stuck here, I hope you guys can help!
    I'm trying to invoke one class from another through the use of ActionListener Interface.
    I've been using a small example to try make it work but haven't been able to:
    This is the class that implements the actionlistener for a button:
    import javax.swing.*;
    import java.awt.event.*;
    public class TrialGui implements ActionListener
    JButton button;
    //private void run ()
    // JTextField txt = new JTextField(10);
    //frame.getContentPane().add(txt);
    //SW nuevaSW = new SW("It works");
    public static void main (String[] args)
    TrialGui gui = new TrialGui();
    gui.go();
    public void go()
    JFrame frame = new JFrame();
    button = new JButton("Click me");
    button.addActionListener(this);
    frame.getContentPane().add(button);
    frame.setSize(300,300);
    frame.setVisible(true);
    public void actionPerformed (ActionEvent ae)
    //button.run();
    button.setSize(200,300);
    Now, I would like the button rather than to be resized to launch another class when pressed (this other class has been created in a different .java file) . As you can see I've tried creating the run method for launching the other class but it didn't work.
    This is the other class I would like to be fired when pressing the button:
    import javax.swing.*; // Contains the JFrame, JButton, etc.
    import java.awt.*; //Contains the Border Layout
    import java.awt.event.*;// package containing ActionListener and ActionEvent
    //import java.util.Hashtable; Was being Used with GraphPaperLayout: Couldn't manage to make it work!
    public class SW //implements ActionListener
    JButton button1;
    JButton button2;
    JButton button3;
    JButton button4;
    JButton button5;
    JButton button6;
    JButton button7;
    JButton button8;
    // Declare main method
    public static void main (String[] args)
    /** What can I use to substitute the main. I think that in the programme
    * one should not have more than one main method. But I'm not sure what
    * to call this method or how it will influence the rest of the code.
    // Creates an instance of SecondWindow
    SW gui = new SW();
    gui.go();
    public void go()
    // Generate frame and panels + look and feel
    JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame frame = new JFrame("Campaign Details");
    JPanel panel1 = new JPanel(); // To occupy northern region of frame layout
    JPanel panel2 = new JPanel(); // To occupy central region of frame layout
    JPanel panel3 = new JPanel(); // To occupy southern region of frame layout
    GridBagLayout gbl = new GridBagLayout();//Generates layout for panel2
    // Generate the necessary buttons
    button1 = new JButton("GO");
    button2 = new JButton("Edit"); // times 3
    /** Can I add the same button (button2) three times to the same panel and yet assign
    * each different functions? they would all be edit buttons but
    * they will be editing different parametersof the campaign
    button3 = new JButton("Add Keywords");
    button4 = new JButton("New Campaign");
    button5 = new JButton("Log Out");
    button6 = new JButton("Refresh");
    button7 = new JButton("Edit");
    button8 = new JButton("Edit");
    // Generate the necessary txtAreas
    JTextArea txtArea1 = new JTextArea(1,4);
    JTextArea txtArea2 = new JTextArea(1,4);
    JTextArea txtArea3 = new JTextArea(1,4);
    JTextArea txtArea4 = new JTextArea(1,4);
    JTextArea txtArea5 = new JTextArea(1,4);
    JTextArea txtArea6 = new JTextArea(1,4);
    JTextArea txtArea7 = new JTextArea(1,4);
    JTextArea txtArea8 = new JTextArea(1,4);
    JTextArea txtArea9 = new JTextArea(1,4);
    /** Need to ask whether the data that will be
    * downloaded from the google server can be displayed on a
    * JTextField or do I need some other thing for displaying it?
    * I found the JTextArea but I don't know how appropriate this is.
    // Generate the necessary labels
    JLabel label1 = new JLabel("Select Campaign:");
    JLabel label2 = new JLabel("Impressions:");
    JLabel label3 = new JLabel("Clicks:");
    JLabel label4 = new JLabel("Budget:");
    JLabel label5 = new JLabel("Monthly");
    JLabel label6 = new JLabel("Daily");
    JLabel label7 = new JLabel("Keywords:");
    JLabel label8 = new JLabel("Popularity");
    JLabel label9 = new JLabel("Avg.\nCPC");// how do I make it two lines?? /que?
    JLabel label10 = new JLabel("Cost");
    //Generate the necessary Drop Down Menus
    String[] items = {"ApoyoVenezuela", "Other Campaign", "..."};
    JComboBox editableCB1 = new JComboBox(items);
    //editableCB1.setEditable(true);
    String[] items2 = {"Venezuela", "hugo chavez", "ApoyoVenezuela", "..."};
    JComboBox editableCB2 = new JComboBox(items2);
    //editableCB2.setEditable(true);
    // What class can I use to generate these menues???
    // Defines format of fonts to be used
    Font bigFont = new Font("Courrier New", Font.PLAIN, 12);
    Font smallFont = new Font("Courrier New", Font.PLAIN, 9);
    Font boldBigFont = new Font("Courrier New", Font.BOLD, 15);
    Font boldSmallFont = new Font("Courrier New", Font.BOLD, 10);
    // Assign fonts to differet components
    button1.setFont(smallFont);
    button2.setFont(smallFont);
    button3.setFont(bigFont);
    button4.setFont(bigFont);
    button5.setFont(bigFont);
    button6.setFont(bigFont);
    button7.setFont(smallFont);
    button8.setFont(smallFont);
    label1.setFont(bigFont);
    label2.setFont(boldBigFont);
    label3.setFont(boldBigFont);
    label4.setFont(boldBigFont);
    label5.setFont(boldSmallFont);
    label6.setFont(boldSmallFont);
    label7.setFont(boldBigFont);
    label8.setFont(boldSmallFont);
    label9.setFont(boldSmallFont);
    label10.setFont(boldSmallFont);
    //Assign ActionListener Fuctionality to buttons
    //button1.addActionListener(this);
    //button2.addActionListener(this);
    //button3.addActionListener(this);
    //button4.addActionListener(this);
    //button5.addActionListener(this);
    //button6.addActionListener(this);
    //button7.addActionListener(this);
    //button8.addActionListener(this);
    // Format frame and panels
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//atmtclly ends Prgmm on clsing the frame
    frame.getContentPane().add(BorderLayout.NORTH, panel1);//fit panels inside the frame
    frame.getContentPane().add(BorderLayout.CENTER, panel2);
    frame.getContentPane().add(BorderLayout.SOUTH, panel3);
    panel1.setBackground(Color.yellow); // set panels background colour
    panel2.setBackground(Color.blue);
    panel3.setBackground(Color.red);
    panel2.setLayout(gbl); // Assign gbl layout created above
    //Set constraints for gbc
    GridBagConstraints gbc = new GridBagConstraints();
    //Components spanning three columnsand aligned to the left (west)
    gbc.gridwidth = 3;
    gbc.anchor = GridBagConstraints.WEST;
    gbc.gridx = 0;
    gbc.gridy = 1;
    gbl.setConstraints(label4, gbc);
    panel2.add(label4);
    gbc.gridx = 0;
    gbc.gridy = 2;
    gbl.setConstraints(label2, gbc);
    panel2.add(label2);
    gbc.gridx = 0;
    gbc.gridy = 3;
    gbl.setConstraints(label3, gbc);
    panel2.add(label3);
    gbc.gridx = 0;
    gbc.gridy = 4;
    gbl.setConstraints(label7, gbc);
    panel2.add(label7);
    gbc.gridx = 0;
    gbc.gridy = 6;
    gbl.setConstraints(button3, gbc);
    panel2.add(button3);
    gbc.gridx = 0;
    gbc.gridy = 5;
    gbl.setConstraints(editableCB2, gbc);
    panel2.add(editableCB2);
    //Sets back 2 column spanning and aligns back to the centre
    gbc.anchor = GridBagConstraints.CENTER;
    gbc.gridwidth = 1;
    gbc.gridx = 3;
    gbc.gridy = 0;
    gbl.setConstraints(label5, gbc);
    panel2.add(label5);
    gbc.gridx = 4;
    gbc.gridy = 0;
    gbl.setConstraints(label6, gbc);
    panel2.add(label6);
    gbc.gridx = 3;
    gbc.gridy = 4;
    gbl.setConstraints(label8, gbc);
    panel2.add(label8);
    gbc.gridx = 4;
    gbc.gridy = 4;
    gbl.setConstraints(label9, gbc);
    panel2.add(label9);
    gbc.gridx = 5;
    gbc.gridy = 4;
    gbl.setConstraints(label10, gbc);
    panel2.add(label10);
    gbc.gridx = 5;
    gbc.gridy = 1;
    gbl.setConstraints(button2, gbc);
    panel2.add(button2);
    gbc.gridx = 4;
    gbc.gridy = 6;
    gbl.setConstraints(button7, gbc);
    panel2.add(button7);
    gbc.gridx = 5;
    gbc.gridy = 6;
    gbl.setConstraints(button8, gbc);
    panel2.add(button8);
    gbc.gridx = 3;
    gbc.gridy = 1;
    gbl.setConstraints(txtArea1, gbc);
    panel2.add(txtArea1);
    gbc.gridx = 3;
    gbc.gridy = 2;
    gbl.setConstraints(txtArea3, gbc);
    panel2.add(txtArea3);
    gbc.gridx = 3;
    gbc.gridy = 3;
    gbl.setConstraints(txtArea5, gbc);
    panel2.add(txtArea5);
    gbc.gridx = 3;
    gbc.gridy = 5;
    gbl.setConstraints(txtArea7, gbc);
    panel2.add(txtArea7);
    gbc.gridx = 4;
    gbc.gridy = 1;
    gbl.setConstraints(txtArea2, gbc);
    panel2.add(txtArea2);
    gbc.gridx = 4;
    gbc.gridy = 2;
    gbl.setConstraints(txtArea4, gbc);
    panel2.add(txtArea4);
    gbc.gridx = 4;
    gbc.gridy = 3;
    gbl.setConstraints(txtArea6, gbc);
    panel2.add(txtArea6);
    gbc.gridx = 4;
    gbc.gridy = 5;
    gbl.setConstraints(txtArea8, gbc);
    panel2.add(txtArea8);
    gbc.gridx = 5;
    gbc.gridy = 5;
    gbl.setConstraints(txtArea9, gbc);
    panel2.add(txtArea9);
    panel1.add(label1);
    panel1.add(editableCB1);
    panel1.add(button1);
    panel3.add(button6);
    panel3.add(button4);
    panel3.add(button5);
    // Set frame dimensions and make it visible
    frame.setSize(320,300);
    frame.setVisible(true);
    //Set actions for the ActionListener enabled buttons
    //public void actionPerformed (ActionEvent ae)
    //button1.
    Thank you very much for your help, I really appreciate it.
    Cheers

    Thanx for yout pronpt reply!!
    I've added
    SW sw = new SW();
    to the actionPerformed method and it seems to actually invoke the SW class. I've also added the following method to the SW class
    public SW()
    //build the GUI here, or call a method that builds it from here
    SW sw2 = new SW();
    but when I run it I get some error which I can't understand. I'm using the cmd to compile and execute and can't read the first lines of teh error. The only line of the error I can see is:
    at SW.<init>(SW.java:22)
    which keeps on repeating untill I stop the programme from running
    To be sincere I'm confused with all this code and I'm no quite sure what method to use to make it work.
    Please help!! :-)
    Cheers

  • I've got some kind of issue with removing an ActionListener

    public class JTextNameListener implements ActionListener
        public void actionPerformed(ActionEvent e)
          //if (buttonEnabled == true)
            passengers[currentButton-1] = jTextName.getText();
            jTextName.setEditable(false);
            jTextSeatNumber.setText(Integer.toString(currentButton));
            if (currentButton == 2)
              btnSeatTwo.removeActionListener(ButtonChoiceListener);
              btnSeatTwo.removeActionListener(ButtonEnableListener);
              btnSeatTwo.setForeground(Color.black);
            else if (currentButton == 5)
              btnSeatFive.removeActionListener(ButtonChoiceListener);
              btnSeatFive.removeActionListener(ButtonEnableListener);
              btnSeatFive.setForeground(Color.black);
            }Here is the segment of code that is not functioning properly...and i'm a bit confused.
    The entire program is working except when I hit enter for this JTextField...it does not remove the listeners off of the Buttons. I declared these up top as private fields and then I added the listeners by doing this...
    add(btnSeatFive);
        btnSeatFive.setForeground(Color.GREEN);
        btnSeatFive.addActionListener(new ButtonEnableListener());
        btnSeatFive.addActionListener(new ButtonChoiceListener());
        add(btnSeatSeven);
        add(btnSeatNine);
        add(btnSeatEleven);
        btnSeatEleven.setForeground(Color.GREEN);
        btnSeatEleven.addActionListener(new ButtonEnableListener());
        btnSeatEleven.addActionListener(new ButtonChoiceListener());
        add(btnSeatTwo);
        btnSeatTwo.setForeground(Color.GREEN);
        btnSeatTwo.addActionListener(new ButtonEnableListener());
        btnSeatTwo.addActionListener(new ButtonChoiceListener());
        add(btnSeatFour);
        add(btnSeatSix);
        btnSeatSix.setForeground(Color.GREEN);
        btnSeatSix.addActionListener(new ButtonEnableListener());
        btnSeatSix.addActionListener(new ButtonChoiceListener());
        add(btnSeatEight);
        add(btnSeatTen);
        add(btnSeatTwelve);

    alright thank you very much! I ended up having to do this for some reason...but works perfectly...
    private ButtonEnableListener enableListener = new ButtonEnableListener();
      private ButtonChoiceListener choiceListener = new ButtonChoiceListener();
    if (currentButton == 2)
              btnSeatTwo.removeActionListener(choiceListener);
              btnSeatTwo.removeActionListener((ActionListener) enableListener);
              btnSeatTwo.setForeground(Color.black);
            else if (currentButton == 5)
              btnSeatFive.removeActionListener(choiceListener);
              btnSeatFive.removeActionListener((ActionListener) enableListener);
              btnSeatFive.setForeground(Color.black);
            }I don't understand why I had to cast the enable listener but eclipse told me to do it and it worked so...Still if anyone knows why I had to do that, that would be helpful.

  • Confused after reading bug report

    Hello,
    I'm working on a desktop application which utilizes the system tray. I have an icon set with a popup menu that is triggered when the user left-clicks on the icon. Originally I was using java.awt.PopupMenu but then came across javax.swing.JPopupMenu which looks a little nicer and has support for icons. For the most part it works great. However I noticed that when the user triggers the popup menu more than once (i.e. the user left-clicks the tray icon twice or more times), a ClassCastException is thrown. After doing a bit of searching, I came across [this bug report|http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6583251] and many others describing the issue I was having.
    According to the report, the evaluation is:
    Everything is clear
    we shouldn't cast mouseEvent.getSource() to Component without checkingUnfortunately this still leaves me a little confused. I mean, it does sort of let me know where the problem is happening (in the MouseListener portion of my Tray Menu where I am trying to detect the popup trigger), but I don't understand if this means that there is a way to prevent this from happening or not.
    In other words, I think the bug is coming from this block of code (correct me if I am mistaken):
    public void mouseReleased(MouseEvent e) {
              if ( e.isPopupTrigger() ) {
                   this.setLocation( e.getX(), e.getY() );
                   this.setInvoker( this );
                   this.setVisible( true );
         }Where e is apparently being casted to a Component, thus causing the error. Now, why this error occurs when the user clicks twice or more on the icon, I don't really understand. Ultimately, my question is: Is there any other way this can be written to prevent the error?
    One solution would be to simply use java.awt.PopupMenu, but I want to make sure there isn't a better solution first as JPopupMenu looks much nicer.. but if I have no other option, I will of course substitute looks for function.
    Any clarification would be greatly appreciated.
    (Apologies if this is the wrong forum. I was originally going to post this in the Swing forum, but the error actually cites AWT, yet I'm using a Swing component.. so I figured the Java Programming forum would be alright. Well, please feel free to move it if necessary.)

    ejp wrote:
    The exception stack trace tells you where the exception is being thrown from. It certainly isn't from that code, because there are no class casts of any kind there, let alone casts of e.getSource() to Component.Hi ejp, thank you for the response. My apologies.. I only assumed that e.isPopupTrigger() was throwing the exception because the bug report mentioned mouse events, and the stack trace doesn't specify where the error is within my code (e.g. the line, method, or even which class is throwing the error that I've written, though it does cite other Java classes not written by me). The e.getSource() in actionPerformed() was my next guess because that and the MouseListener are the only two places where I am detecting events. Nevertheless, I still don't believe that I am using casting, so I'm not sure how to fix this.
    Here is the stack trace:
    Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.awt.TrayIcon cannot be cast to java.awt.Component
         at javax.swing.plaf.basic.BasicPopupMenuUI$MouseGrabber.eventDispatched(Unknown Source)
         at java.awt.Toolkit$SelectiveAWTEventListener.eventDispatched(Unknown Source)
         at java.awt.Toolkit$ToolkitEventMulticaster.eventDispatched(Unknown Source)
         at java.awt.Toolkit.notifyAWTEventListeners(Unknown Source)
         at java.awt.TrayIcon.dispatchEvent(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)
    Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.awt.TrayIcon cannot be cast to java.awt.Component
         at javax.swing.plaf.basic.BasicPopupMenuUI$MouseGrabber.eventDispatched(Unknown Source)
         at java.awt.Toolkit$SelectiveAWTEventListener.eventDispatched(Unknown Source)
         at java.awt.Toolkit$ToolkitEventMulticaster.eventDispatched(Unknown Source)
         at java.awt.Toolkit.notifyAWTEventListeners(Unknown Source)
         at java.awt.TrayIcon.dispatchEvent(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)Below is my TrayMenu class extending JPopupMenu:
    package gui.menus;
    import gui.frames.TrayTweetFrame;
    import java.awt.HeadlessException;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import javax.swing.ImageIcon;
    import javax.swing.JMenuItem;
    import javax.swing.JPopupMenu;
    import util.Constants;
    public class TrayMenu extends JPopupMenu implements ActionListener, MouseListener {
         private JMenuItem exitMenuItem = null;
         private TrayTweetFrame frame = null;
         private JMenuItem minimizeMenuItem = null;
         private JMenuItem restoreMenuItem = null;
         private static final long serialVersionUID = 1L;
          * Constructor
          * @param TrayTweetFrame frame
          * @throws HeadlessException
         public TrayMenu ( TrayTweetFrame frame ) throws HeadlessException {
              this.frame = frame;
              this.initialize();
         } // end constructor
          * This method handles the events.
         public void actionPerformed( ActionEvent e ) {
              // Exit
              if ( e.getSource().equals( getExitMenuItem() ) ) {
                   getFrame().exit();
              // Restore or Minimize window
              else if ( e.getSource().equals( getRestoreMenuItem() ) ||
                        e.getSource().equals( getMinimizeMenuItem() ) ) {
                   getFrame().minimize();
         } // end method actionPerformed()
          * This method initializes and returns
          * the Exit menu item.
          * @return MenuItem exitMenuItem
         public JMenuItem getExitMenuItem() {
              if ( exitMenuItem == null ) {
                   exitMenuItem = new JMenuItem( Constants.MENU_EXIT, new ImageIcon("img/icons/exit.png" ) );
                   exitMenuItem.addActionListener( this );
              return exitMenuItem;
         } // end method getExitMenuItem
          * This method returns the frame.
          * @return frame
         public TrayTweetFrame getFrame() {
              return frame;
         } // end method getFrame
          * This method initializes and returns
          * the Minimize menu item.
          * @return MenuItem minimizeMenuItem
         public JMenuItem getMinimizeMenuItem() {
              if ( minimizeMenuItem == null ) {
                   minimizeMenuItem = new JMenuItem( Constants.MENU_MINIMIZE, new ImageIcon("img/icons/minimize.png" ) );
                   minimizeMenuItem.addActionListener( this );
              return minimizeMenuItem;
         } // end method getMinimizeMenuItem
          * This method initializes and returns
          * the Restore menu item.
          * @return MenuItem restoreMenuItem
         public JMenuItem getRestoreMenuItem() {
              if ( restoreMenuItem == null ) {
                   restoreMenuItem = new JMenuItem( Constants.MENU_RESTORE, new ImageIcon("img/icons/maximize.png" ) );
                   restoreMenuItem.addActionListener( this );
                   restoreMenuItem.setEnabled( false );
              return restoreMenuItem;
         } // end method getRestoreMenuItem
          * This method initializes the menu.
         private void initialize() {
              this.add( getMinimizeMenuItem() );          // Minimize
              this.add( getRestoreMenuItem() );          // Restore
              this.addSeparator();                    // --------
              this.add( getExitMenuItem() );               // Exit
         } // end method initialize
         public void mouseClicked(MouseEvent e) {
              // Check for double-click
              if ( e.getClickCount() == 2 ) {
                   // Minimize to the system tray
                   getFrame().minimize();
              } // end if
         public void mouseEntered(MouseEvent e) {}
         public void mouseExited(MouseEvent e) {}
         public void mousePressed(MouseEvent e) {}
         public void mouseReleased(MouseEvent e) {
              if ( e.isPopupTrigger() ) {
                   this.setLocation( e.getX(), e.getY() );
                   this.setInvoker( this );
                   this.setVisible( true );
    } // end class TrayMenuAm I doing something wrong? Like I said, I'm not casting (at least explicitly..), so I'm not sure why I'm getting a java.lang.ClassCastException error. Normally I can figure out problems like these with Google, but again, when I did Google this, I came across the bug report which describes my issue exactly (but at the same time, left me wondering what the solution is).
    Again, any help is appreciated. Thanks again, ejp!

  • MVC Variations Confusing Me

    I've read this in one article:
    # a model consisting of the application with no external interface;
    # a view consisting of one or more graphical frames that interact with the user and the application; and
    # a controller consisting of the ``main'' program that constructs the model and the view and links them together.Additionally,
    When a program with a graphical interface starts, the controller
       1. creates the model (application),
       2. creates the view consisting of one or more graphical frames and attaches commands to the graphical input controls (buttons, text boxes, etc.) of the view,
       3. activates the graphical components in the view, and
       4. terminates.Here's what I understand: anything that can be seen or has a graphical component is automatically a view. This includes Swing, AWT, even a JFrame with all the buttons and stuff in it. I've also read somewhere that Views can opt to register to a Model to automatically update itself when the Model changes, but that the Controller would handle the registration process. Models only store state, or data. They DO NOT have to do any special formatting or know how to present themselves. They don't know about any Views. Controllers contain the application-specific logic. They just tie the two together then terminate. They don't have a user interface. Hence, the following code...
    class Model
         // misc. code.
         private String name;
         public void setName(String name)
              this.name = name;
         public String getName()
              return name;
    class Controller
         // misc. code.
         private Model model;
         private View view;
         public Controller()
              model = new Model();
              model.setName("I am Sam");
              view = new View();
              view.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              view.addOkButtonListener(new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        view.setNameTextFieldText(model.getName());
         public static void main(String[] args)
              new Controller();
    class View extends JFrame
         // misc. code.
         private JButton okButton;
         private JTextField nameTextField;
         public void addOkButtonListener(ActionListener l)
              okButton.addActionListener(l);
         public void removeOkButtonListener(ActionListener l)
              okButton.removeActionListener(l);
         public void setNameTextFieldText(String text)
              nameTextField.setText(text);
    }is an example of MVC, or at least that is my understanding of it. I was just beginning to appreciate the above pattern when all of a sudden, I encounter this(http://www.cs.tufts.edu/~jacob/106/lecture/25_MVC.html), again putting me in a state of confusion.
    If I stick to the definition of a controller given earlier in this post, I would say that the second example's controller is...."wrong". The Controller class has a view of its own. Additionally, the Controller uses a common callback for handling button events. I've read in the same article that this is bad design. The author presents some reasons, but in short, a common callback could turn into one long MONSTER IF statement mayhem.
    Since the focus of MVC is on improved object reuse, model and view objects should be loosely coupled. Controller objects get reused the least. In the second example, all Views have a Model object inside of them, lessening their reusability. If in the first example, the Controller object acts as the glue that magically binds the model and view objects together, in the second example, glue is all over the place.
    In the first example, if one removes the Controller class, the Model and View objects remain intact. If the Model is removed, the Controller is surely affected but the View still remains intact. We can even change the Model's API, and all that would need to be changed is the Controller.
    In the second example, if one removes the Model object, the Controller and View objects are compromised. If we completely change the Model's API, the Controller and View objects would need to be changed too.
    The second example has gotten me so confused I feel I need to ask these questions:
    1.) Why does the second example maintain a tight coupling between the Model and the View?
    2.) Why does the Controller have it's own View?
    3.) Does the second example have any strengths over the first example? Or does the first example have any weaknesses too? In short, what can the first example do that the other can't and vice versa?
    3.) In what types of problems is one more suitable than the other?
    4.) Which is better in the long run or in larger projects (in terms of modularity, ease of coding, maintainability, etc.)?
    I really need to clear this up. :)

    MVC is a great design goal, but more often than not, you end up with model-delegate. The delegate contains controller and view, more tightly coupled than one would like in full-blown MVC.
    You should avoid coupling the model and view in any way. If you have to, write the controller closely coupled to the view, and then have the controller invoke model classes. That way, you can at least keep your domain model classes if you ever switch views or add a view.
    Conceptually:
    View - Displays the model to the user
    Model - Application data and business objects
    Controller - Parses user requests and mediates between view and model
    You can also check out the following URL that may explain the concepts differently (and better) than I could:
    http://java.sun.com/blueprints/patterns/MVC-detailed.html
    It's very difficult to totally separate the view and controller. The closest I've ever come is to implement the Command pattern and then use dynamic method invocation.
    - Saish
    "My karma ran over your dogma." - Anon

  • Question about jcheckbox , very confused here.

    look at my comments, im very frustrated here why it seems to be skipping that part. thanks.
    private class ButtonListener implements ActionListener
          public void actionPerformed (ActionEvent event)
    if (event.getSource() == submit)
       if (bathroom.isSelected()){
                       g1.remove(namelabel);    
                     g1.remove(namelabel);
                     g1.remove(bathroom);//why wont this stuff work?
                     g1.remove(office);
                     g1.remove(nurse);
                     g1.remove(other);
    System.out.println("TESTWONTPRINT"); // WONT WORK WTF?!
                          g1.setBackground(Color.red);
                          p2.add(returnbutton);
                          namelabel.setText(namearray[0]+" is currently using the pass the time left was ");
                           g1.add(namelabel);
                           g1.add(time);
                          f1.dispose();
                          f1.show();
    }

    i know its an eye full but i marked the relevent parts.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.Calendar;
    import java.text.SimpleDateFormat;
    import java.lang.Object;
    import java.io.*;
    import javax.swing.event.*;
    public class Main
            JFrame f1,f2;
            JPanel p1,p2,p3,p4;
            String id,enterstring,name,namestring,idstring,str;
            GP g1;
            JCheckBox bathroom,office,nurse,other; //check boxes
            JButton submit,returnbutton;
            JTextField idnumber;
            JLabel idprompt,what,time,namelabel;
            boolean show,bathroomb,officeb,nurseb,otherb;
            int idnum,counter;
            SimpleDateFormat sdf;
           String[] namearray;
           int[] idarray;
           int a,b,idint,enter,teacher;
            teacher = 1234567890;
             bathroomb = false;
             officeb = false;
             nurseb = false;
             otherb = false;
            namearray = new String[3];
            idarray = new int[3];
         sdf = new SimpleDateFormat("yyyy.MM.dd G 'at' hh:mm:ss z"); 
           show=true;
            a=0;
            b=0;
            namelabel = new JLabel("");
           bathroom = new JCheckBox("Bathroom");  // CHECKBOXES
            bathroom.setMnemonic(KeyEvent.VK_C);
            bathroom.setSelected(false);
            counter = 1;
           office = new JCheckBox("Office");
           office.setMnemonic(KeyEvent.VK_C);
            office.setSelected(false);
           nurse = new JCheckBox("Nurse");
            nurse.setMnemonic(KeyEvent.VK_C);
            nurse.setSelected(false);
           other = new JCheckBox("Other");
            other.setMnemonic(KeyEvent.VK_C);
            other.setSelected(false);
            idprompt = new JLabel("Enter ID Number");
            idnumber = new JTextField(14);
            f1 = new JFrame("Hall Pass");
              f1.setSize(550,200);       
            Container c1 = f1.getContentPane();
            time = new JLabel("left at "+sdf.format(new java.util.Date(System.currentTimeMillis())));
            id = "123";
            p1 = new JPanel();
            p1.setSize(500,150);
            p1.setLayout(new BorderLayout());
              what = new JLabel("");
          //  bathroom.addActionListener(new ButtonListener());
          //  other.addActionListener(new ButtonListener());
          //  nurse.addActionListener(new ButtonListener());
          //  office.addActionListener(new ButtonListener());
            returnbutton = new JButton("Return");
            returnbutton.addActionListener(new ButtonListener());
            submit = new JButton("Submit");
            submit.addActionListener(new ButtonListener());
            p2 = new JPanel();  //panel to add JLabel and TextField
            g1 = new GP();   
             p1.add(g1,BorderLayout.CENTER);
                      //g1.setBackground(new RGB(255, 255, 255));
           g1.add(idprompt);
           g1.add(idnumber);
            p2.add(submit);
            g1.add(what);
            p1.add(p2,BorderLayout.SOUTH);      //adds p2 to south (Bottom) Graphics Panel will be added to Center   
            c1.add(p1);
            f1.show();
        private class ButtonListener implements ActionListener
          public void actionPerformed (ActionEvent event)
      try {
            BufferedReader in = new BufferedReader(new FileReader("names.txt"));  // this reads a txt file
            if (event.getSource() == returnbutton)
                f1.show();
           //idnum = Integer.Parseint(enter);
            if (event.getSource() == submit)
           for(int i=0; i<6; i++){
         str = in.readLine().trim() ;
            if(i<3){
                namearray[a] = str;
                a++;                                                      //greg
             }else{                                                          //joe
                  idarray[b] = Integer.parseInt(str);           //john
                  b++;                                                   //45454    // this is what the txt file looks like
                                                                                  //54535
              }                                                                //56666
            in.close();
               enterstring = idnumber.getText();
               enter = Integer.parseInt(enterstring);
               for(int b = 0;  b< 3; b++)
                   //number 1
               if (enter==idarray[0])
                     g1.remove(idnumber);
                     p1.remove(submit);
                     g1.remove(what);
                     g1.remove(idprompt);
                      p2.remove(submit);
                      namelabel.setText(namearray[0]);
                      g1.add(namelabel);
                     g1.add(bathroom);
                     g1.add(office);
                     g1.add(nurse);
                     g1.add(other);
                   //  nurse.addItemListener(new ItemListener() {       // i was confused?
                  if (bathroom.isSelected()){  // this part wont work
                       g1.remove(namelabel);    
                     g1.remove(namelabel);
                     g1.remove(bathroom);
                     g1.remove(office);
                     g1.remove(nurse);
                     g1.remove(other);
                          g1.setBackground(Color.red);
                          p2.add(returnbutton);
                          namelabel.setText(namearray[0]+" is currently using the pass the time left was ");
                           g1.add(namelabel);
                           g1.add(time);
                          f1.dispose();
                          f1.show();
                      if (office.isSelected()){
                           g1.remove(namelabel);    
                     g1.remove(namelabel);
                     g1.remove(bathroom);
                     g1.remove(office);
                     g1.remove(nurse);
                     g1.remove(other);
                          g1.setBackground(Color.red);
                          p2.add(returnbutton);
                          namelabel.setText(namearray[0]+" is currently using the pass the time left was ");
                           g1.add(namelabel);
                           g1.add(time);
                          f1.dispose();
                          f1.show();
                      if (nurse.isSelected()){
                           g1.setBackground(Color.red);
                          p2.add(returnbutton);
                          namelabel.setText(namearray[0]+" is currently using the pass the time left was ");
                           g1.add(namelabel);
                           g1.add(time);
                      if (other.isSelected()){
                           g1.setBackground(Color.red);
                          p2.add(returnbutton);
                          namelabel.setText(namearray[0]+" is currently using the pass the time left was ");
                           g1.add(namelabel);
                           g1.add(time);
                  //g1.setBackground(Color.red);
                 // p2.add(returnbutton);
                 // g1.add(time);
                  f1.dispose();
                  f1.show();
                else{
                 what.setText("Incorrect Login");
            //number 2
            if (enter==teacher)
                f1.dispose();
              if (enter == idarray[1])
                     g1.remove(idnumber);
                     p1.remove(submit);
                     g1.remove(what);
                     g1.remove(idprompt);
                  g1.setBackground(Color.red);
                  p2.remove(submit);
                  p2.add(returnbutton);
                   namelabel.setText(namearray[1]);
                 g1.add(namelabel);
                  g1.add(time);
                  f1.dispose();
                  f1.show();
                else{
                 what.setText("Incorrect Login");
              if (enter == idarray[2])
                     g1.remove(idnumber);
                     p1.remove(submit);
                     g1.remove(what);
                     g1.remove(idprompt);
                  g1.setBackground(Color.red);
                  p2.remove(submit);
                  p2.add(returnbutton);
                   namelabel.setText(namearray[2]);
                 g1.add(namelabel);
                  g1.add(time);
                  f1.dispose();
                  f1.show();
                else{
                 what.setText("Incorrect Login");
                idnumber.setText(null);
              g1.repaint();
    } catch (IOException e) {
    }

  • Apple ID appearing on another iPhone device (Sync confusion)

    Issue
    iTunes is sporadically requesting access to my partner's Apple ID account when downloading applications and trying to install the other iTunes account applications also when syncing takes place within iTunes. System software/accounts seems confused.
    How can I ensure that both devices remain separate and do not access each other's iTunes accounts or sync over Mac logins? How can I delete mixed applications from separate Apple ID's ensuring it won't replicate the deletion on the primary Apple ID?
    Background
    1 x Macbook Pro OS 10.8.2
    iTunes 11.0.1
    App Store 1.2.1
    1 x iPhone 4S OS 6.0.1 (Device A)
    1 x iPhone 4 OS 6.0.1 (Device B)
    Separate Apple ID's
    Separate iCloud accounts
    iTunes accounts
    Both people have our own iTunes accounts linked to their own device. All details are currently correct when checking Apple ID profiles.
    MacbookPro
    Both people have separate MacBook Pro logins and software is all up to date.
    History
    In the past, over a year ago, both iPhone devices were sync'd via the same iTunes and Macbook log in. (Not a good start I know) Both iPhones always had their own iTunes account for downloading apps and music etc. When I realised I was syncing application data from one iPhone to the other on my Macbook, I created two Macbook log ins. I deleted all applications on Device B that were transferred from Device A and also deleted the applications in Device B's iTunes account. It seemed that both devices finally had seperated, retained their own Apple ID logins, applications and Macbook user logins.
    Device B recently tried to install an application that Device A also had.
    The application installed onto Device B without an issue and there was no confusion with Device A having the same application. The application can be upgraded to provide additional functionality. When Device B requested this within the application to upgrade, the Apple ID of Device A suddenly appeared.
    I checked that Device B was asked to INSTALL the primary basic version of the application rather than OPEN it, just incase the confusion started at this point. It definitely said INSTALL.
    I thought the divorce was done and dusted in the past.
    Why would Device B suddenly point Device A's Apple ID?
    To troubleshoot, I connected Device B to iTunes on the MacBook with Device B's Macbook log in. When iTunes opened within the Apple ID of Device B ALL DEVICE A applications appeared and started to sync these applications to Device B! I am back to mixed accounts.
    How can ITunes suddenly connect the Apple ID's of both accounts and then tell Device B it needs to install Device A's applications? They are separate Apple ID accounts, separate copyright, separate costs.
    I know with iMatch that you can share the library with another device and when this occurs it locks the Apple ID of the primary iTunes account for 90 days on secondary device. We have never done this.
    I'm 'Syncing' trying to work this one out, please help!

    Steve324 wrote:
    s there a solution to get things
    back the way it was before the install?
    Thank you!
    See my previous suggestions

  • HT1414 i am in the process of getting my iphone4 unlocked from att to use it on straighttalk. why do i need to "back up" the iphone and all of this? i dont have an apple computer sooo, im a little confused on why i need to do this. can someone please help

    Can someone please explain and help me? I am unlocking an iphone4 from at&amp;t to use it on the straight talk network. They've confirmed my request to do this and I am now a little confused as to what to do next. They want me to back up the phone using itunes on either a MAC or PC. I do not have an aplle computer but I do have an acer. Sooo, can I use it to do this? Or do I even have to do this to unlock and switch the iphone4 over to a new network? If I do have to what can I do to do this because like I said I do not have a computer by apple? Can anybody walk me through what I need to do next please? I've been waiting to do this for a very long time and I now have the option to have an iphone and use it. Thanks to my awesome boyfriend who Gave me his old iphone when he swapped back to an android. Hahahaha! Please anybody!? Because I sooo don't know what I'm doing and really do not want to mess the phone Or the process up. Thanks to any and all who read this and help me! It is greatly appreciate it!

    Install iTunes on your Acer and you can back up the iPhone. Or back it up to iCloud. If you do not back it up you can get it unlocked, but you will lose all of your content.
    You can get iTunes from http://www.apple.com/itunes.
    Even after unlocking I'm not sure it will work on Straight Talk, because last time I checked ST used Verizon as its carrier, and an AT&T iPhone 4 is not compatible with Verizon's network. You can probably use it on Net 10 or T-Mobile once it is unlocked.

  • Computers on small office network - names getting confused on iChat

    We are using bonjour and iChat on the computers on a small airport network in our office as an instant messaging solution in our office - however, 2 of the computers (which are named differently) keep getting confused and both being called the same name.
    I have done the fix where you go to System Prefs, Users & Groups and then set the address book card to that particular computer owner, restart the computer and then open iChat (using bonjour) - it saves the name but then my colleague becomes the same name as me on iChat - so we do the same thing to her computer (set address book card etc) and it changes her iChat name, but then also seems to override what I had set for mine previously.
    Help!! What can I do to stop these 2 computers seemingly overriding each other? It doesn't happen with the other 4 computers sharing our network...

    Hi,
    In System Preferences > Sharing is the Name the Computer has.
    This does play a part in any Bonjour Connection.
    It is this name that appears in Shares in the Finders's Side bar.
    Separate for that iChat and Messages that have the Bonjour Account Enabled broadcast the details from the My Card in the Address Book.
    Issues can arise with some Server based Logins that create a Global Address book that changes the My Card.
    You get similar difficulties on some DiskImage roll outs of updates and the like if the details of the Address Book are copied as well.
    I am not sure what you mean by the "fix" in System Preferences > Users and Groups to change the My Card or the Computer's Name.
    Yes you can click the Contact Card for that account and it will show you it in the Address Book and it should be th My Card.
    Changing the My Card then does not alter which Card is associated with the Mac User Account.
    There is no access to the Computer's Name
    7:53 PM      Wednesday; August 1, 2012
    Please, if posting Logs, do not post any Log info after the line "Binary Images for iChat"
      iMac 2.5Ghz 5i 2011 (Lion 10.7.2)
     G4/1GhzDual MDD (Leopard 10.5.8)
     MacBookPro 2Gb (Snow Leopard 10.6.8)
     Mac OS X (10.6.8),
    "Limit the Logs to the Bits above Binary Images."  No, Seriously

  • Can not add a picture to the JFrame from an ActionListener class

    As topic says, I can not add a picture to the JFrame from an ActionListener class which is a class inside the JFrame class.
    I have a Map.java class where I load an image with ImageIcon chosen with JFileChooser.
    I my window class (main class), I have following:
    class OpenImage_Listener implements ActionListener
         public void actionPerformed(ActionEvent e)
              int ans = open.showOpenDialog(MainProgram.this);     // "open" is the JFileChooser reference
              if(ans == open.APPROVE_OPTION)
                   File file = open.getSelectedFile();                    
                   MainProgram.this.add(new Map(file.getName()), BorderLayout.CENTER);     // this line does not work - it does not add the choosen picture on the window,
                            //but if I add the picture outside this listener class and inside the MainProgram constructor, the picture apperas, but then I cannot use the JFileChooser.
                            showMessageDialog(MainProgram.this, fil.getName() ,"It works", INFORMATION_MESSAGE);  // this popup works, and thereby the ActionListener also works.
    }So why can�t I add a picture to the window from the above listener class?

    The SSCCE:
    Ok, I think I solved it with the picture, but now I cannot add new components after adding the picture.
    Look at the comment in the actionlistener class:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    public class Test extends JFrame{
         JButton b = new JButton("Open");
         JFileChooser jfc = new JFileChooser(System.getProperty("user.dir"));
         Picture pane;
         Test(){
              super("Main Program");
              setLayout(new BorderLayout());
              JPanel north = new JPanel();
              add(north, BorderLayout.NORTH);
              north.add(b);
              b.addActionListener(new Listener());
              setVisible(true);
              setSize(500,500);
              pane = new Picture("");
              add(pane, BorderLayout.CENTER);
         class Listener implements ActionListener {
              public void actionPerformed(ActionEvent e){
                   int ans = jfc.showOpenDialog(Test.this);
                   if(ans == jfc.APPROVE_OPTION)
                        File file = jfc.getSelectedFile();
                        Test.this.add(new Picture(file.getName()), BorderLayout.CENTER);
                        pane.add(new JButton("NEW BUTTON")); // Why does this button not appear on the window???
                        pane.repaint();
                        pane.revalidate();
         public static void main(String[] args)
              Test t = new Test();
    class Picture extends JPanel
         Image pic;
         String filename;
         Picture(String filename)
              setLayout(null);
              this.filename = filename;
              pic = Toolkit.getDefaultToolkit().getImage(filename);
            protected void paintComponent(Graphics g)
                super.paintComponent(g);
                g.drawImage(pic,0,0,getWidth(),getHeight(),this);
                revalidate();
    }

  • Unable to capture video from canon xha1s to final cut pro 6.0. so confused

    hi,
    i purchased a canon xha1s and am simply trying to capture the video onto my macbook pro laptop. i keep getting the error saying my settings are incorrect and am confused as what to put and where. i went to the video/audio settings and put what i believed to be correct (HDV) since my camcorder records in HDV. still that error window pops up when i try to log and capture footage.
    any help would be greatly appreciated!

    Hi .. I had a very similar problem .. if the above fails it may be worth a look at this too..
    http://discussions.apple.com/message.jspa?messageID=10804559#10804559
    Jim

Maybe you are looking for

  • How can i convert a window media player file into a format playable on ipod

    hey guys can you tell me how can i convert an widdow media player file into a format that can be played on my ipod, i used videora ipod converter but it can't convert the window media player file

  • Installation of oracle 8.1.5 on solaris8 install

    I have 2.5 GB HardDisk, I installed Solaris8 on intel using autolayout & then I tried to install Oracle8.1.5 on solaris but installation process is hangingup at this oracle.sysman.oii.oiic.oiicInstaller.run(oiicInstaller.Java:287) oracle.sysman.oii.o

  • Best practice on storing configurations

    So a question for you all: It's my understanding that to make a set of LDOM configurations persist across a power cycle, they must be committed to the system controller (presumably it sticks them in some flash/eeprom memory somewhere). As best as I c

  • Sync : Changes in phone do not appear in Lotus Not...

    Hi everyone, I've been fighting with my N73, PC suite and Lotus Note 6.5 for quite some time with this problem... When I sync, it doesn't synch from my phone to my computer although the option for cross sync is checked in the options ! When I sync an

  • IMPORT DYNPRO problem

    HI, I'm using the below statement to fill the these internal tables H_588m, IMP588m, e_588m m_588m . IMPORT DYNPRO H_588M IMP588M E_588M M_588M ID W_DYNPRONAME. But iits enable fill the data. is tehre any conditions r there before using this statemen