Arrays/gui

I am trying to get an array of textfields appear on a GUI, but when i executed the code i have, this appeared on the GUI...
colums=3,columnWidth=0,command=,horizontalAlignment=LEADING]javax.swing.JTextField[,0,0,0x0,invalid,layout=javax.swing.plaf.basic.BasicTextUI$
yada yada...thats the only section i could cut out, but its obviously longer. What does that mean I'm doing wrong?
Thanks

You are probably doing
String s= myControl.toString();
as opposed to
String s = myControl.getText().toString();
or better
String s = myControl.getText();

Similar Messages

  • Image Array , GUI Issue

    I am currently trying to insert a 20X20 image a specific spot on an array spot[X][Y], but do not know how to get them in the array.
    Can anyone help me?
    I am using JPanel and want the images to be displayed within the GUI.

    AWebster wrote:
    How would i be able to do this? By reading the Sun Swing tutorials JLabel section and by playing with JLabels and ImageIcons first before trying to incorporating them into your main application.
    And sorry im a Beginner, but would this mean i would have to make 100 separate JLabels to fill the 10X10 grid for the array?Yes, you'd have to make 100 JLabel objects, but not 100 separate JLabel variables as all the JLabel objects would be held in a single 10 by 10 array.
    Is this a memory game application?

  • Problem with an array

    i have problem with my program i implement saveing method
    but when i open file( game.txt) it does not update my board it return same postion every time i same game
    chess class Jframe(Jfilechooser)(call an board array)---->
    Gui Japplet class( call and board array------------>
    Board(class Jpanel have board array)
    it does not update borad array
    it just call it once in start and return the same value every time
    classChess(){
    ChessPlayer  java = new ChessPlayer();
    public  void saveData()
        File file = null;
       JFileChooser fc = new JFileChooser();
       fc.setCurrentDirectory(new File("."));
        fc.setDialogTitle("Save Text As...");
       int returnVal = fc.showSaveDialog(this);
       if (returnVal == JFileChooser.APPROVE_OPTION)
       { file = fc.getSelectedFile();
         try
         { PrintWriter out =
          new PrintWriter(
         new BufferedWriter(
           new FileWriter(file)));
         //while for all the moves in the array>
    for (int i=0;i<120;i++)
         out.println( java.saveDAta(i));
         out.println("\n");
         out.close();
         catch (IOException e) {
              // Some error has occured while trying to read the file.
                // Show an error message.
             JOptionPane.showMessageDialog(this,
                   "Sorry, some error occurred:\n" + e.getMessage());}
    public static void main(String[] args) {
    JPopupMenu.setDefaultLightWeightPopupEnabled(false);
         JFrame frame = new ChessMan();
         Container content = frame.getContentPane();
         ChessMan f = new ChessMan();
              //japplet
         ChessPlayer  javaAppletication = new ChessPlayer();
            javaAppletication.init();
            javaAppletication.start();
       }Gui
    [Gui]
    class Gui{
    int [] board = new int [120];
         int [] boardcolor = new int [120];     
    Board check = new Board(this,false);
    {public void init()
         {        // Create new Border
         contentPane = getContentPane();
         bboard = new Board(this,false);
    public String saveDAta(int i)
    String l=check. save(i);
    return (l);
    and finally board Jpanel
    class Board extends JPanel
    {public Board (JApplet useapplet,boolean bool) {
       setup();
    { public String  save(int i)
         {  String l;
                   if (color==1)
                 {System.out.println("notpossible");}
               l =  board[i]+"$"+boardColor;
    return l;
    thanks guys

    My Jframe
    public class ChessMan extends JFrame implements ActionListener, WindowListener  {
    JMenuItem saveItem, loadItem, copyItem, pasteItem; 
    JMenu fileMenu, editMenu; 
    JMenuBar bar;
    ChessPlayer  java = new ChessPlayer();
    public ChessMan()  { setTitle("CHESS PLAYER GAME" );
    setSize(200,300);
    System.out.println("\n");      }
    addWindowListener(new java.awt.event.WindowAdapter()
         {      public void windowClosing(java.awt.event.WindowEvent e)
         {        System.exit(0);      }    });
    JMenu fileMenu = new JMenu("File");
    saveItem = new JMenuItem("Save");
    saveItem.setActionCommand("save");
    saveItem.setAccelerator( KeyStroke.getKeyStroke("ctrl S"));
    saveItem.addActionListener(this);
    fileMenu.add(saveItem);
    loadItem = new JMenuItem("Load");
    loadItem.setActionCommand("load");
    loadItem.setAccelerator( KeyStroke.getKeyStroke("ctrl L"));
    loadItem.addActionListener(this);
    fileMenu.add(loadItem);
    JMenu editMenu = new JMenu("About");
    copyItem = new JMenuItem("Help");
    copyItem.setActionCommand("Help");
    copyItem.setAccelerator( KeyStroke.getKeyStroke("ctrl H"));
    copyItem.addActionListener(this);
    editMenu.add(copyItem);
    pasteItem = new JMenuItem("Exit");
    pasteItem.setActionCommand("Exit");
    pasteItem.setAccelerator( KeyStroke.getKeyStroke("ctrl E"));
    pasteItem.addActionListener(this);
    editMenu.add(pasteItem);
    JMenuBar bar = new JMenuBar();
    bar.add(fileMenu);
    bar.add(editMenu);
    setJMenuBar(bar);
    setVisible(true);
    setLocation(0,0);
    public void actionPerformed(ActionEvent e) {
    JMenuItem item = (JMenuItem)e.getSource();
    String    ac   = item.getActionCommand();
    System.out.println("ac = "+ ac);
    // you can use action commands to track menu item events   
    if(ac.equals("save"))
         {System.out.println("ac.equals(\"save\") = "+ ac.equals("save"));
            saveData();}
    if(ac.equals("load"))
    {System.out.println("ac.equals(\"load\") = "+ ac.equals("load"));
                         loadingData();}
       if(ac.equals("Help"))
    {System.out.println("ac.equals(\"load\") = "+ ac.equals("Help"));
    if(ac.equals("Exit"))
    {System.out.println("ac.equals(\"load\") = "+ ac.equals("Exit"));
                         Exit();}                   
    // the event origin  
    if(item == saveItem)
         System.out.println("item = "+ item.toString().substring
         (item.toString().indexOf("text=") + 5, item.toString().lastIndexOf("]")));
    if(item == loadItem)
         System.out.println("item = "+ item);
    //   System.out.print( java.saveDAta());
    public  void saveData()
        File file = null;
       JFileChooser fc = new JFileChooser();
       fc.setCurrentDirectory(new File("."));
        fc.setDialogTitle("Save Text As...");
       int returnVal = fc.showSaveDialog(this);
       if (returnVal == JFileChooser.APPROVE_OPTION)
       { file = fc.getSelectedFile();
         try
         { PrintWriter out =
          new PrintWriter(
         new BufferedWriter(
           new FileWriter(file)));
         //while for all the moves in the array>
    for (int i=0;i<120;i++)
         out.println( java.saveDAta(i));
         out.println("\n");
         out.close();
         catch (IOException e) {
              // Some error has occured while trying to read the file.
                // Show an error message.
             JOptionPane.showMessageDialog(this,
                   "Sorry, some error occurred:\n" + e.getMessage());}
       public  void loadingData()
       File loadfile = null;
       JFileChooser fc = new JFileChooser();
          fc.setDialogTitle("OpenFile...");
       fc.setCurrentDirectory(new File("."));
        int returnVal = fc.showOpenDialog(this);
       if (returnVal == JFileChooser.APPROVE_OPTION)
       { loadfile = fc.getSelectedFile();
          try
         { PrintWriter out =
         new PrintWriter(
         new BufferedWriter(
           new FileWriter(loadfile)));
         //while for all the moves in the array>
            out.println("�����������������");
         out.println("\n");
         out.close();
         catch (IOException e) {
              // Some error has occured while trying to read the file.
                // Show an error message.
             JOptionPane.showMessageDialog(this,
                   "Sorry, some error occurred:\n" + e.getMessage());}
    public void Exit()
    System.exit(0);
    public static void main(String[] args) {
    JPopupMenu.setDefaultLightWeightPopupEnabled(false);
         JFrame frame = new ChessMan();
         Container content = frame.getContentPane();
         ChessMan f = new ChessMan();
         f.setLocation(300,300);
         f.show();
                 ImageIcon customImageIcon = new ImageIcon("ac516.gif");
              Image customImage = customImageIcon.getImage();
              frame.setIconImage(customImage);
                 //japplet
         ChessPlayer  javaAppletication = new ChessPlayer();
         // i could not put my constructor here <Static>     
    javaAppletication.init();
    javaAppletication.start();
    // for(int i=0; i < .length(); i++)
    content.add(javaAppletication, BorderLayout.CENTER);
         frame.getContentPane();
    javaAppletication.setBackground (Color.black);
         frame.setVisible(true);
    frame.show();
    frame.pack(); // invokes getPreferredSize()
    // invokes paint();
    public void windowOpened(WindowEvent e) {
    fileMenu.doClick();
    public void windowClosing(WindowEvent e) {}
    public void windowClosed(WindowEvent e) {}
    public void windowIconified(WindowEvent e) {}
    public void windowDeiconified(WindowEvent e) {}
    public void windowActivated(WindowEvent e) {}
    public void windowDeactivated(WindowEvent e) {}
    My Japplet Class
    class ChessPlayer extends JApplet
         implements ActionListener,MouseListener              
    int c;
         //Reference for new Board
               Board bboard;
         //Reference for Button
             JButton newgame,undo,onePlayer,TwoPlayer,NormalPieceSet,
             FuunyPieceSet,startButton,stopButton;
         //Reference for Label  
              JLabel message;
        //Reference for new Panel
             JPanel buttonpanel2,buttonpanel,messagepanel,buttonpane;
         //Initilize the  Applet
          DemoAnimation Demo;
          Container contentPane;
           Board check = new Board(this,false);
               int [] board = new int [120];
           int [] boardcolor = new int [120];
         public void init()
                   // Create new Border
            contentPane = getContentPane();
         check = new Board(this,false);          
         bboard = new Board(this,false);
         bboard.setPreferredSize(new Dimension(500,400));
        bboard.setBorder(BorderFactory.createLineBorder( Color.red ) ); 
         contentPane.add(bboard);   
         final ImageIcon image = new ImageIcon("ac516.gif");
         bboard.addMouseListener(this);
         bboard.setBackground (Color.black); 
         BorderLayout text=new BorderLayout();
        Demo = new DemoAnimation( this );
         Demo.setPreferredSize(new Dimension(160, 500));
         contentPane.add(Demo);
        // Set Background Black
         contentPane.setBackground (Color.black); 
         contentPane.setLayout (new BorderLayout (50,50));
         // set new Font "TimesRoman"
         Font Text= new Font("TimesRoman", Font.BOLD,15);
         //panel to keep buttons together
         buttonpanel=new JPanel();
         buttonpanel.setLayout(new GridLayout(1,2,6,0));
         buttonpanel.add(newgame=new JButton("new game",image));
         newgame.addActionListener(this);
         buttonpanel.add(undo=new JButton("undo"));
         undo.addActionListener(this);
         // Create new Choice Panel                      
         buttonpanel2 = new JPanel();
         buttonpanel2.setLayout(new GridLayout(6,1,0,10));
         buttonpanel2.add(onePlayer=new JButton("Change Colour"));
         onePlayer.addActionListener(this);
         buttonpanel2.add(TwoPlayer=new JButton("Statistic"));
         TwoPlayer.addActionListener(this);
         buttonpanel2.add(NormalPieceSet=new JButton("Quit"));
         NormalPieceSet.addActionListener(this);
         buttonpanel2.add(FuunyPieceSet=new JButton("Change Piece"));
        FuunyPieceSet.addActionListener(this);
        buttonpanel2.add(startButton = new JButton("Start Animation"));
         startButton.addActionListener(this);
         buttonpanel2.add(stopButton  = new JButton("Stop Animation"));
         stopButton.addActionListener(this);
            contentPane.add(BorderLayout.WEST, demopanel);
    // Set Font For Text Message
         setFont(Text);
         messagepanel=new JPanel();
         messagepanel.setBorder(BorderFactory.createLineBorder( Color.red ) );
         messagepanel.setBackground(Color.black);
    //     essagepanel.setLayout(new GridLayout(1,1));
         // Create new Label
         messagepanel.add(message = new JLabel());               
         setMessage("Welcome");
         // Postion panels in  Layout                
         contentPane.add("North",buttonpanel);
         contentPane.add("East",buttonpanel2);
         contentPane.add ("South",messagepanel);     
         contentPane.add ("Center",bboard);
         contentPane.add("West",Demo);
    public void mouseReleased(java.awt.event.MouseEvent e)
    {  statuseChange();}
    public void mouseClicked(java.awt.event.MouseEvent e)
    public void mouseEntered(java.awt.event.MouseEvent e) {     
    public void mouseExited(java.awt.event.MouseEvent e) {
    public void mouseMoved(java.awt.event.MouseEvent e) {
    statuseChange();
    public void mousePressed(java.awt.event.MouseEvent e)
    {statuseChange();
    public void actionPerformed(ActionEvent e)
         Object source=e.getSource();
         if (source == newgame)
              {  bboard.newgame();
                yellow();
              setMessage("try again");
              pause(100);
              c=add(c);
         else if (source==undo)
                  yellow();
              bboard.undo();
         setMessage("Undo");
         else if (source== TwoPlayer )
              //bboard.setup();
                 yellow(); 
              setMessage("Starting new Game");
         setMessage("Change Color");
         else if(source == FuunyPieceSet)
              {yellow();
              setMessage("game played::" +c);
              bboard.PieceChange();
         else if(source == NormalPieceSet)
              {yellow();
              setMessage("GOODBYE");
              destroy();
          else if(source == startButton)
              {yellow();
              setMessage("Start Animation");
              Demo.start();
         else if(source == stopButton)
              {yellow();
              setMessage("Stop Animation");
              Demo.stop();
              else if(source == onePlayer)
              {setMessage("");
              bboard.changePiece();
              setMessage("Change Color");
           public void statuseChange()
                switch (bboard.gameStatus())
            case 1:
                red();
               setMessage("White won");
           break;
      case 2:
            red();
            setMessage("Black won");
         break;
      case 3:
          red();
           setMessage("DRAW");
         Demo.changeAnimation(2);
           break;
      case 4:
           white();
           setMessage("White Turn");
           Demo.changeAnimation(1);
           break;
      case 5:
           green();
           setMessage("Black turn");
           Demo.changeAnimation(3);
         break;
      case 6:
           red();
            setMessage(" Check");
            Demo.changeAnimation(4);
              break;
      case 7:
           red();
           setMessage("Check");     
            Demo.changeAnimation(4);
            break;
      case 8:
           yellow();
           setMessage("I Hope you enjoyed it");     
    public String saveDAta(int i)
    String l=check.save(i);
    return (l);   
    public void LoadData(String load)
    public void setMessage(String s)
                /*The string s will be shown to the user.*/
         Font Text= new Font("Courier", Font.BOLD,30);
                       message.setText(s);
                       message.setFont(Text);
              public void white()
                   {  message.setForeground(Color.white);}
              public void green()
                     message.setForeground(Color.green);
                   public void red()
                          message.setForeground(Color.red);
                   public void yellow()
                        message.setForeground(Color.yellow);
             //  pause method       
              void pause(int time)
      try {Thread.sleep(time);
    }     catch (InterruptedException e)
         // Create new inset Object
         public Insets getInsets()
         return new Insets(50,220,150,200);
    public void destroy()
    contentPane.remove(buttonpanel2);
    contentPane.remove(buttonpanel);
    contentPane.remove(bboard);
    contentPane.repaint();
    Demo.start();
    public int add(int x)
         { int b=x+1;
          return b;
    }tanx man i dont the other two because they are to long
    my is when i open jframe
    i think Japplet and Jframe can not commuinicate to each other

  • Pleas  can someone help me

    i have problem with my program i implement saveing method
    but when i open file( game.txt) it does not update my board it return same postion every time i same game
    chess class Jframe(Jfilechooser)(call an board array)---->
    Gui Japplet class( call and board array------------>
    Board(class Jpanel have board array)
    it does not update borad array
    it just call it once in start and return the same value every time
    classChess(){
    ChessPlayer  java = new ChessPlayer();
    public  void saveData()
        File file = null;
       JFileChooser fc = new JFileChooser();
       fc.setCurrentDirectory(new File("."));
        fc.setDialogTitle("Save Text As...");
       int returnVal = fc.showSaveDialog(this);
       if (returnVal == JFileChooser.APPROVE_OPTION)
       { file = fc.getSelectedFile();
         try
         { PrintWriter out =
          new PrintWriter(
         new BufferedWriter(
           new FileWriter(file)));
         //while for all the moves in the array>
    for (int i=0;i<120;i++)
         out.println( java.saveDAta(i));
         out.println("\n");
         out.close();
         catch (IOException e) {
              // Some error has occured while trying to read the file.
                // Show an error message.
             JOptionPane.showMessageDialog(this,
                   "Sorry, some error occurred:\n" + e.getMessage());}
    public static void main(String[] args) {
    JPopupMenu.setDefaultLightWeightPopupEnabled(false);
         JFrame frame = new ChessMan();
         Container content = frame.getContentPane();
         ChessMan f = new ChessMan();
              //japplet
         ChessPlayer  javaAppletication = new ChessPlayer();
            javaAppletication.init();
            javaAppletication.start();
       }Gui
    class Gui{
    int [] board = new int [120];
         int [] boardcolor = new int [120];     
    Board check = new Board(this,false);
    {public void init()
         {        // Create new Border
         contentPane = getContentPane();
         bboard = new Board(this,false);
    public String saveDAta(int i)
    String l=check. save(i);
    return (l);   
          }and finally board Jpanel
    class Board extends JPanel
    {public Board (JApplet useapplet,boolean bool) {
       setup();
    { public String  save(int i)
         {  String l;
                   if (color==1)
                 {System.out.println("notpossible");}
               l =  board[i]+"$"+boardColor;
    return l;
    thanks guys

    With some basic print-outs (System.out.println(...)) of what you ACTUALLY read and write and what values are in your board etc, you should see what goes wrong.
    Gil

  • How to view C/C++   pointer as an array in Xcode GUI debugger?

    How to view C/C++ pointer as an array in Xcode GUI debugger?

    A similar question was asked recently regarding strings. You cannot pass pointers in LabVIEW as you do in C. You can pass an array to a DLL, but that means you would need to write a wrapper DLL. Be sure to read the section in the LabVIEW Help on calling code from text-based languages and also take a look at the "Call DLL" example that ships with LabVIEW  - it contains many examples of how to deal with various datatypes.

  • How to create a array of GUI components?

    Hello, everyone!
    I need help or advice how to create an GUI components array. As I remenber in VB this possible just by calling two or more buttons (for example) with the same name. The API will authomatically create an array: Buton[0], Button[1], Button[2] and so on...
    In Java it possible as well:
    JButton button[];
    button = new JButton[10];
    for ( int i = 1; i < 10; i++ ){
    button[i] = new JButton();
    ....and so on....
    But my problem is that I use Forte for Java v. 3.0 and when I using Frame Editor it does not allow me to call two components with the same name and at the same time does not allow to change the initialization code painted in blue color...
    Does anyone knows how to avoid this, or how to create GUI components array in Forte for Java API using Frame Editor or Component Inspector???
    All that I need is few buttons accessible by index ( button[1], button[2] etc.) I will apreciate any help or advise.
    Thank you in advance,
    Michael

    I tried using Forte after having used Windows notepad and found that I
    like notepad much better. If you seem to be having problems with Forte,
    you might just try writing this portion of code in a regular text editor
    and compiling it with a command line compiler. Hope this helps some.

  • Gui connect to a store array

    Hi, beasicaly i have a gui created in awt and I want the details entered into the gui to be saved in my store array but I don't know how to do this, so help would be great :) ...i think its along the lines of :
    store[n] = name.getText();
    Not sure though ?
    Thanks

    No.
    The variable "store" is of the type "Store", i.e. a single Store, not an array. You need to declare the variable to be of the type "Store[]". It would make more sense to name it "stores" in that case, of course.
    Obviously, your variable "n" needs to contain an integer value that is within the bounds of the array, not a Student. Your code really makes no sense at all. Perhaps this tutorial will help (there are other tutorials there as well).

  • GUI array information cycler help please

    I currently have a program that has 3 classes. Basically one class is the main and has some information hard coded that it submits to one of the other classes. The second class takes that information, formats it and sends it to the third class. The third class creates an array, takes the information from the second class and has a display method that the main can call to display the information.
    The program basically spews out all the information in the array in a specific format. The array elements contain strings, ints and doubles. The third class also calculates some things that are displayed with the display method in main.
    What I need to do is create a third class. This class needs to make a GUI to display the information. I currently have the programs display method display the information in a GUI but I need it to display each element one at a time with a NEXT and PREVIOUS button. The next button needs to go to the next array element and the previous button obviously needs to go back to the array element.
    Here is the code.
    //  Inventory Program
    //  Created June 20, 2007
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Inventory4 {
        public static void main(String[] args) {
            CD cd;
            Inventory inventory = new Inventory();
            cd = new CDWithGenre(16, "Disney Hits", 11, 13.01f, "Soundtrack");
            inventory.add(cd);
            cd = new CDWithGenre(12, "The Clash", 10, 19.99f, "Classic Rock");
            inventory.add(cd);
            cd = new CDWithGenre(45, "Dixie Chiks", 18, 10.87f, "Country");
            inventory.add(cd);
            cd = new CDWithGenre(32, "The Cure", 62, 25.76f, "Alternative");
            inventory.add(cd);
            cd = new CDWithGenre(18, "MS Office", 27, 99.27f, "None");
            inventory.add(cd);
            inventory.display();    
        } //End main method
    } //End Inventory4 class
         /* Defines data from main as CD data and formats it. Calculates value of a title multiplied by its stock.
          Creates compareTo method to be used by Arrays.sort when sorting in alphabetical order. */
    class CD implements Comparable{
        //Declares the variables as protected so only this class and subclasses can act on them
        protected int cdSku;        
        protected String cdName;               
        protected int cdCopies;
        protected double cdPrice;
        protected String genre;
        //Constructor
        CD(int cdSku, String cdName, int cdCopies, double cdPrice, String genre) {
            this.cdSku    = cdSku;
            this.cdName   = cdName;
            this.cdCopies = cdCopies;
            this.cdPrice  = cdPrice;
            this.genre = genre;
        // This method tells the sort method what is to be sorted     
        public int compareTo(Object o)
            return cdName.compareTo(((CD) o).getName());
        // Calculates the total value of the copies of a CD
        public double totalValue() {
            return cdCopies * cdPrice;
        // Tells the caller the title
        public String getName() {
            return cdName;       
        //Displays the information stored by the constructor
        public String toString() {
            return String.format("SKU=%2d   Name=%-20s   Stock=%3d   Price=$%6.2f   Value=$%,8.2f",
                                  cdSku, cdName, cdCopies, cdPrice, totalValue());
    } // end CD class    
         //Class used to add items to the inventory, display output for the inventory and sort the inventory
    class Inventory {
        private CD[] cds;
        private int nCount;
         // Creates array cds[] with 10 element spaces
        Inventory() {
            cds = new CD[10];
            nCount = 0;
         // Used by main to input a CD object into the array cds[]
        public void add(CD cd) {
            cds[nCount] = cd;
            ++nCount;
            sort();               
         //Displays the arrays contents element by element into a GUI pane
           public void display() {
            JTextArea textArea = new JTextArea();
            textArea.append("\nThere are " + nCount + " CD titles in the collection\n\n");
            for (int i = 0; i < nCount; i++)
                textArea.append(cds[i]+"\n");
            textArea.append("\nTotal value of the inventory is "+new java.text.DecimalFormat("$0.00").format(totalValue())+"\n\n");
            JFrame invFrame = new JFrame();
            invFrame.getContentPane().add(new JScrollPane(textArea));
            invFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            invFrame.pack();
            invFrame.setLocationRelativeTo(null);
            invFrame.setVisible(true);
         // Steps through the array adding the totalValue for each CD to "total"
        public double totalValue() {
            double total = 0;
            double restock = 0;
            for (int i = 0; i < nCount; i++)
                total += cds.totalValue();                
    return total;
         //Method used to sort the array by the the name of the CD
    private void sort() {
         Arrays.sort(cds, 0, nCount);
    } // end Inventory class
    // Subclass of CD. Creates new output string to be used, adds a restocking fee calculation and genre catagory to be displayed.
    class CDWithGenre extends CD {
         String genre;
         CDWithGenre(int cdSku, String cdName, int cdCopies, double cdPrice, String genre) {
    super(cdSku, cdName, cdCopies, cdPrice, genre);
    this.cdName = cdName;
              this.cdCopies = cdCopies;
    this.cdPrice = cdPrice;
    this.genre = genre;
    // Calculates restocking fee based on previous data.
    public double restockFee() {
         double total = 0;
         double restock = 0;
         total = cdCopies * cdPrice;
         restock = total * .05;
    return restock;
    // New output method overrides superclass's output method with new data and format.
         public String toString() {
              return String.format("SKU: %2d     Genre: %-12s     Name: %-20s     \nPrice: $%6.2f Value: $%,8.2f Stock: %3d      Restocking Fee: $%6.2f\n",
    cdSku, genre , cdName, cdPrice, totalValue(), cdCopies, restockFee());
    }// Ends CDWithGenre class

    Hey Michael,
    I edited the code to add some more features but I am having some errors. Can you help again?
    Here is the code
    The additional buttons are for features I need to add. The commented part that says save need to save to a certain location.
    But the problem I am having is with the previous and next buttons. I need them to loop so when Next reaches the end of the array it needs to go to the first element again and keep on rolling thru. The previous needs to roll back from element 0 to the end again.
    This works when the program is not stopped on the last or first element. If I press the last button then press next, it errors. If I press the first button and press previous, it errors.
    I also need to add an icon
    Let me know what you think. Thanks a bunch
    class InventoryGUI
      Inventory inventory;
      int displayElement = 0;
      public InventoryGUI(Inventory inv)
        inventory = inv;
      public void buildGUI()
        final JTextArea textArea = new JTextArea(inventory.display(displayElement));
        final JButton prevBtn = new JButton("Previous"); 
        final JButton nextBtn = new JButton("Next");   
        final JButton lastBtn = new JButton("Last");
        final JButton firstBtn = new JButton("First");
        final JButton addBtn = new JButton("Add"); 
        final JButton modifyBtn = new JButton("Modify");   
        final JButton searchBtn = new JButton("Search");
        final JButton deleteBtn = new JButton("Delete");
        final JButton saveBtn = new JButton("Save");
        ImageIcon icon = new ImageIcon("images/icon.jpg");  
        JLabel label1 = new JLabel(icon);
        JPanel panel = new JPanel(new GridLayout(2,4));
        panel.add(firstBtn); panel.add(nextBtn); panel.add(prevBtn); panel.add(lastBtn);
        panel.add(addBtn); panel.add(modifyBtn); panel.add(searchBtn); panel.add(deleteBtn);
        //panel.add(saveBtn);
        JFrame invFrame = new JFrame();   
        invFrame.getContentPane().add(new JScrollPane(textArea),BorderLayout.CENTER);
        invFrame.getContentPane().add(panel,BorderLayout.SOUTH);
        invFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        invFrame.pack();
        invFrame.setSize(500,200);
        invFrame.setTitle("Inventory Manager");
        invFrame.setLocationRelativeTo(null);
        invFrame.setVisible(true);
        prevBtn.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent ae){
            nextBtn.setEnabled(true);
            displayElement--;
            textArea.setText(inventory.display(displayElement));
            if(displayElement <= 0) displayElement = 5;
        nextBtn.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent ae){
            prevBtn.setEnabled(true);
            displayElement++;
            textArea.setText(inventory.display(displayElement));
            if(displayElement >= inventory.nCount-1) displayElement = -1;
        firstBtn.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent ae){
            firstBtn.setEnabled(true);
            displayElement = 0;
            textArea.setText(inventory.display(displayElement));
        lastBtn.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent ae){
            lastBtn.setEnabled(true);
            displayElement = inventory.nCount-1;
            textArea.setText(inventory.display(displayElement));
    }

  • Array output to GUI

    I need to write a gui that takes data from an array and puts it in a gui frame. Nothing fancy, no buttons, just a frame with all the data in there. A close button wouldnt be a bad idea but its not needed.
    The program currently displays the information I want just fine but does it in console. I just want to tell that data to use a gui instead of console.
    Can anyone give me a hint on where to begin? I havent used swing or created a gui before this and I am new to java entirely.

    Hmm, that gives me an idea where to start but I think my case is a bit more sophisticated then that. Here is the code.
    //  Jmichelsen
    //  Created June 17, 2007
    /*  This program is designed to show an inventory of CD's in alphabetical order
        and their corresponding prices.
        It gives the prices of the CD's and the value of the entire inventory.
        It adds a restocking fee for the entire product inventory and displays it separately */
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Inventory4 {
        public static void main(String[] args) {
            CD cd;
            Inventory inventory = new Inventory();
            cd = new CDWithGenre(16, "Snatch Soundtrack", 11, 13.01f, "Soundtrack");
            inventory.add(cd);
            cd = new CDWithGenre(12, "Best Of The Beatles", 10, 19.99f, "Classic Rock");
            inventory.add(cd);
            cd = new CDWithGenre(45, "Garth Brooks", 18, 10.87f, "Country");
            inventory.add(cd);
            cd = new CDWithGenre(32, "American Idol", 62, 25.76f, "Alternative");
            inventory.add(cd);
            cd = new CDWithGenre(18, "Photoshop", 27, 99.27f, "None");
            inventory.add(cd);
            inventory.display();    
        } //End main method
    } //End Inventory4 class
         /* Defines data from main as CD data and formats it. Calculates value of a title multiplied by its stock.
          Creates compareTo method to be used by Arrays.sort when sorting in alphabetical order. */
    class CD implements Comparable{
        //Declares the variables as protected so only this class and subclasses can act on them
        protected int cdSku;        
        protected String cdName;               
        protected int cdCopies;
        protected double cdPrice;
        protected String genre;
        //Constructor
        CD(int cdSku, String cdName, int cdCopies, double cdPrice, String genre) {
            this.cdSku    = cdSku;
            this.cdName   = cdName;
            this.cdCopies = cdCopies;
            this.cdPrice  = cdPrice;
            this.genre = genre;
        // This method tells the sort method what is to be sorted     
        public int compareTo(Object o)
            return cdName.compareTo(((CD) o).getName());
        // Calculates the total value of the copies of a CD
        public double totalValue() {
            return cdCopies * cdPrice;
        // Tells the caller the title
        public String getName() {
            return cdName;       
        //Displays the information stored by the constructor
        public String toString() {
            return String.format("SKU=%2d   Name=%-20s   Stock=%3d   Price=$%6.2f   Value=$%,8.2f",
                                  cdSku, cdName, cdCopies, cdPrice, totalValue());
    } // end CD class    
         //Class used to add items to the inventory, display output for the inventory and sort the inventory
    class Inventory {
        private CD[] cds;
        private int nCount;
         // Creates array cds[] with 10 element spaces
        Inventory() {
            cds = new CD[10];
            nCount = 0;
         // Used by main to input a CD object into the array cds[]
        public void add(CD cd) {
            cds[nCount] = cd;
            ++nCount;
            sort();               
         //Displays the arrays contents element by element
        public void display() {
            System.out.println("\nThere are " + nCount + " CD titles in the collection\n");
            for (int i = 0; i < nCount; i++)
                System.out.println(cds);
    System.out.printf("\nTotal value of the inventory is $%,.2f\n\n", totalValue());
         // Steps through the array adding the totalValue for each CD to "total"
    public double totalValue() {
    double total = 0;
    double restock = 0;
    for (int i = 0; i < nCount; i++)
    total += cds[i].totalValue();                
    return total;
         //Method used to sort the array by the the name of the CD
    private void sort() {
         Arrays.sort(cds, 0, nCount);
    } // end Inventory class
    // Subclass of CD. Creates new output string to be used, adds a restocking fee calculation and genre catagory to be displayed.
    class CDWithGenre extends CD {
         String genre;
         CDWithGenre(int cdSku, String cdName, int cdCopies, double cdPrice, String genre) {
    super(cdSku, cdName, cdCopies, cdPrice, genre);
    this.cdName = cdName;
              this.cdCopies = cdCopies;
    this.cdPrice = cdPrice;
    this.genre = genre;
    // Calculates restocking fee based on previous data.
    public double restockFee() {
         double total = 0;
         double restock = 0;
         total = cdCopies * cdPrice;
         restock = total * .05;
    return restock;
    // New output method overrides superclass's output method with new data and format.
         public String toString() {
              return String.format("SKU: %2d     Genre: %-12s     Name: %-20s     \nPrice: $%6.2f Value: $%,8.2f Stock: %3d      Restocking Fee: $%6.2f\n",
    cdSku, genre , cdName, cdPrice, totalValue(), cdCopies, restockFee());
         }// Ends CDWithGenre class
    would I make a new class calling it GUI or whatever, in there extend JFrame and add a JTextArea and JScrollpane there? Would I need to make the class public or just an internal class?

  • Swing display array to GUI

    Hi all,
    I am trying to use swing to display the contents of an array in a GUI pane. The gui doesnt need any buttons ( an OK button wouldnt be a bad thing) but I just need it to take the array and display it with formatting.
    I have the program so far to display the array in console with the proper formatting. The array is a multi attrib array so it has strings, ints, and doubles.
    So I need to use the format already in place to display the array but instead of console, just display it as a swing GUI.
    I can post my code later, if anyone has ideas on the best way to accomplish this, i would appreciate it!
    Thanks

    If it's just an array, a JList springs to mind. If it were a tree, then use JTree. Etc.
    Look at tutorials for javax.swing.JList.
    Swing-specific questions should probably go on the Swing forum.

  • How can I print out an Array List in my GUI program?

    I have an ArrayList of Objects which I want to print out in a TextArea in my GUI. I tried using setText(), but it seems like that can only handle strings. Does anyone know of an alternative method or some other way to get around this?

    Ok, I have an object name Instrument which contains a double price, String name, int numberInStock. In my GUIFrame class which creates the GUI obviously, I have a button listener that should print out my ArrayList in a TextArea when clicked on a button.
    Here is the code:
    private class showIResponse implements ActionListener{
              public void actionPerformed(ActionEvent e){
                   showText.setText(parseString(ali));
    it is still giving me an error saying "cannot find symbol method parseString(java.util.ArrayList<java.lang.Object>)"

  • Gui - making an array of JButtons to make a grid

    how do i declare an array of JButtons to make a 16x16 grid? here is an example:
    JPanel grid = new JPanel();
    grid.setLayout (new GridLayout(16,16));
    Container content = frame.getContentPane();
    ImageIcon icon = new ImageIcon("picture.gif");
    JButton[][] element = new JButton[16][16];
    for ( i = 0; i < 16; i++ )
    for ( j = 0; j < 16; j++)
    grid.add(element[i][j].setIcon(icon));
    content.add(grid);
    is that correct at all? it returns this error:
    'void' type not allowed here
    grid.add(elem[i][j].setIcon(icon));
    the caret points to the open parenthesis in setIcon(icon).
    if an array of JButtons doesnt work at all, is there an alternative? my program allows the user to arrange various bricks, etc. to create a maze.

    A 2-dimensional array of JButtons is perfectly possible, provided you write valid Java code. That's all the compiler is complaining about. And also, you forgot to create any button objects to go in the array. Try something like this:for ( i = 0; i < 16; i++ ) {
      for ( j = 0; j < 16; j++) {
        element[i][j] = new JButton();
        element[i][j].setIcon(icon);
        grid.add(element[i][j]);
    content.add(grid);That will get you started. Of course those buttons won't do anything until you add listeners to them, but that's your next challenge, I suppose.
    (By the way, there's a bug in the code that runs this forum. Wherever you see "<i>" in the code, alter it to use the correct rectangular brackets.)

  • An array of java queries:GUI, naitive stuff, symbian

    Kaiora, (Greetings in the Maori language of New Zealand)
    I'm doing myself up a J2ME application primaraly used to send and receive text messages and process the message payload, and just need to clarify some points so as to align my thinking:
    a) Symbian? Is it a language or just an OS for mobile devices? What is it when they talk about Symbian C++?
    b) When making the GUI for my application, is it more effecient to have a new form (of whose content is just commands and text/lists) for each next steep or to replace the commands and content of the current display and update it. My thougth is its better for the running of the application if it doesn't continaually change screens/forms but just updates and changes, but i really have no idea what is better.
    c) what is meant by "accessing naitive services" or (what other things are naitive?)? Does it mean naitive to the phone system? Are the naitive 'things' more API's and classes or things to do with the phone, ie inbox etc?
    d) is it possible for a MIDlet to access the cell phones phone book and inbox to look at recived messages? If so whats classes/methods are used?
    Having these answered really helps.
    Cheers,
    Matty

    Kaiora, (Greetings in the Maori language of New Zealand)
    I'm doing myself up a J2ME application primaraly used to send and receive text messages and process the message payload, and just need to clarify some points so as to align my thinking:
    a) Symbian? Is it a language or just an OS for mobile devices? What is it when they talk about Symbian C++?
    b) When making the GUI for my application, is it more effecient to have a new form (of whose content is just commands and text/lists) for each next steep or to replace the commands and content of the current display and update it. My thougth is its better for the running of the application if it doesn't continaually change screens/forms but just updates and changes, but i really have no idea what is better.
    c) what is meant by "accessing naitive services" or (what other things are naitive?)? Does it mean naitive to the phone system? Are the naitive 'things' more API's and classes or things to do with the phone, ie inbox etc?
    d) is it possible for a MIDlet to access the cell phones phone book and inbox to look at recived messages? If so whats classes/methods are used?
    Having these answered really helps.
    Cheers,
    Matty

  • Displaying the value of an array in swing? Almost like a chess baord

    Hi all.
    After a long time from coding I thought I'd have a bash.
    Here's a short outline of what I'm trying code.
    I have a robot, a simple robot, does nothing but move around, pick up objects and drop them.
    This robot lives in a world that is a square 1000x1000 for example.
    The world is populated with objects, the robot goes around, if the robot is not holding an object and comes across one it will pick it up.
    Then the robot moves around and if it comes across another object of the same type it will then drop the object.
    These are the class names that I've created, the names give it away what they are for:
    RobotProject (main class, not much in here apart from the starting parameters, such as starting position, how big the world is, number of objects in the world etc)
    SandBox (is the class that the world object will be created from)
    Robot (is the class the robot will be created from, I did it this way just in case I wanted more then one robot in the world)
    GridCheck (this is a static class as it's only a set of instructions to carry out depending where in the world it the robot is and what is around it)
    Movement (this class is not built yet, but all it does is check the current location of the robot, give options of where to move, then randomly picks a move)
    Gui (this is going to be used to display the world, not built yet)
    The object I create of SandBox is called world1, the only thing need to be known about this world is that it has an array, this array is what keeps track of each of the grid in the world and there state.
    So let?s imagine a chess board, top left grid is 0 going from left to right/ top to bottom we end up with 63 (or 64 arrays).
    What would be the best way to display this "chess board"?
    At the moment I have a method in the SandBox class that will return all the grids states and a string.
    This was put in there "just in case" but I think this is the wrong way to go.
    Really what I'm after is a few pointers to make this work, maybe my way of doing this is incorrect?
    I know I've been thinking that maybe I should have created an array of objects (SandBox, but with only an int rather than the array) rather than an object with an array var.
    Anyways, I hope that makes sense, if not feel free to "bust my chops"
    If you would like to see some of the mode feel free to ask, I'm not a student or anything, to be frank the last time I coded anything was over 4 years ago, so as you can guess the code is simply.
    Jon.
    Thanks in advance.
    Edited by: jontelling on Jan 12, 2009 9:47 AM

    I agree with BDLH that Swing would work well here. There are a million and one way to create your "grid" one option include using a 2D grid of JLabels, another being a single JPanel with a grid BufferedImage as its background image (which is probably how I'd do it), etc... which one to choose will depend on the rest of the program, so it may be very early to say. Perhaps at this point you just want to create an interface of invariant behaviors to represent the Grid and thus allowing you flexibility with its implementation.

  • Which methods to put in my Document object and which to put in my gui?

    Please offer corrections or suggestions for the plan I discuss. :-)
    I have created an MLDocument object that holds an xml document, some text(, a TreeModel(actually the tree model comes from the xml), and a text document, and an array of data that correlates the text with the stuff in the xml document.
    This object is used in a document browser that I have written for it that has two panes: a tree and a JEditorPane(IIRC). One key element of the GUI is that I can click on the tree and the associated text is highlighted in the JEditorPane and vice versa. This is what drives me to ask this question.
    Background: When I first wrote this program I did it before making the MLDocument class, but I began to realize I needed to do this in a better way. Now I am struggling to get some things to work trying it the new way.
    My question is, how much (if any) of the gui stuff should I put in the MLDocument. At first I didn't have any, then it seemed like a good idea to have the tree's root be created by a get method in the object but now I'm remembering that I shouldn't serialize swing objects or else I won't be able to upgrade. (or would I be ok since the tree root is created dynamically on when the object is created). More importantly, I'm not sure where (or how) to keep/place my eventlisteners. (the ones in the document that make events occur in the gui).
    It seems they should be in the GUI, but up until now, they had been associated with the document. Now the document is in the MLDocument object at that seems a bad place to keep them, since now I can't get them to do anything in the parent application.
    Thanks for reading my confusing post,
    LNMEgo

    Is there some reason you're asking us, other users, instead of doing what you were told to do and contacting iTunes store support?

Maybe you are looking for

  • How to show the data of one query since Forms9i using to Report built-in on

    Hello!!!, I have Developer 9i (Forms and Reports), the OCJ4 and repserver90 are running, now, I attempt to run one report from Forms9i, and only it appears an empty page HTML. I don't understand why doesn't show the data of query? Please, give me a s

  • 8350i and MicroSDHC cards

    Good morning all, I read several posts about the compatability with the BlackBerry and memory cards, one post has the following memory card use per OS version. BlackBerry Device Software                      Media Card Size Limit BlackBerry Device So

  • Problem migrating Iphoto library to Photos

    installed 10.10.3 and Photos will not recognize (grayed out) when I attempt to import my pics from iphoto (v9.6.1) In Photos preferences it knows that my Iphoto library (on an internal drive that is not my boot drive) but that is grayed out as well. 

  • Metadata Repository upgrade

    Is it possible to upgrade Metadata Repository running on 9.0.1.5.0 database to 9.2.0.4.0 without installing new 9.2.0.4.0 database and running Metadata Repository Creation Assistant?

  • Why is my iPhone 5c touchscreen not responding?

    My new phone's touchscreen has stopped responding other that a small line at the top and the bottom. Due to this I am unable to reset the phone or turn it off to try and resolve the issue. What's wrong and what do I need to do?