Lookingfor help displaying GUI's

I am trying to add buttons to my inventory program and everything complies but the screen comes up and is blank. Can someone point me in the right direction please?
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.*;
public class InventoryButtons extends JFrame
     private JTextField jtfTitle;
    private JTextField jtfItem;
    private JTextField jtfUnits;
    private JTextField jtfPrice;
    private JTextField jtfRestock;
    private JTextField jtfValue;
    private JTextField jtfValueAll;
     static int dispMov = 0;
          int i;
          double total = 0;
          final Movies[]DVDs = new Movies[4];
          for (i = 0; i<4; i++)
        for(int index = 0; index < DVDs.length; index++)
               DVDs[0] = new Movies("Raiders of the Lost Ark", "189", 15, 12.99, "PG-13");
               DVDs[1] = new Movies("Revenge of the Sith", "222", 4, 10.99, "R");
               DVDs[2] = new Movies("Toy Story", "325", 11, 15.95, "G");
               DVDs[3] = new Movies("Memento", "456", 30, 14.00, "R");
        JPanel jpLabels = new JPanel();
          jpLabels.setLayout(new GridLayout(8,1));
          jpLabels.add(new JLabel(" DVD Title:"));
          jpLabels.add(new JLabel(" Item #"));
          jpLabels.add(new JLabel(" Units in Stock:"));
          jpLabels.add(new JLabel(" Price:"));
          jpLabels.add(new JLabel(" Restocking Fee (5%):"));
          jpLabels.add(new JLabel(" Total Value of Inventory:"));
          jpLabels.add(new JLabel(" Value of All Inventory:"));
        JPanel jpTextFields = new JPanel();
          jpTextFields.setLayout(new GridLayout(8,1));
          jpTextFields.add(jtfTitle = new JFormattedTextField());
          jpTextFields.add(jtfItem = new JFormattedTextField());
          jpTextFields.add(jtfUnits = new JFormattedTextField());
          jpTextFields.add(jtfPrice = new JFormattedTextField());
          jpTextFields.add(jtfRestock = new JFormattedTextField());
          jpTextFields.add(jtfValue = new JFormattedTextField());
          jpTextFields.add(jtfValueAll = new JFormattedTextField());
        for(int j1=0; j1 < DVDs.length; ++j1)
            jtfTitle.setText(DVDs[j1].getDvdTitle());
            jtfItem.setText(DVDs[j1].getDvdItem());
            jtfUnits.setText(String.valueOf(DVDs[j1].getDvdStock()));
            jtfPrice.setText(String.valueOf(DVDs[j1].getDvdPrice()));
            jtfRestock.setText(String.valueOf(DVDs[j1].getRestockingFee()));
            jtfValue.setText(String.valueOf(DVDs[j1].inventoryValue()));
            jtfValueAll.setText(String.valueOf(DVDs[j1].CalculateTotalInventoryValue( DVDs)));
     public static void main(String args[])
               InventoryButtons inventorybuttons = new InventoryButtons();
               inventorybuttons.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
               inventorybuttons.setSize(1100,300);
               inventorybuttons.setVisible(true);
     class Inventory
           // instance fields
        private String dvdTitle;
        private String dvdItem;
        private double dvdStock;
        private double dvdPrice;
        //constructor to initialize DVD title, item, stock and price
        public Inventory(String title, String item, double stock, double price)
           dvdTitle = title;
           dvdItem = item;
           dvdStock = stock;
           dvdPrice = price;
        } // end class Inventory constructor
        // set DVD name
        public void setDvdTitle(String title)
           dvdTitle = title;
        } // end method setDvdTitle
        // return DVD name
        public String getDvdTitle()
           return dvdTitle;
        } // end method getDvdTitle
        // set item number
        public void setDvdItem(String item)
           dvdItem = item;
        } // end method setDvdItem
        // return item number
        public String getDvdItem()
           return dvdItem;
        } // end method getDvdItem
        // set number of units in stock
        public void setDvdStock(double stock)
           dvdStock = stock;
        } // end method setDvdStock
        // return number of units in stock
        public double getDvdStock()
           return dvdStock;
        } // end method getDvdStock
        // set price of each unit
        public void setDvdPrice (double price)
           dvdPrice = price;
        } // end method setDvdPrice
        // return price of each unit
        public double getDvdPrice()
           return dvdPrice;
        } // end method getDvdPrice
        // calculate inventory value
        public double inventoryValue()
           return dvdPrice * dvdStock;
        } // end method inventoryValue
         //method to calculate total value of the inventory in an array of products
     public Double CalculateTotalInventoryValue(Inventory[] DVDs)
       Double total = 0.0;
       for(int index = 0; index < DVDs.length; index++)
        Inventory inv = DVDs[index];
        total += inv.inventoryValue();
       return total;
          //sort method
     //method to sort products based on product name
     public Inventory[] SortInventory(Inventory[] DVDs)
       Inventory tmp;
       for (int i = 0; i < DVDs.length; i++)
        for (int j = i + 1; j < DVDs.length; j++)
         String s1 = DVDs.getDvdTitle();
     String s2 = DVDs[j].getDvdTitle();
     if( s1.compareTo(s2) > 0)
     tmp = DVDs[i];
     DVDs[i] = DVDs[j];
     DVDs[j] = tmp;
     return DVDs;
     } // end class Inventory
     class Movies extends Inventory
          //instance field
          private String dvdRating;//DVD Rating
          private double RestockingFee;
          //five argument constructor
          public Movies(String title, String item, double stock, double price, String rating)
          super( title,item,stock,price);
          setDvdRating( rating ); // validate and store DVD rating
          } // end five-argument Movie constructor
          private void setDvdRating(String rating)
               dvdRating = rating;
          } // end method setDvdRating
               // return DVD rating
               public String getDvdRating()
               return dvdRating;
               } // end method getDvdRating
               public void setRestockingFee(double Fee)
               RestockingFee = Fee;
               }//end method setRestockingFee
               public double getRestockingFee()
                    return super.getDvdPrice()*.05;
               }//end method restocking fee
          // calculate total inventory
               public double inventoryValue()
          return super.getDvdStock()*super.getDvdPrice() * 1.05;
                    // end class Movies

Why is all that code not in your constructor? It should be in the constructor. Or some method.
Anyway. You create a JFrame. You create a bunch of Panels. You add a bunch of stuff to the Panels. You never add the Panels to the frame.
Fix the first thing I talked about (put the code in the constructor at least) and then add the panels to the frame.
Edit: due to achieving binary zen this will probably be my last post for today. Good luck.

Similar Messages

  • Hi, need help, displaying text in crystal report

    Post Author: decentsimple
    CA Forum: Crystal Reports
    CR8.5 help, displaying included or not included  i
    have a win app that calls the report, during rendering of report, the
    win app will first create a temp table that holds all the fields for
    the report, then the report is accessing that temptable. i want my report to display &#91;not&#93; included text for a field that contains the right value..here is the tricky part, the field is not in the temp table..is there a way for the crystal report to read the value of that certain field that is not in the temptable..so far.. i have a parameter     3 parameters, the value can be B/P/U          ?B / ?P /?U each parameter have its own formula:  @havefieldvalue        if {?B} = "T" then            ""  else  "Not" same for the rest..if the report generated have B     then the report should display B - includedsame for the rest.. 

    you can always use an array if there's no pattern to your positions:
    var positionA:Array=[ [100,20], [2,222], [55,2], [201,111], [78,23] ];
    import flash.net.URLLoader;
    import flash.net.URLRequest;
    import flash.events.Event;
    import com.adobe.serialization.json.JSON;
    var loader:URLLoader = new URLLoader(new URLRequest("https://api.twitter.com/1/statuses/user_timeline.json?screen_name=ScottMitchell"));
    loader.addEventListener(Event.COMPLETE, loadComplete);
    function loadComplete(e:Event):void {
        processData(e.target.data);
    function processData(data:String):void {
        var tweets:Array = JSON.decode(data) as Array;
    for(var i:int=0;i<5;i++){
    var tf:TextField=new TextField();
    addChild(tf);
    tf.multiline=true;
    tf.width=300;
    tf.text =   tweets[i].text;
    tf.autoSize="left";
    tf.x=positionA[i][0];
    tf.y=positionA[i][1];
    nextY+=tf.height;

  • Set location of the Help display

    try {
    URL url = new URL("file:/c:/help/help.hs"); // the actual location of the help set
    HelpSet hs = new HelpSet(null, url);
    HelpBroker hb = hs.createHelpBroker();
    helpDocsItem.addActionListener(new CSH.DisplayHelpFromSource(hb));
    catch (Exception e) {
    e.printStackTrace();
    I used the above code, and the Help is displayed on the left corner of the screen.
    How to set the location of the Help display? Can I set a frame as its parent? If yes, how to do that?
    Thank you.

    you can use HelpBroker.setLocation and HelpBroker.setSize, but both are new methods introduced in JavaHelp 2.0 beta release only.

  • Help displaying a splash screen.

    Hi Guys.
    I need help displaying a splash screen as an advertisment or something before i have my main application run.
    Here is the code i wrote (it works as if it were a seperate application)
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package MajourProject;
    import java.awt.AWTException;
    import java.awt.Dimension;
    import java.awt.Robot;
    import java.awt.Toolkit;
    import javax.swing.ImageIcon;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JProgressBar;
    import javax.swing.JScrollPane;
    import javax.swing.JWindow;
    * @author Matt
    public class SplashScreen extends JWindow
        public SplashScreen()
    Start();
        public void Start(int UpTime)
            ImageIcon ii = new ImageIcon("src/1.jpg");
              JScrollPane jsp = new JScrollPane(new JLabel(ii));
                    JProgressBar Bar = new JProgressBar();
              getContentPane().add(jsp);
              setSize(853,303);
              centerScreen();
              setVisible(true);
                   try
                                Thread.sleep(20000);
                               dispose();
                   catch(Exception IE)
            private void centerScreen()
                    Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
                    int x = (int) ((d.getWidth() - getWidth()) / 2);
              int y = (int) ((d.getHeight() - getHeight()) / 2);
              setLocation(x, (y-100));
           public static void main(String [] args)
                 new
    }

    And there's a problem with that code, is there?
    I don't really feel like running the code to find out what that problem might be, so let me just point out that splash screens are built into Java 6. Adding a splash screen to your program requires nothing more than using a command-line argument to point at the image file.

  • How to explicitely write PLSQL code for "Help - Display Error"? [SOLVED]

    I'm using menu DEFAULT&SMARTBAR and I'd like to write command in PLSQL code for "Help - Display Error" to display error. Has anyone any idea how to do this? I can not find syntaks in form help for this.
    Message was edited by:
    marussig

    Display_Error;

  • I'm following Firefox Help for Windows XP on "clear cookies & cache." When I open Firefox & follow the Help steps (click on History, Tools, etc.) these aren't active links. I'm clicking on a Help display; no actions are executed. ???

    (On desktop PC) When I open Firefox & follow the Help steps (click on History, Tools, etc.), these aren't active links. I'm clicking on a Help display; no actions are executed. Cookies & cache aren't cleared.

    Make sure that you do not run Firefox in permanent Private Browsing mode.
    *https://support.mozilla.org/kb/Private+Browsing
    To see all History and Cookie settings, choose:
    *Tools > Options > Privacy, choose the setting <b>Firefox will: Use custom settings for history</b>
    *Deselect: [ ] "Always use private browsing mode"

  • Can we display GUI windows/dialog boxes from two asynchronus threads?

    Hi All,
    I'm facing a problem with asynchronous threads. I've a client-server application where client is a Java application and server is a C++ application running on UNIX m/c. The C++ server is implemented equivalent to a HTTP server which handles the HTTP requests from the java client. So, whenever user select some action on the Java client, say "File/Open" menu, the client sends the equivalent HTTP request to the server, and waits for the response back from the server, and after getting the response displays it on the GUI.
    So far the java client application is single-threaded, and the communication between client-server was only one-way, i.e. all the communication was always initiated by the client.
    We had to change this behavior to make it multi-threaded, or rather two-way communication where kernel while processing any client request might need some response from the GUI. So, we had to create a ServerSocket on java client side, and C++ server is connected to this socket. So, whenever C++ server has to send some message to the GUI, it can send thru this other socket.
    On the java side, it's listening at this ServerSocket port in a separate thread, whenever it receives any request, it has to display a dialog box based on the request.
    Here is my problem coming. The main application thread (which is an AWT-EVENT- thread) has made a http request to the kernel and is blocked until it gets the response back, and in the mean time, the C++ server has sent a message to the GUI thru the other socket, and when I use JOptionPane.showOptionDialog(...), I see the dialog box outline but not the contents, and the same for my main application window.
    So main question here is, can I invoke, say,
    JOptionPane.showOptionDialog(...) on another thread, when the main application thread (rather AWT-EVENT -QUEUE thread) is blocked.
    Please let me know if anyone knows the answer or if has faced the similar problem. It will be a big help.
    thanks,
    Ajay

    You mean to make the HTTP request in a separate thread, like below,
    new Thread ( new Runnable() {
    public void run() {
    server.makeHTTPRequest(...);
    }).start();
    But we cannot do this, as there is one more constraint with our application, that it has to behave like single-threaded from user's perspective. i.e. If user has clicked "File/Open" menu, user has to wait until the "File/Open" action is completed. He cannot do anything in between.
    But if the server sends some message thru the other socket, then it has to displayed, and whatever user select on that dialog box, has to be sent to the server thry the same socket.
    I'm not sure whether this possible.
    Here is what I tried to make the http request in a separate thread, and at the same time, keeping the main thread in a wait state until the thread completes:
    new Thread (new Runnable() {
    public void run() {
    synchronized(server) {
    server.makeHTTPRequest(...);
    server.notify();
    }).start();
    synchronized(server) {
    server.wait();
    Even by doing the above it doesn't work, the GUI just hangs. I think the above code is effectively the same as,invoking directly,
    server.makeHTTPRequest(...);
    All I know is it's quite confusing. Does anyone has insight into it.
    thanks,
    Ajay

  • I need help in GUI

    Hi every one..
    I need help in this class. I want to do a modification to the project AddGUI so that it will do subtraction, multiplication and division of two integre numbers, in addition to addition.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class GUIAddition extends JFrame {
       private String output;
       private int number1, number2, sum;
       private JLabel number1Label, number2Label, sumLabel;
       private JTextField number1TextField, number2TextField;
       private JButton addButton, exitButton;
       private JTextArea textArea;
       public GUIAddition()   {
       super("Sum of Two Integer Numbers");
    // Create an instance of inner class ActionEventHandler
       ActionEventHandler handler = new ActionEventHandler();
    // set up GUI
       Container container = getContentPane();
       container.setLayout( new FlowLayout() );
       // set up Label Fields and Text Fields for number1
       number1Label = new JLabel( "Number1" );
       number1TextField = new JTextField( 10 );
       number1TextField.addActionListener( handler );
       container.add( number1TextField );
       container.add( number1Label );
       // for number2
       number2Label = new JLabel( "Number2" );
       number2TextField = new JTextField( 10 );
       number2TextField.addActionListener( handler );
       container.add( number2TextField );
       container.add( number2Label );
       // for sum
       sumLabel = new JLabel( "Sum" );
       textArea = new JTextArea( 1,10 );  // only output, no addAction
       textArea.setEditable( false );
       container.add( textArea );
       container.add( sumLabel );
       // set up Add Button
       addButton = new JButton( "Add" );
       addButton.addActionListener( handler );
       container.add( addButton );
       // set up Exit Button
       exitButton = new JButton( "Exit" );
       exitButton.addActionListener( handler );
       container.add( exitButton );
      }// end constructor
    // Display The Sum of the Two Numbers in displayfield
       public void displayAddition() {
           textArea.setText(output);
      }// end display method
       public static void main( String args[] )   {
          GUIAddition window = new GUIAddition();
          window.setSize(500, 100);
          window.setVisible( true );
      }// end main
       private class ActionEventHandler implements ActionListener {
         public void actionPerformed(ActionEvent event) {
           // process Text Fields: number1 and number2 as well as Add Button events
           if (event.getSource() == number1TextField)
               number1 = Integer.parseInt(event.getActionCommand());
           else if (event.getSource() == number2TextField)
               number2 = Integer.parseInt(event.getActionCommand());
           else if (event.getSource() == addButton){
                   sum = number1 + number2;
                   output = "" + sum;
                   System.out.println("The Result of adding number1: " + number1 +
                   " and number2: " + number2 + " is: " + sum);
           // process Exit Button event
           else if (event.getSource() == exitButton) System.exit(0);
    // Display Information
           displayAddition();
         } // end method actionPerformed
       }// end inner class ActionEventHandler
    }  // end Class GUIAddition

    I try to do it for subtraction, but it didn't work correctly.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class GUIAddition extends JFrame {
       private String output;
       private int number1, number2, sum, sub;
       private JLabel number1Label, number2Label, sumLabel, subLabel;
       private JTextField number1TextField, number2TextField;
       private JButton addButton, subButton, exitButton;
       private JTextArea textArea;
       public GUIAddition()   {
       super("Sum of Two Integer Numbers");
    // Create an instance of inner class ActionEventHandler
       ActionEventHandler handler = new ActionEventHandler();
    // set up GUI
       Container container = getContentPane();
       container.setLayout( new FlowLayout() );
       // set up Label Fields and Text Fields for number1
       number1Label = new JLabel( "Number1" );
       number1TextField = new JTextField( 10 );
       number1TextField.addActionListener( handler );
       container.add( number1TextField );
       container.add( number1Label );
       // for number2
       number2Label = new JLabel( "Number2" );
       number2TextField = new JTextField( 10 );
       number2TextField.addActionListener( handler );
       container.add( number2TextField );
       container.add( number2Label );
       // for sum
       sumLabel = new JLabel( "Sum" );
       textArea = new JTextArea( 1,10 );  // only output, no addAction
       textArea.setEditable( false );
       container.add( textArea );
       container.add( sumLabel );
       // for sub
       subLabel = new JLabel( "Subtraction" );
       textArea = new JTextArea( 1,10 );  // only output, no addAction
       textArea.setEditable( false );
       container.add( textArea );
       container.add( subLabel );
       // set up Add Button
       addButton = new JButton( "Add" );
       addButton.addActionListener( handler );
       container.add( addButton );
       // set up Sub Button
        subButton = new JButton( "Subtraction" );
       subButton.addActionListener( handler );
       container.add( subButton );
       // set up Exit Button
       exitButton = new JButton( "Exit" );
       exitButton.addActionListener( handler );
       container.add( exitButton );
      }// end constructor
    // Display The Sum of the Two Numbers in displayfield
       public void displayAddition() {
           textArea.setText(output);
      }// end display method
       public static void main( String args[] )   {
          GUIAddition window = new GUIAddition();
          window.setSize(500, 100);
          window.setVisible( true );
      }// end main
       private class ActionEventHandler implements ActionListener {
         public void actionPerformed(ActionEvent event) {
           // process Text Fields: number1 and number2 as well as Add Button events
           if (event.getSource() == number1TextField)
               number1 = Integer.parseInt(event.getActionCommand());
           else if (event.getSource() == number2TextField)
               number2 = Integer.parseInt(event.getActionCommand());
           else if (event.getSource() == addButton){
                   sum = number1 + number2;
                   output = "" + sum;
                   System.out.println("The Result of adding number1: " + number1 +
                   " and number2: " + number2 + " is: " + sum);
           else if (event.getSource() == subButton){
                   sub = number1 - number2;
                   output = "" + sub;
                   System.out.println("The Result of subtraction number1: " + number1 +
                   " and number2: " + number2 + " is: " + sub);
           // process Exit Button event
           else if (event.getSource() == exitButton) System.exit(0);
    // Display Information
           displayAddition();
         } // end method actionPerformed
       }// end inner class ActionEventHandler
    }  // end Class GUIAddition

  • Problems displaying GUI and fillRect()

    Hello all, thanks for reading this post ... this is a four part question:
    1)I have a JFrame set up with JButtons along the bottom. There is open space at the top where I would like to display some 2D drawing like fillRect(). In my paint method, when I use fillRect(), my buttons would disappear until I ran the mouse over them. To fix this problem I used a super.paint(g) before my fillRect() and in my paint method. Is there a better way to disiplay 2D images with a GUI?
    2)I am dispalying 2D images directly to the JFrame. Should I use another type of java container like a JPanel to do the 2D output? If so, how would I alter and use the paint method of JPanel (for example) so that I could call it from JFrame.
    3)I need to display repeated rectangles with the fillRect() function. Right now I am including the fillRect() call in the paint method and using another method to loop repaint. I am getting many errors and have a feeling that there is an easier way to achieve repeated display of rectangles. Can anyone offer a better way?
    4)The title bar of my JFrame steals some pixels away from the area that I am trying to draw to. Consequetly, if I try to paint to the coordinates (0,0) i cannot see the coloring becuase it is behind the title bar. I read in a book about something called insets that have variables such as .top .bot .left .right that have the size of the margins taken up (e.g. the title bar). I tried to get such information from my JFrame but didn't have much luck. Any and all help is greatly appreciated.
    To recap, I have a JFrame as my main program, with JButtons at the bottom and open space at the top for displaying 2D images.

    Follow this sample:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Draw2 extends JFrame 
         Tpan     board = new Tpan();
         JButton jb1    = new JButton("sample1");
         JButton jb2    = new JButton("sample1");
    public Draw2()
         super();
         setBounds(1,1,500,400);     
         addWindowListener(new WindowAdapter()
        {     public void windowClosing(WindowEvent ev)
                   dispose();     
                   System.exit(0);
         getContentPane().setLayout(new BorderLayout());
         getContentPane().add("Center",board);
         JPanel con = new JPanel();
         getContentPane().add("South",con);
         con.add(jb1);
         con.add(jb2);
         setVisible(true);
    public class Tpan extends JPanel
    public Tpan()
         setBackground(Color.pink);
    public void paintComponent(Graphics g)
         super.paintComponent(g);
         g.setColor(Color.black);
         for (int i=0; i < 35;i++)
              g.setColor(new Color(i*7,100,250-i*6));
              g.drawRect(i*9,i*6,50,50);
    public static void main (String[] args)
         new Draw2();  
    }       Noah

  • Displaying GUI on other PCs

    hey guys
    so i've got a GUI (as a JSP file) going where i've got it to display the map of a certain county in the US with a few features like pan zoom in enabling/disabling the themes using the Oracle MapViewer API. But now what if i want to be able to access that JSP file from another computer. I've got MapViewer deployed on the Oracle Application Server. Please guide me as to how i could be able to do that. Will there be need to load MapViewer on the other PC? Please help...
    Thanks,
    Avinash

    Hey sorry for the late reply.
    I didn't quite get what you meant. MapViewer is the only application I have deployed after the installation of the Application Server. Please excuse my lack of understanding.
    Is there a way I could access the GUI on another PC?

  • Help!  GUI using two buttons

    Hello all:
    I have created a class for reading and writing to a text file on my hard drive. Also, I have created another class for a GUI to use for opening the text file with a button labeled Display. As you will see in the code below, I have created another button labeled Update. I seek to be able to edit and save the text directly in the text area with the Update button after opening the file with the Display button. Any help would be greatly appreciated. Thanks!
    /** Class TextFile */
    import java.io.*;
    public class TextFile
        public String read(String fileIn) throws IOException
            FileReader fr = new FileReader(fileIn);
            BufferedReader br = new BufferedReader(fr);
            String line;
            StringBuffer text = new StringBuffer();
            while((line = br.readLine()) != null)
              text.append(line+'\n');
            return text.toString();
        } //end read()
        public void write(String fileOut, String text, boolean append)
            throws IOException
            File file = new File(fileOut);
            FileWriter fw = new FileWriter(file, append);
            PrintWriter pw = new PrintWriter(fw);
            pw.println(text);
            fw.close();
        } // end write()
    } // end class TextFile
    /** Class TextFileGUI */
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class TextFileGUI implements ActionListener
        TextFile tf = new TextFile();
        JTextField filenameField = new JTextField (30);
        JTextArea fileTextArea = new JTextArea (10, 30);
        JButton displayButton = new JButton ("Display");
        JButton updateButton = new JButton ("Update");
        JPanel panel = new JPanel();
        JFrame frame = new JFrame("Text File GUI");
        public TextFileGUI()
            panel.add(new JLabel("Filename"));
            panel.add(filenameField);
            panel.add(fileTextArea);
            fileTextArea.setLineWrap(true);
            panel.add(displayButton);
            displayButton.addActionListener(this);
            panel.add(updateButton);
            updateButton.addActionListener(this);
            frame.setContentPane(panel);
            frame.setSize(400,400);
            frame.setVisible(true);
        } //end TextFileGUI()
        public void actionPerformed(ActionEvent e)
            String t;
            try
                t = tf.read(filenameField.getText());
                fileTextArea.setText(t);
            catch(Exception ex)
                fileTextArea.setText("Exception: "+ex);
            } //end try-catch
        } //end actionPerformed()
    } //end TextFileGUI

    Swing related questions should be posted in the Swing forum.
    You are using the same ActionListener for both buttons, so you need to be able to tell which button was pressed. There are a couple of ways to do this:
    a) use the getSource() method of the ActionEvent and compare the source against your two buttons to see which one was pressed and then invoke the appropriate code.
    Object source = e.getSource();
    if (source == displayButton)
        //  do display processing
    else if (source == updateButton)
        //  do update processingb) Check the action command to determine which button was clicked. This approach is demonstrated in the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/button.html]How to Use Buttons
    Another option is to create separate ActionListeners for each button so there is no confusion
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import javax.swing.*;
    class TextAreaLoad
         public static void main(String a[])
              final JTextArea edit = new JTextArea(5, 40);
              JButton read = new JButton("Read some.txt");
              read.addActionListener( new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        try
                             FileReader reader = new FileReader( "some.txt" );
                             BufferedReader br = new BufferedReader(reader);
                             edit.read( br, null );
                             edit.requestFocus();
                        catch(Exception e2) { System.out.println(e2); }
              JButton write = new JButton("Write some.txt");
              write.addActionListener( new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        try
                             FileWriter writer = new FileWriter( "some.txt" );
                             BufferedWriter bw = new BufferedWriter( writer );
                             edit.write( bw );
                             edit.setText("");
                             edit.requestFocus();
                        catch(Exception e2) {}
              JFrame frame = new JFrame("TextArea Load");
              frame.getContentPane().add( new JScrollPane(edit), BorderLayout.NORTH );
              frame.getContentPane().add(read, BorderLayout.WEST);
              frame.getContentPane().add(write, BorderLayout.EAST);
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.pack();
              frame.setLocationRelativeTo( null );
              frame.setVisible(true);
    }

  • Canon HF R400 Chromatic Aberration and Blocking Zooming, Hard Time Focusing, LCD Display GUI

    An otherwise nice cam for the price point especially end-of-the model year. I'm going to keep for primarily shooting youtube collectibles in a controlled environment of clamp lights with diffusers and either Auto White Balance or 'P' mode.
    1. In my optical zoom tests (it's nice there's four speed options. I use number 3. The cam exhibits a lot of chromatic aberration which is purple, white ,or even green fringing around the subject matter. I shot of a telephone pole transformer box in bright light, the sky behind it, tree branches and snow on hedges in winter.
    2. On a couple occasions when I zoomed in from about estimated 100-150yds the sky exhibited large blocky pixels for a second. But if I took it to an amusement park to shoot roller coasters I'd hold my breath for both reasons.
    3. It has a hard time adjusting focus when zoomed in even from a close 1-6ft distance to record detail of collectibles or leaves on bushes etc.
    4. The amount of display items on the LCD GUI is too much. Even the cheap Samsung F90 has a button to turn it off. Am I missing something. I read the 197pg PDF manual. Is there a way to turn off or at least reduce the number of items I don't need to see in order to actually shoot a video/picture? In still life tests. I had to take photos with the cam. Look at them. Then adjust. Then repeat. Just to see the composition. Kind of like in the day when pro photographers would take Polaroids prior to the film shot.
    Note: If I'm allow to post youtube links or at least the titles of the videos to demonstrate in the near future when I upload examples of the Likes and Dislikes of my purchase I'd like to know from a Canon moderator (thanx in advance).

    Hi ElectroT2!
    Thanks for posting.
    Chromatic aberration is not always something that can be completely eliminated.  It most often appears when shooting a subject in the foreground that highly contrasts with the background  Chromatic aberration is caused by a lens having a different refractive index for different wavelengths of light.  Because each hue in the spectrum is not focused at a single point, colored halos or fringing appears.  There are two types of chromatic aberration:  longitudinal, where different wavelengths are focused at different distances from the lens, and lateral, where different wavelengths are focused at different positions on the focal plane.
    Are you zooming optically or digitally when you see the "blockiness" in the image?  If digital zoom is being used, it would explain why you see it.  Digital zoom appears as the light blue area of the zoom bar.  When you zoom digitally, the image is basically cropped and expanded more and more as you zoom.  Because of this, the image quality will deteriorate the more you zoom in.  You can select the type of zoom used in the settings menu under [Zoom Type].
    Autofocus may not work well on the following subjects:
    - Reflective surfaces
    - Subjects with low contrast or without vertical lines
    - Fast moving subjects
    - Through wet windows
    - Night scenes
    You can always adjust the focus manually by selecting [ Focus] in the menu.  You can then touch a subject that appears inside the frame, then touch and hold to adjust focus.  When it is focused where you want it, then touch [ X ] to lock the focus.  Something that may help you is when you are focusing manually, you can touch inside the frame to automatically focus on that spot to help you with the adjustment process.
    As for the onscreen displays you are describing, they cannot be disabled so that only the subject appears on the LCD.  You can, however, keep them from being displayed when the camcorder is connected to an external monitor.  The setting is in the menu under the tab.  It is called [Output Onscreen Displays].
    This didn't answer your questions? Find more help at Contact Us.
    Did this answer your question? Please click the Accept as Solution button so that others may find the answer as well.

  • Help with GUI project.

    I need help with JcomboBox when I select the Exit in the File box it will open
    //inner class
    class exitListener implements ActionListener {
    I have the part of the parts of statement but I don't know how to assign the Keystoke. here is that part of the code
    filemenu.setMnemonic(KeyEvent.VK_X);Here is my code...
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class MyFrame extends JFrame {
         String[] file = { "New", "Open", "Exit" };//items for file
        String[] edit = { "Cut", "Copy", "Paste" };//items for edit
        JComboBox filemenu = new JComboBox();
        JComboBox editmenu = new JComboBox();
         public MyFrame(String title) {
              super(title);
              this.setSize(250, 250); //sets the size for the frame
              this.setLocation(200, 200);//location where frame is at
              this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              // setup contents
              makeComponents();
              initComponents();
              buildGUI();
              // display
              this.setVisible(true);
         private void makeComponents() {
              JPanel pane = new JPanel();
    //          file menu section
              filemenu = new JComboBox();
            JLabel fileLabel = new JLabel();
            pane.add(fileLabel);
            for (int i = 0; i < file.length; i++)
                 filemenu.addItem(file);
    pane.add(filemenu);
    add(pane);
    setVisible(true);
    //edit menu section
    editmenu = new JComboBox();
    JLabel editLabel = new JLabel();
    pane.add(editLabel);
    for (int i = 0; i < edit.length; i++)
         editmenu.addItem(edit[i]);
    pane.add(editmenu);
    add(pane);
    setVisible(true);
         private void initComponents() {
              filemenu.addActionListener(new exitListener());
         //inner class
    class exitListener implements ActionListener {
    public void actionPerformed(ActionEvent arg0) {
    int x = JOptionPane.showOptionDialog(MyFrame.this, "Exit Program?",
    "Exit Request", JOptionPane.YES_NO_OPTION,
    JOptionPane.QUESTION_MESSAGE, null, null,
    JOptionPane.NO_OPTION);
    if (x == JOptionPane.YES_OPTION) {
    MyFrame.this.dispose();
         private void buildGUI() {
              Container cont = this.getContentPane();// set gui components into the frame
              this.setLayout(new FlowLayout(FlowLayout.LEFT));// Comp are added to the frame
              cont.add(filemenu);
              cont.add(editmenu);
         // / inner classes
    public class ButtonFrame {
         public static void main(String[] args) {
              MyFrame f1 = new MyFrame("This is my Project for GUI");
    Thanks
    SandyR.

    One way is to
    1) pass a reference of the Window object to the USDListener class, and set a local Window variable say call it window, to this reference.
    2) Give the Window class a public method that returns a String and allows you to get the text from USDField. Same to allow you to set text on the euroField.
    3) Give the Listener class a Converter object.

  • Help displaying an image using the canvas!!!!!!!!

    Hey guys
    I don't know whether I am not grasping some concepts well.I have been going mad trying to get the code working
    Here is the code
    import javax.microedition.midlet.*;
    import javax.microedition.lcdui.*;
    import java.io.*;
    * @author Administrator
    * @version
    public class MyMIDlet extends javax.microedition.midlet.MIDlet implements CommandListener{
    private Display display;
    private MyCanvas canvas;
    private Command exitcommand = new Command("Exit",Command.SCREEN,1);
    private Image source;
    public MyMIDlet() {
    protected void startApp() throws MIDletStateChangeException{
    if (display == null){
    initMIDlet();
    protected void pauseApp() {
    protected void destroyApp(boolean unconditional)throws MIDletStateChangeException {
    exitMIDlet();
    public void commandAction(Command c, Displayable d) {
    if (c == exitcommand){
    exitMIDlet();
    protected void initMIDlet() {
    display = Display.getDisplay(this);
    canvas = new MyCanvas(this);
    System.err.println("Canvas instiated succesfully");
    canvas.addCommand(exitcommand);
    canvas.setCommandListener(this);
    display.setCurrent(canvas);
    public void exitMIDlet() {
    notifyDestroyed();
    import javax.microedition.lcdui.*;
    import javax.microedition.midlet.*;
    import java.io.*;
    public class MyCanvas extends Canvas implements Runnable {
    private MIDlet midlet;
    private Image offscreen;
    private Image currentimage;
    private Graphics g;
    //MID profile application
    /** Creates a new instance of MyCanvas */
    public MyCanvas(MIDlet midlet) {
    this.midlet = midlet;
    try{
    currentimage = Image.createImage("/bird0.png");
    }catch(IOException e){
    System.err.println(e.getMessage());
    if (currentimage!= null){
    System.err.println("Image create successfully");
    }else{
    System.err.println("Image not created");
    try{
    Thread t = new Thread(this);
    t.start();
    }catch(Execption e){}
    protected void paint(Graphics g){
    Graphics saved = g;
    int x = getWidth();
    int y = getHeight();
    g.setColor(255,255,255);
    g.drawImage(currentimage,x,y,g.TOP|g.VCENTER);
    public void run() {
    repaint();
    I know for a fact that the Canvas class 's paint method is called by the system and not the application. This poses a problem for me because I am not sure how to pass the image to the piant method, so that it can be painted.
    When I run the program(using J2ME wtk04), this is the outcome.
    Image created succesfully
    Canvas instiatiated successfully
    null
    Here are my questions
    1) when is the paint method precisely called by the system?after a reference to the canvas class is created?
    2) is it wise to create the image when instiating the canvas class?( initially created the image using a separate thread)-when sould the image be created?
    3)how to let the application know when to use the image when painting the display area?
    I am just trying the logistics here. It is very crucial to me to understand the bolts of this as the core f my project fouses on the man machine interface development.(For the project, the cilent application is quering for the map using HTTP)
    I use a png file of size 161 bytes. Is that too big for testing purposes.
    I would all the help that I can get. thanks in advance

    1) when is the paint method precisely called by the system?after a reference to the canvas class is created?
    After the canvas is set as the current display, and after that, after the repaint() is called.
    2) is it wise to create the image when instiating the canvas class?( initially created the image using a separate thread)-when sould the image be created?
    It's better to create the image in the very begining of the program e.g. in the midlet initialization. You can call the created image as often as you like later on
    3)how to let the application know when to use the image when painting the display area?
    you have to tell it :))
    you can use if-then, switch, or anything else
    and you can use clipping too

  • Urgent! Need help in GUI!

    Hi, I am doing a small java project and I am expected to code all the GUI I need in just one class file. Can someone help me? My GUI consists of 2 JButtons, 2 JLabels and 1 JTextField. Also I need to have ActionListener for both of the buttons all in just 1 class file. Anyone please help. It is better if you can provide me with some sample coding to view

    That sounds like a very arbitrarily cooked-up requirement. Homework?
    Assuming your class needs to be a component itself, simply add the buttons, labels and fields into it, typically within the constructor.
    If you mean "one source file" then I would advise using an inner class as your ActionListener; you may even want two. You may like to use anonymous classes which, for instance, call methods in your outer class. All of these solutions will produce more than one class file from the single source file.
    If you really do mean "one class file" then you will need your outer class to implement ActionListener and determine from the getActionCommand() or getSource() methods which of the two buttons the event emanated from. It's a less clean way of going about it, but you get your single class file.
    No sample code - if you need further explanation of the above then just Google for the underlined terms.

Maybe you are looking for