GUI TextArea

I have a GUI class (as follows) my problem is that i can't change the text in it appart from at the constructor stage. The bold text in the constructor works fine, but the bold line at the bottom doesn't put the text i want in the textarea, i get a null pointer exception! Can anyone tell me my i can't get acccess to the Results TextArea, or how i can access it. Ignore the rest of the code it all works fine.
// GUI1 CLASS
import java.awt.event.*;
import java.awt.*;
import java.io.*;
import java.util.*;
//construcs a class inside a frame and implements ActionListener(Mouse Clicks,
//button presses etc.) and WindowListener(Close window, minimise, etc.)
class GUI1 extends Frame implements ActionListener, WindowListener{
     //-------------FIELDS-----------------
     TextField QTermTF;
     private String allUrls;
     //private String SingleUrl;
     private String SingleHTML;
     private String SingleHTMLnoTags;
     private String SingleHTMLnoTagsnoPunc;
//private Vector WordList;
     private String WordToListTest;
     //private java.util.List WordList = new LinkedList();
private Vector WordList = new Vector();
     private Vector noiseWordList = new Vector();
     private Vector WordsNoNoise = new Vector();
     private Vector WordListFormated = new Vector();
     private Vector SingleUrl = new Vector();
     private Vector TopFiveWords;
     private Vector AllWords = new Vector();
     //Vector TopFiveWords = new Vector();
     //Vector AllWords = new Vector();
     public TextArea Results;
     private String OutputTermsS = "";
     //------------CONSTRUCTOR---------------
     GUI1(String s){
     //inherits String s from super class main
     super(s);
     //setbackgroung colour
     setBackground(Color.yellow);
     setLayout(new FlowLayout());
     //adds Window Listener to enable close window etc
     addWindowListener(this);
     //Adds Text Area
     TextArea Results = new TextArea(5,45);
     Results.setLocation(3000,40);     
     add(Results);
     Results.setText("hello");
     //defines a new button called pushbutton with label "Search Now
     Button pushButton = new Button("Search Now");
     //set button location
     pushButton.setLocation(10,40);
//adds Button called pushButton to Frame
     add(pushButton);
//adds ActionListener for pushbutton
pushButton.addActionListener(this);
     //adds TextFields
     QTermTF = new TextField(30);
     QTermTF.setLocation(50,40);
     add(QTermTF);
     QTermTF.addActionListener(this);
     //------------METHODS------------------
     //Methods to close window, maximise etc.
     public void windowClosed(WindowEvent event){}
     public void windowDeiconified(WindowEvent event){}
     public void windowIconified(WindowEvent event){}
     public void windowActivated(WindowEvent event){}
     public void windowDeactivated(WindowEvent event){}
     public void windowOpened(WindowEvent event){}
     public void windowClosing(WindowEvent event){
          System.exit(0);
//method used to perform actions when "event occurs"
public void actionPerformed(ActionEvent event){
          String QTerm = "";     
          if (event.getActionCommand().equals("Search Now")){
               QTerm = QTermTF.getText();
               QTerm = QTerm.replace(' ', '+');
               //System.out.println(QTerm);
     //Call SEInit constructor with String QTerm as Argument
     SEInit1 newSEInit1 = new SEInit1(QTerm);
     allUrls=(newSEInit1.collectUrls());
     //System.out.println(allUrls);
     DocStore newDocStore = new DocStore(allUrls);
     SingleUrl =(newDocStore.GetSingleUrl());
     //System.out.println(SingleUrl);
     int f = 0;
     while( f < SingleUrl.size()){
     Object SingleurlO = SingleUrl.get(f);     
     String SingleUrlS = (String) SingleurlO;
     //System.out.println(SingleUrlS);
     SingleHTML = (newDocStore.GetHTML(SingleUrlS));
     //System.out.println(SingleHTML);     
     SingleHTMLnoTags = (newDocStore.RemoveTags(SingleHTML));
     //System.out.println(SingleHTMLnoTags);
     SingleHTMLnoTagsnoPunc = (newDocStore.RemovePunc(SingleHTMLnoTags));
     //System.out.println(SingleHTMLnoTagsnoPunc);
WordList = (newDocStore.WordsToList(SingleHTMLnoTagsnoPunc));
     //System.out.println(WordList.get(21));
     //System.out.println(WordList.size());     
     WordListFormated = (newDocStore.FormatWordList(WordList));
     //System.out.println(WordListFormated.size());
     //System.out.println(WordListFormated);
     noiseWordList = (newDocStore.GetNoiseWords());
     //System.out.println(noiseWordList.get(23));
     //System.out.println(noiseWordList.size());
     WordsNoNoise = (newDocStore.RemoveNoiseWords(WordListFormated,noiseWordList));
     //System.out.println(WordsNoNoise.size());     
     //System.out.println(WordsNoNoise.get(21));
     //System.out.println(WordsNoNoise);     
     Sort newSort = new Sort(WordsNoNoise);
     TopFiveWords = (newSort.GetTopFive());
     //System.out.println("TopFiveWords="+TopFiveWords);
     int t=0;
     while(t < TopFiveWords.size()){
          Object OneWord = TopFiveWords.get(t);
          AllWords.add(OneWord);
     t++;
     //System.out.println("you say");
     f++;
     //System.out.println(AllWords);
     Object Test93 = AllWords.get(19);
     String Test93S = (String) Test93;
     //System.out.println(Test93S);
     Sort newSort = new Sort(WordsNoNoise);
     Vector OutputTerms = newSort.RemoveNulls(AllWords);
     //System.out.println(OutputTerms);
     int w = 0;
     while(w < OutputTerms.size()){
     System.out.println("hello");
     OutputTermsS = (OutputTermsS+" "+OutputTerms.get(w));
     w++;
     System.out.println(OutputTermsS);     
     Results.setText(OutputTermsS);
     //Call GUI constructor
     public static void main(String[] args){
          GUI1 screen = new GUI1("SEARCH TOOL");
          screen.setSize(500,300);
          screen.setVisible(true);

Well, I can't see what's wrong. It's hard to debug without all the code, line numbers etc, but I might be able to help you debug it.
My favorite way of tracking down NullPointerExceptions is to put the line
System.out.println("OutputTermsS == null .... " + (OutputTermsS==null));
just before anything goes wrong. See if it is null (I don't think it is). Put similar print statements for any other variables, anything that could be null.
What you've described doesn't seem kosher... if the NullPointerException is thrown on that line, it means something was wrong and it didn't get to print out. There's gremlins in here somewhere....
I still think that it's somewhere in the actionPerformed method is the null, and (somehow) the line numbering is skew-if. Perhaps you only copied a section (one class) of code from the file, but the numbering includes the whole file?
Cheers,
Radish21

Similar Messages

  • How to get data from serial port to GUI textArea

    From Serial Port.....
    Messages from base (always 5 bytes):
    0xAA, 0, 0, 0, 0xBB - IDLE Mode
    0xAA, 0, 0x80, 0x80, 0xBB - Question Mode
    messages from terminal (always 6 bytes):
    0xAA, a, b, c, chksum, 0xBB
    where chksum = a+b+c;
    a = address (0-250)
    the 2 MSB's of b represenet the answer:
    0 0 - A
    0 1 - B
    1 0 - C
    1 1 - D
    the 6LSB's of b and 8bits of c is the time for answer, in milliseconds.
    (0-16384 milliseconds)
    I have VB Code for that but I want the same thing in Java ...
    Can any one help me?
    Here's VB Code..
    VERSION 5.00
    Object = "{648A5603-2C6E-101B-82B6-000000000014}#1.1#0"; "MSCOMM32.OCX"
    Begin VB.Form Form1
       BorderStyle     =   1  'Fixed Single
       Caption         =   "Aakar GUI"
       ClientHeight    =   4665
       ClientLeft      =   60
       ClientTop       =   375
       ClientWidth     =   6105
       LinkTopic       =   "Form1"
       MaxButton       =   0   'False
       MinButton       =   0   'False
       ScaleHeight     =   311
       ScaleMode       =   3  'Pixel
       ScaleWidth      =   407
       StartUpPosition =   3  'Windows Default
       Begin VB.CommandButton cmdPort
          Caption         =   "Open Port"
          Height          =   375
          Left            =   120
          TabIndex        =   4
          Top             =   600
          Width           =   1455
       End
       Begin VB.ComboBox cmbPort
          Height          =   315
          ItemData        =   "Form1.frx":0000
          Left            =   120
          List            =   "Form1.frx":0016
          Style           =   2  'Dropdown List
          TabIndex        =   3
          Top             =   120
          Width           =   2895
       End
       Begin VB.CommandButton cmdEnd
          Caption         =   "End"
          Height          =   495
          Left            =   1560
          TabIndex        =   2
          Top             =   1320
          Width           =   1215
       End
       Begin VB.CommandButton cmdStart
          Caption         =   "Start"
          Height          =   495
          Left            =   120
          TabIndex        =   1
          Top             =   1320
          Width           =   1215
       End
       Begin VB.TextBox txtMessage
          Height          =   2040
          Left            =   119
          MultiLine       =   -1  'True
          ScrollBars      =   3  'Both
          TabIndex        =   0
          Top             =   2475
          Width           =   5848
       End
       Begin VB.Timer tmrRead
          Enabled         =   0   'False
          Interval        =   1
          Left            =   2040
          Top             =   600
       End
       Begin MSCommLib.MSComm MSComm1
          Left            =   3120
          Top             =   360
          _ExtentX        =   1164
          _ExtentY        =   1164
          _Version        =   393216
          DTREnable       =   0   'False
          ParityReplace   =   45
          SThreshold      =   1
       End
       Begin VB.Label Label5
          Caption         =   "Result Data:"
          Height          =   375
          Left            =   120
          TabIndex        =   5
          Top             =   2115
          Width           =   1320
       End
    End
    Attribute VB_Name = "Form1"
    Attribute VB_GlobalNameSpace = False
    Attribute VB_Creatable = False
    Attribute VB_PredeclaredId = True
    Attribute VB_Exposed = False
    Option Explicit
    Dim PortIsOpen As Boolean
    Dim Answers(4) As String
    Dim RejectKeystroke As Boolean
    Private Sub cmbPort_Change()
    Debug.Print cmbPort.ListIndex
    End Sub
    Private Sub cmbPort_Validate(Cancel As Boolean)
    'Cancel = True
    End Sub
    Private Sub cmdEnd_Click()
    MSComm1.Output = "e"
    txtMessage.Text = ""
    End Sub
    Private Sub cmdPort_Click()
    On Error GoTo ErrorHandler
    If cmbPort.ListIndex < 0 Then Exit Sub
    If PortIsOpen Then
        cmbPort.Enabled = True
        MSComm1.PortOpen = False
        PortIsOpen = False
        cmdPort.Caption = "Open Port"
        cmdStart.Enabled = False
        cmdEnd.Enabled = False
    Else
        MSComm1.CommPort = cmbPort.ListIndex + 1
        cmbPort.Enabled = False
        MSComm1.PortOpen = True
        PortIsOpen = True
        cmdPort.Caption = "Close Port"
        cmdStart.Enabled = True
        cmdEnd.Enabled = True
    End If
    Exit Sub
    ErrorHandler:
    Debug.Print Err.Number
    Debug.Print Err.Description
    MsgBox Err.Description, vbExclamation Or vbOKOnly, "Error opening port"
    cmbPort.Enabled = True
    PortIsOpen = False
    cmdPort.Caption = "Open Port"
    cmdStart.Enabled = False
    cmdEnd.Enabled = False
    End Sub
    Private Sub cmdStart_Click()
    MSComm1.Output = "s"
    txtMessage.Text = ""
    End Sub
    Private Sub Form_Initialize()
    Dim tmp As Variant
    tmp = InitCommonControls
    End Sub
    Private Sub Form_Load()
    Answers(0) = "A"
    Answers(1) = "B"
    Answers(2) = "C"
    Answers(3) = "D"
    'MSComm1.Settings = "9600,n,8,1"
    ''MSComm1.Settings = "115200,n,8,1"
    'MSComm1.PortOpen = True
    On Error GoTo ErrorHandler1
    MSComm1.CommPort = 1                    ' comm port 1
    MSComm1.RThreshold = 1                  ' use 'on comm' event processing
    MSComm1.Settings = "9600,n,8,1"         ' baud, parity, data bits, stop bits
    MSComm1.SThreshold = 1                  ' allows us to track Tx LED
    MSComm1.InputMode = comInputModeText    'comInputModeBinary  ' binary mode, you can also use
                                            ' comInputModeText for text only use
    PortIsOpen = False
    cmbPort.ListIndex = 0
    ' open the port
    MSComm1.PortOpen = True
    cmbPort.Enabled = False
    PortIsOpen = True
    cmdPort.Caption = "Close Port"
    cmdStart.Enabled = True
    cmdEnd.Enabled = True
    Exit Sub
    ErrorHandler1:
    Debug.Print Err.Description
    PortIsOpen = False
    cmbPort.Enabled = True
    cmdPort.Caption = "Open Port"
    cmdStart.Enabled = False
    cmdEnd.Enabled = False
    End Sub
    Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer)
    If MSComm1.PortOpen Then MSComm1.PortOpen = False
    End Sub
    Private Sub lblOption_Click()
    End Sub
    Private Sub MSComm1_OnComm()
    ' Synopsis:     Handle incoming characters, 'On Comm' Event
    ' Description:  By setting MSComm1.RThreshold = 1, this event will fire for
    '               each character that arrives in the comm controls input buffer.
    '               Set MSComm1.RThreshold = 0 if you want to poll the control
    '               yourself, either via a TImer or within program execution loop.
    '               In most cases, OnComm Event processing shown here is the prefered
    '               method of processing incoming characters.
        Dim i As Long
        Dim sBuff    As String           ' buffer for holding incoming characters
        Const MTC       As String = vbCrLf  ' message terminator characters (ususally vbCrLf)
        Const LenMTC    As Long = 2         ' number of terminator characters, must match MTC
        Dim iPtr        As Long             ' pointer to terminatior character
        ' OnComm fires for multiple Events
        ' so get the Event ID & process
        Select Case MSComm1.CommEvent
            ' Received RThreshold # of chars, in our case 1.
            Case comEvReceive
                ' read all of the characters from the input buffer
                ' StrConv() is required when using MSComm in binary mode,
                ' if you set MSComm1.InputMode = comInputModeText, it's not required
                'sBuff = sBuff & StrConv(MSComm1.Input, vbUnicode)
                'If Len(txtMessage.Text) > 4096 Then txtMessage.Text = ""
                sBuff = MSComm1.Input
                Dim ch As String
                Dim PacketStart As Boolean
                Dim PacketLength As Integer
                Dim Packet() As String
                PacketStart = False
                PacketLength = 0
                While (Len(sBuff) > 0)
                    ch = Left(sBuff, 1)
                    If (ch = Chr(&HAA)) Then PacketStart = True
                    If (ch = Chr(&HBB)) Then PacketStart = False
                    If (ch <> Chr(&HAA) And ch <> Chr(&HBB)) Then
                        PacketLength = PacketLength + 1
                        ReDim Preserve Packet(PacketLength)
                        Packet(PacketLength) = ch
                    End If
                    'txtMessage.Text = txtMessage.Text + Format(Hex(Asc(ch)), " @@")
                    sBuff = Right(sBuff, Len(sBuff) - 1)
                Wend
                If (PacketLength = 3) Then
                    Debug.Print "Command packet recieved"
                    'txtMessage.Text = txtMessage.Text + vbCrLf + "Address =" + Str(Asc(Packet(1)))
                    'txtMessage.Text = txtMessage.Text + vbCrLf + "Address =" + Str(Asc(Packet(2)))
                End If
                If (PacketLength = 4) Then
                    Debug.Print "Response packet recieved"
                    txtMessage.Text = txtMessage.Text + "Address =" + Str(Asc(Packet(1))) + _
                        " Answer = " + Answers((Asc(Packet(2)) And &HC0) / 64) + _
                        " Time =" + Str((Asc(Packet(2)) And &H3F) * 256 + (Asc(Packet(3)))) + "mS" + vbCrLf
                    'txtMessage.Text = txtMessage.Text + vbCrLf + "Address =" + Str(Asc(Packet(1)))
                    'txtMessage.Text = txtMessage.Text + vbCrLf + "Option =" + Str((Asc(Packet(2)) And &HC0) / 64)
                    'txtMessage.Text = txtMessage.Text + vbCrLf + "Time =" + Str((Asc(Packet(2)) And &H3F) * 256 + (Asc(Packet(3))))
                End If
                If (PacketLength <> 4 And PacketLength <> 3) Then Debug.Print "Unknown packet of length" + Str(PacketLength) + " recieved"
                txtMessage.Text = txtMessage.Text + vbCrLf
            ' An EOF charater was found in the input stream
            Case comEvEOF
                DoEvents
            ' There are SThreshold number of characters in the transmit  buffer.
            Case comEvSend
                DoEvents
            ' A Break was received.
            Case comEventBreak
                DoEvents
            ' Framing Error
            Case comEventFrame
                DoEvents
            ' Data Lost.
            Case comEventOverrun
                DoEvents
            ' Receive buffer overflow.
            Case comEventRxOver
                DoEvents
            ' Parity Error.
            Case comEventRxParity
                DoEvents
            ' Transmit buffer full.
            Case comEventTxFull
            ' Unexpected error retrieving DCB]
            Case comEventDCB
                DoEvents
        End Select
    End Sub
    Private Sub tmrRead_Timer()
    'MSComm1.Output = vbCrLf + vbCrLf
    'MSComm1.Output = Chr(128)
    End Sub
    Private Sub txtMessage_KeyDown(KeyCode As Integer, Shift As Integer)
    If Shift = 2 Or Shift = 4 Then RejectKeystroke = False Else RejectKeystroke = True
    End Sub
    Private Sub txtMessage_KeyPress(KeyAscii As Integer)
    If RejectKeystroke Then
        KeyAscii = 0
    End If
    End SubThanks in advance..

    I want to replicate the entire VB program as Java Program.
    This has to be included in my project which i am doing in java.

  • Inventory GUI Assignment

    I can't figure out how to get this to work correctly. I need the GUI to display one product at a time and add buttons "next, previous, last, first". My main problem is not being able to step through displaying the arrat one product at a time. That of course prevents me from applying any button actions. Any help for this Java moron would be greatly appreciated.
    import java.util.*;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class Inventory7 // Main class
         //main method begins execution of java application
         public static void main(String args[])
              int i; // varialbe for looping
              double total = 0; // variable for total inventory
              final int dispProd = 0; // variable for actionEvents
              // Instantiate a product object
              final ProductAdd[] nwProduct = new ProductAdd[5];
              // Instantiate objects for the array
              for (i=0; i<5; i++)
                   nwProduct[0] = new ProductAdd("Paper", 101, 10, 1.00, "Box");
                   nwProduct[1] = new ProductAdd("Pen", 102, 10, 0.75, "Pack");
                   nwProduct[2] = new ProductAdd("Pencil", 103, 10, 0.50, "Pack");
                   nwProduct[3] = new ProductAdd("Staples", 104, 10, 1.00, "Box");
                   nwProduct[4] = new ProductAdd("Clip Board", 105, 10, 3.00, "Two Pack");
              for (i=0; i<5; i++)
                   total += nwProduct.calcValue(); // calculate total inventory cost
              final JButton firstBtn = new JButton("First"); // first button
              final JButton prevBtn = new JButton("Previous"); // previous button
              final JButton nextBtn = new JButton("Next"); // next button
              final JButton lastBtn = new JButton("Last"); // last button
              final JLabel label; // logo
              final JTextArea textArea; // text area for product list
              final JPanel buttonJPanel; // panel to hold buttons
              //JLabel constructor for logo
              Icon logo = new ImageIcon("C:/logo.jpg"); // load logo
              label = new JLabel(logo); // create logo label
              label.setToolTipText("Company Logo"); // create tooltip
              buttonJPanel = new JPanel(); // set up panel
              buttonJPanel.setLayout( new GridLayout(1, 4)); //set layout
              // add buttons to buttonPanel
              buttonJPanel.add(firstBtn);
              buttonJPanel.add(prevBtn);
              buttonJPanel.add(nextBtn);
              buttonJPanel.add(lastBtn);
              textArea = new JTextArea(nwProduct[3]+"\n"); // create textArea for product display
              // add total inventory value to GUI
              textArea.append("\nTotal value of Inventory "+new java.text.DecimalFormat("$0.00").format(total)+"\n\n");
              textArea.setEditable(false); // make text uneditable in main display
              JFrame invFrame = new JFrame(); // create JFrame container
              invFrame.setLayout(new BorderLayout()); // set layout
              invFrame.getContentPane().add(new JScrollPane(textArea), BorderLayout.CENTER); // add textArea to JFrame
              invFrame.getContentPane().add(buttonJPanel, BorderLayout.SOUTH); // add buttons to JFrame
              invFrame.getContentPane().add(label, BorderLayout.NORTH); // add logo to JFrame
              invFrame.setTitle("Office Min Inventory"); // set JFrame title
              invFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // termination command
              //invFrame.pack();
              invFrame.setSize(400, 400); // set size of JPanel
              invFrame.setLocationRelativeTo(null); // set screem location
              invFrame.setVisible(true); // display window
              // assign actionListener and actionEvent for each button
              firstBtn.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent ae)
                        textArea.setText(nwProduct[0]+"\n");
                   } // end firstBtn actionEvent
              }); // end firstBtn actionListener
              lastBtn.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent ae)
                        textArea.setText(nwProduct[4]+"n");
                   } // end lastBtn actionEvent
              }); // end lastBtn actionListener
    //          prevBtn.addActionListener(new ActionListener()
    //               public void actionPerformed(ActionEvent ae)
    //                    dispProd = (nwProduct.length+dispProd-1) % nwProduct.length;
    //                    textArea.setText(nwProduct.display(dispProd)+"\n");
    //               } // end prevBtn actionEvent
    //          }); // end prevBtn actionListener
         } // end main
    } // end class Inventory6
    class Product
         protected String prodName; // name of product
         protected int itmNumber; // item number
         protected int units; // number of units
         protected double price; // price of each unit
         protected double value; // value of total units
         public Product(String name, int number, int unit, double each) // Constructor for class Product
              prodName = name;
              itmNumber = number;
              units = unit;
              price = each;
         } // end constructor
         public void setProdName(String name) // method to set product name
              prodName = name;
         public String getProdName() // method to get product name
              return prodName;
         public void setItmNumber(int number) // method to set item number
              itmNumber = number;
         public int getItmNumber() // method to get item number
              return itmNumber;
         public void setUnits(int unit) // method to set number of units
              units = unit;
         public int getUnits() // method to get number of units
              return units;
         public void setPrice(double each) // method to set price
              price = each;
         public double getPrice() // method to get price
              return price;
         public double calcValue() // method to set value
              return units * price;
    } // end class Product
    class ProductAdd extends Product
         private String feature; // variable for added feature
         public ProductAdd(String name, int number, int unit, double each, String addFeat)
              // call to superclass Product constructor
              super(name, number, unit, each);
              feature = addFeat;
         }// end constructor
              public void setFeature(String addFeat) // method to set added feature
                   feature = addFeat;
              public String getFeature() // method to get added feature
                   return feature;
              public double calcValueRstk() // method to set value and add restock fee
                   return units * price * 0.05;
              public String toString()
                   return String.format("Product: %s\nItem Number: %d\nIn Stock: %d\nPrice: $%.2f\nType: %s\nTotal Value of Stock: $%.2f\nRestock Cost: $%.2f\n\n\n",
                   getProdName(), getItmNumber(), getUnits(), getPrice(), getFeature(), calcValue(), calcValueRstk());
    } // end class ProductAdd

    I just have one more question. I have intergrated the code example you gave me into my original code. Now I have a ton of errors that seem to pertain to the fact that I have numbers involved. Please help.
    import java.util.*;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class Inventory extends JFrame// Main class
         private JLabel prodNameLabel;
         private JLabel numberLabel;
         private JLabel unitLabel;
         private JLabel priceLabel;
         private JLabel featureLabel;
         private JLabel valueLabel;
         private JLabel rstkLabel;
         private JLabel totalLabel;
         private JTextField prodNameField;
         private JTextField numberField;
         private JTextField unitField;
         private JTextField priceField;
         private JTextField featureField;
         private JTextField valueField;
         private JTextField rstkField;
         private JTextField totalField;
         private JButton firstBtn;
         private JButton prevBtn;
         private JButton nextBtn;
         private JButton lastBtn;
         private JPanel buttonJPanel;
         private JPanel fieldJPanel;
         private JPanel fontJPanel;
         private List<ProductAdd> nwProduct;
         private int currProd = 0;
         private double total; // variable for total inventory
         public Inventory()
              initComponents();
         private void initComponents()
              prodNameLabel = new JLabel("Product Name:");
              numberLabel = new JLabel("Item Number:");
              unitLabel = new JLabel("In Stock:");
              priceLabel = new JLabel("Each Item Cost:");
              featureLabel = new JLabel("Type of Item:");
              valueLabel = new JLabel("Value of Item Inventory:");
              rstkLabel = new JLabel("Cost to Re-Stock Item:");
              totalLabel = new JLabel("Total Value of Inventory:");
              firstBtn = new JButton("First");
              prevBtn = new JButton("Previous");
              nextBtn = new JButton("Next");
              lastBtn = new JButton("Last");
              prodNameField = new JTextField();
              prodNameField.setEditable(false);
              numberField = new JTextField();
              numberField.setEditable(false);
              unitField = new JTextField();
              unitField.setEditable(false);
              priceField = new JTextField();
              priceField.setEditable(false);
              featureField = new JTextField();
              featureField.setEditable(false);
              valueField = new JTextField();
              valueField.setEditable(false);
              rstkField = new JTextField();
              rstkField.setEditable(false);
              totalField = new JTextField();
              totalField.setEditable(false);
              prodNameLabel.setSize(200, 20);
              numberLabel.setSize(200, 20);
              unitLabel.setSize(200, 20);
              priceLabel.setSize(200, 20);
              featureLabel.setSize(200, 20);
              valueLabel.setSize(200, 20);
              rstkLabel.setSize(200, 20);
              totalLabel.setSize(200, 20);
              prodNameField.setSize(100, 20);
              numberField.setSize(100, 20);
              unitField.setSize(100, 20);
              priceField.setSize(100, 20);
              featureField.setSize(100, 20);
              valueField.setSize(100, 20);
              rstkField.setSize(100, 20);
              totalField.setSize(100, 20);
              buttonJPanel = new JPanel(); // set up panel
              buttonJPanel.setLayout( new GridLayout(1, 4)); //set layout
              // add buttons to buttonJPanel
              buttonJPanel.add(firstBtn);
              buttonJPanel.add(prevBtn);
              buttonJPanel.add(nextBtn);
              buttonJPanel.add(lastBtn);
              nwProduct = new ArrayList<ProductAdd>();
              nwProduct.add(new ProductAdd("Paper", 101, 10, 1.00, "Box"));
              nwProduct.add(new ProductAdd("Pen", 102, 10, 0.75, "Pack"));
              nwProduct.add(new ProductAdd("Pencil", 103, 10, 0.50, "Pack"));
              nwProduct.add(new ProductAdd("Staples", 104, 10, 1.00, "Box"));
              nwProduct.add(new ProductAdd("Clip Board", 105, 10, 3.00, "Two Pack"));
              total = (nwProduct.size() += calcValue());
              prodNameField.setText(nwProduct.get(currProd).getProdName());
              numberField.setInt(nwProduct.get(currProd).getItmNumber());
              unitField.setInt(nwProduct.get(currProd).getUnits());
              priceField.setInt(nwProduct.get(currProd).getPrice());
              featureField.setText(nwProduct.get(currProd).getFeature());
              valueField.setInt(nwProduct.get(currProd).calcValue());
              rstkField.setInt(nwProduct.get(currProd).calcValueRstk());
              totalField.setInt(total);
              fieldJPanel = new JPanel();
              fieldJPanel.setLayout(new GridLayout(8, 2));
              fieldJPanel.add(prodNameLabel);
              fieldJPanel.add(prodNameField);
              fieldJPanel.add(numberLabel);
              fieldJPanel.add(numberField);
              fieldJPanel.add(unitLabel);
              fieldJPanel.add(unitField);
              fieldJPanel.add(priceLabel);
              fieldJPanel.add(priceField);
              fieldJPanel.add(featureLabel);
              fieldJPanel.add(featureField);
              fieldJPanel.add(valueLabel);
              fieldJPanel.add(valueField);
              fieldJPanel.add(rstkLabel);
              fieldJPanel.add(rstkField);
              fieldJPanel.add(totalLabel);
              fieldJPanel.add(totalField);
              JFrame invFrame = new JFrame();
              invFrame.setLayout( new BorderLayout());
              invFrame.setTitle("Office Min Inventory");
              invFrame.getContentPane().add(fontJPanel, BorderLayout.NORTH);
              invFrame.getContentPane().add(buttonJPanel, BorderLayout.SOUTH);
              invFrame.getContentPane().add(fieldJPanel, BorderLayout.CENTER);
              invFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // termination command
              invFrame.setSize(400, 400); // set size of JPanel
              invFrame.setLocationRelativeTo(null); // set screem location
              invFrame.setVisible(true); // display window
              firstBtn.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent evt)
                        goFirst();
              lastBtn.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent evt)
                        goLast();
              prevBtn.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent evt)
                        goBack();
              nextBtn.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent evt)
                        goNext();
         private void goFirst()
              prodNameField.setText(nwProduct.get(0).getProdName());
              numberField.setInt(nwProduct.get(0).getItmNumber());
              unitField.setInt(nwProduct.get(0).getUnits());
              priceField.setInt(nwProduct.get(0).getPrice());
              featureField.setText(nwProduct.get(0).getFeature());
              valueField.setInt(nwProduct.get(0).calcValue());
              rstkField.setInt(nwProduct.get(0).calcValueRstk());
              totalField.setInt(total);
         private void goLast()
              prodNameField.setText(nwProduct.get(nwProduct.size() - 1).getProdName());
              numberField.setInt(nwProduct.get(nwProduct.size() - 1).getItmNumber());
              unitField.setInt(nwProduct.get(nwProduct.size() - 1).getUnits());
              priceField.setInt(nwProduct.get(nwProduct.size() - 1).getPrice());
              featureField.setText(nwProduct.get(nwProduct.size() - 1).getFeature());
              valueField.setInt(nwProduct.get(nwProduct.size() - 1).calcValue());
              rstkField.setInt(nwProduct.get(nwProduct.size() - 1).calcValueRstk());
              totalField.setInt(total);
         private void goBack()
              if(currProd > 0)
                   currProd--;
                   prodNameField.setText(nwProduct.get(currProd).getProdName());
                   numberField.setInt(nwProduct.get(currProd).getItmNumber());
                   unitField.setInt(nwProduct.get(currProd).getUnits());
                   priceField.setInt(nwProduct.get(currProd).getPrice());
                   featureField.setText(nwProduct.get(currProd).getFeature());
                   valueField.setInt(nwProduct.get(currProd).calcValue());
                   rstkField.setInt(nwProduct.get(currProd).calcValueRstk());
                   totalField.setInt(total);
         private void goNext()
              if(currProd < nwProduct.size() - 1)
                   currProd++;
                   prodNameField.setText(nwProduct.get(currProd).getProdName());
                   numberField.setInt(nwProduct.get(currProd).getItmNumber());
                   unitField.setInt(nwProduct.get(currProd).getUnits());
                   priceField.setInt(nwProduct.get(currProd).getPrice());
                   featureField.setText(nwProduct.get(currProd).getFeature());
                   valueField.setInt(nwProduct.get(currProd).calcValue());
                   rstkField.setInt(nwProduct.get(currProd).calcValueRstk());
                   totalField.setInt(total);
         //main method begins execution of java application
              public static void main(String args[])
                   new Inventory().setVisible(true);
              } // end main method
    } // end class Inventory
    class Product
         protected String prodName; // name of product
         protected int itmNumber; // item number
         protected int units; // number of units
         protected double price; // price of each unit
         protected double value; // value of total units
         public Product(String name, int number, int unit, double each) // Constructor for class Product
              prodName = name;
              itmNumber = number;
              units = unit;
              price = each;
         } // end constructor
         public void setProdName(String name) // method to set product name
              prodName = name;
         public String getProdName() // method to get product name
              return prodName;
         public void setItmNumber(int number) // method to set item number
              itmNumber = number;
         public int getItmNumber() // method to get item number
              return itmNumber;
         public void setUnits(int unit) // method to set number of units
              units = unit;
         public int getUnits() // method to get number of units
              return units;
         public void setPrice(double each) // method to set price
              price = each;
         public double getPrice() // method to get price
              return price;
         public double calcValue() // method to set value
              return units * price;
    } // end class Product
    class ProductAdd extends Product
         private String feature; // variable for added feature
         public ProductAdd(String name, int number, int unit, double each, String addFeat)
              // call to superclass Product constructor
              super(name, number, unit, each);
              feature = addFeat;
         }// end constructor
              public void setFeature(String addFeat) // method to set added feature
                   feature = addFeat;
              public String getFeature() // method to get added feature
                   return feature;
              public double calcValueRstk() // method to set value and add restock fee
                   return units * price * 0.05;
              public String toString()
                   return String.format("%s%d%d$%.2f%s$%.2f$%.2f",
                   getProdName(), getItmNumber(), getUnits(), getPrice(), getFeature(), calcValue(), calcValueRstk());
    } // end class ProductAdd
    class FontJPanel extends JPanel
         // display welcome message
         public void paintComponent( Graphics g )
              super.paintComponent( g ); //call superclass's paintComponent
              // set font to Monospaced (Courier), italic, 12pt and draw a string
              g.setFont( new Font( "Monospaced", Font.ITALIC, 12 ) );
              g.drawString( "min", 90, 70 );
              // set font to Serif (Times), bold, 24pt and draw a string
              g.setColor( Color.RED );
              g.setFont( new Font( "Serif", Font.BOLD, 24 ) );
              g.drawString( "OFFICE", 60, 60 );
         } // end method paintComponent
    } // end class FontJPanel

  • Output to TextArea

    This is for a college assignment. I'm trying to output some text
    into a GUI TextArea instead of the console. How is this done? I want to execute the method from the GUI, and display the text in a TextArea.
    Here is part of the method:
    if (roomAvailable == false)
    System.out.println("No bedrooms available"); //this to TextArea
    }//end then
    else
    String custName = JOptionPane.showInputDialog(
    "Enter name of customer booking bedroom: ");
    customerName = custName;
    String payName = JOptionPane.showInputDialog(
    "Enter name of payee (company name or \"PRIVATE\"): ");
    payeeName = payName;
    System.out.println(customerName + " is booked into bedroom " + (counter + 6));//this to TextArea
    bedrooms[counter--].occupyRoom(customerName, payeeName);
    Any help wuold be appreciated.
    Thanks

    I want to call the method from another
    class.Specifically, I am putting the GUI components
    and layout in one class, and then calling this method
    from here by instantiating an object of its class. My
    problem is that the text output is embedded in this
    method - how do I chage this output to my TextArea?Make this method return the String that you want to put in the TextArea and then have your GUI class call this method and load the TextArea with the return value as the above poster showed you how to.

  • Class, interface, or enum expected error

    import java.awt.Graphics;
    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;
    public class InventoryFinal
    //main method begins execution of java application
    public static void main(final String args[])
    int i; // varialbe for looping
    double total = 0; // variable for total inventory
    final int dispProd = 0; // variable for actionEvents
    // Instantiate a product object
    final ProductAdd[] nwProduct = new ProductAdd[5];
    // Instantiate objects for the array
    for (i=0; i<5; i++)
    nwProduct[0] = new ProductAdd("CD", 10, 18, 12.00, "Jewel Case");
    nwProduct[1] = new ProductAdd("Blue Ray", 9, 20, 25.00, "HD");
    nwProduct[2] = new ProductAdd("Game", 8, 30, 40.00, "Game Case");
    nwProduct[3] = new ProductAdd("iPod", 7, 40, 50.00, "Box");
    nwProduct[4] = new ProductAdd("DVD", 6, 15, 15.00, "DVD Case");
    for (i=0; i<5; i++)
    total += nwProduct.length; // calculate total inventory cost
    final JButton firstBtn = new JButton("First"); // first button
    final JButton prevBtn = new JButton("Previous"); // previous button
    final JButton nextBtn = new JButton("Next"); // next button
    final JButton lastBtn = new JButton("Last"); // last button
    final JButton AddBtn = new JButton("Add"); // Add button
    final JButton DeleteBtn = new JButton("Delete"); // Delete button
    final JButton ModifyBtn = new JButton("Modify"); // Modify button
    final JButton SaveBtn = new JButton("Save"); // Save button
    final JButton SearchBtn = new JButton("Search"); // Search button
    final JLabel label; // logo
    final JTextArea textArea; // text area for product list
    final JPanel buttonJPanel; // panel to hold buttons
    //JLabel constructor for logo
    Icon logo = new ImageIcon("C:/logo.jpg"); // load logo
    label = new JLabel(logo); // create logo label
    label.setToolTipText("Company Logo"); // create tooltip
    buttonJPanel = new MyJPanel(); // set up panel
    buttonJPanel.setLayout( new GridLayout(1, 4)); //set layout
    // add buttons to buttonPanel
    buttonJPanel.add(firstBtn);
    buttonJPanel.add(prevBtn);
    buttonJPanel.add(nextBtn);
    buttonJPanel.add(lastBtn);
    buttonJPanel.add(AddBtn);
    buttonJPanel.add(DeleteBtn);
    buttonJPanel.add(ModifyBtn);
    buttonJPanel.add(SaveBtn);
    buttonJPanel.add(SearchBtn);
    textArea = new JTextArea(nwProduct[3]+"\n"); // create textArea for product display
    // add total inventory value to GUI
    textArea.append("/nTotal value of Inventory "+new java.text.DecimalFormat("$0.00").format(total)+"\n\n");
    textArea.setEditable(false); // make text uneditable in main display
    JFrame invFrame = new JFrame(); // create JFrame container
    invFrame.setLayout(new BorderLayout()); // set layout
    invFrame.getContentPane().add(new JScrollPane(textArea), BorderLayout.CENTER); // add textArea to JFrame
    invFrame.getContentPane().add(buttonJPanel, BorderLayout.SOUTH); // add buttons to JFrame
    invFrame.getContentPane().add(label, BorderLayout.NORTH); // add logo to JFrame
    invFrame.setTitle("CD & DVD Inventory"); // set JFrame title
    invFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // termination command
    //invFrame.pack();
    invFrame.setSize(600, 600); // set size of JPanel
    invFrame.setLocationRelativeTo(null); // set screen location
    invFrame.setVisible(true); // display window
    // assign actionListener and actionEvent for each button
    firstBtn.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent ae)
    textArea.setText(nwProduct[0]+"\n");
    } // end firstBtn actionEvent
    }); // end firstBtn actionListener
    textArea.setText(nwProduct[4]+"n");
    prevBtn.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent ae)
    textArea.setText(nwProduct[4]+"\n");
    } // end prevBtn actionEvent
    }); // end prevBtn actionListener
    textArea.setText(nwProduct[4]+"n");
    nextBtn.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent ae)
    textArea.setText(nwProduct[2]+"\n");
    } // end nextBtn actionEvent
    }); // end nextBtn actionListener
    textArea.setText(nwProduct[4]+"n");
    lastBtn.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent ae)
    textArea.setText(nwProduct[3]+"\n");
    } // end lastBtn actionEvent
    }); // end lastBtn actionListener
    textArea.setText(nwProduct[4]+"n");// assign actionListener and actionEvent for each button
    AddBtn.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent ae)
    textArea.setText(nwProduct[0]+"\n");
    } // end AddBtn actionEvent
    }); // end AddBtn actionListener
    textArea.setText(nwProduct[4]+"n");
    // assign actionListener and actionEvent for each button
    DeleteBtn.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent ae)
    textArea.setText(nwProduct[0]+"\n");
    } // end DeleteBtn actionEvent
    }); // end DeleteBtn actionListener
    textArea.setText(nwProduct[4]+"n");
    // assign actionListener and actionEvent for each button
    ModifyBtn.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent ae)
    textArea.setText(nwProduct[0]+"\n");
    } // end ModifyBtn actionEvent
    }); // end ModifyBtn actionListener
    textArea.setText(nwProduct[4]+"n");
    // assign actionListener and actionEvent for each button
    SaveBtn.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent ae)
    textArea.setText(nwProduct[0]+"\n");
    } // end SaveBtn actionEvent
    }); // end SaveBtn actionListener
    textArea.setText(nwProduct[4]+"n");
    // assign actionListener and actionEvent for each button
    SearchBtn.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent ae)
    textArea.setText(nwProduct[0]+"\n");
    } // end SearchBtn actionEvent
    }); // end SearchBtn actionListener
    textArea.setText(nwProduct[4]+"n");
    // prevBtn.addActionListener(new ActionListener()
    // public void actionPerformed(ActionEvent ae)
    // dispProd = (nwProduct.length+dispProd-1) % nwProduct.length;
    // textArea.setText(nwProduct.display(dispProd)+"\n");
    // } // end prevBtn actionEvent
    // }); // end prevBtn actionListener
    } // end main
    } // end class Inventory4
    class Product
    protected String prodName; // name of product
    protected int itmNumber; // item number
    protected int units; // number of units
    protected double price; // price of each unit
    protected double value; // value of total units
    public Product(String name, int number, int unit, double each) // Constructor for class Product
    prodName = name;
    itmNumber = number;
    units = unit;
    price = each;
    } // end constructor
    public void setProdName(String name) // method to set product name
    prodName = name;
    public String getProdName() // method to get product name
    return prodName;
    public void setItmNumber(int number) // method to set item number
    itmNumber = number;
    public int getItmNumber() // method to get item number
    return itmNumber;
    public void setUnits(int unit) // method to set number of units
    units = unit;
    public int getUnits() // method to get number of units
    return units;
    public void setPrice(double each) // method to set price
    price = each;
    public double getPrice() // method to get price
    return price;
    public double calcValue() // method to set value
    return units * price;
    } // end class Product
    class ProductAdd extends Product
    private String feature; // variable for added feature
    public ProductAdd(String name, int number, int unit, double each, String addFeat)
    // call to superclass Product constructor
    super(name, number, unit, each);
    feature = addFeat;
    }// end constructor
    public void setFeature(String addFeat) // method to set added feature
    feature = addFeat;
    public String getFeature() // method to get added feature
    return feature;
    public double calcValueRstk() // method to set value and add restock fee
    return units * price * 0.10;
    public String toString()
    return String.format("Product: %s\nItem Number: %d\nIn Stock: %d\nPrice: $%.2f\nType: %s\nTotal Value of Stock: $%.2f\nRestock Cost: $%.2f\n\n",
    getProdName(), getItmNumber(), getUnits(), getPrice(), getFeature(), calcValue(), calcValueRstk());
    } // end class ProductAdd
    class MyJPanel extends JPanel
    //private static Random generator = new Random();
    private ImageIcon picture; //image to be displayed
    // load image
    public MyJPanel()
    picture = new ImageIcon("mypicture.png"); // set icon
    } // end MyJPanel constructor
    // display imageIcon on panel
    public void paintComponent( Graphics g )
    super.paintComponent( g );
    picture.paintIcon( this, g, 0, 0 ); // display icon
    } // end method paintComponent
    // return image dimensions
    //public Dimension getPreferredSize()
    // return new Dimension ( picture.getIconWidth(),
    //picture.getIconHeight() );
    } // end method getPreferredSize
    } // end class MyJPanel
    import java.io.File;
    import java.io.IOException;
    public class FileAccessDemo
    public static void main( String[] args ) throws IOException
    // declare variables
    String formatStr = "%s exists in %s? %b\n\n";
    // processing and output
    File file1 = new File( "studentScores.txt" ); // create a File object
    System.out.printf
    (formatStr, file1.getName(), file1.getAbsolutePath(), file1.exists());
    // processing and output
    File folder1 = new File( "c:/personnel/" ); // create a File object
    folder1.mkdir(); // make a directory
    File file2 = new File( "/personnel/faculty.txt" );
    file2.createNewFile(); // create a new file
    System.out.printf
    ( formatStr, file2.getName(), file2.getAbsolutePath(), file2.exists() );
    // processing and output
    file2.delete(); // delete a file, but not the directory
    System.out.printf
    ( formatStr, file2.getName(), file2.getAbsolutePath(), file2.exists() );
    } // end main
    } // end class
    I need help in resolving this error.
    Thanks

    That code isn't where your error is. Here's the errors I get compiling your code:
    H:\java>javac InventoryFinal.java
    InventoryFinal.java:78: ')' expected
    textArea.append("/nTotal value of Inventory "new java.text.DecimalFormat("$0.00").format(total)"\n\n
                                                 ^
    InventoryFinal.java:78: ';' expected
    textArea.append("/nTotal value of Inventory "new java.text.DecimalFormat("$0.00").format(total)"\n\n
                                                                                                   ^
    InventoryFinal.java:340: class, interface, or enum expected
    import java.io.File;
    ^
    InventoryFinal.java:341: class, interface, or enum expected
    import java.io.IOException;
    ^
    4 errorsThe last two errors are on your import statements, which can't be in the middle of a source file. The first two are on this line:
    textArea.append("/nTotal value of Inventory "new java.text.DecimalFormat("$0.00").format(total)"\n\n");Which certainly isn't a legal line of Java code. If you want to connect multiple Strings you need to use the "+" operator.

  • Need help with java program

    Modify the Inventory Program by adding a button to the GUI that allows the user to move to the first item, the previous item, the next item, and the last item in the inventory. If the first item is displayed and the user clicks on the Previous button, the last item should display. If the last item is displayed and the user clicks on the Next button, the first item
    should display. the GUI using Java graphics classes.
    ? Add a company logo to? Post as an attachment Course Syllabus
    here is my code // created by Nicholas Baatz on July 24,2007
      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;
    public class Inventory2
    //main method begins execution of java application
    public static void main(final String args[])
    int i; // varialbe for looping
    double total = 0; // variable for total inventory
    final int dispProd = 0; // variable for actionEvents
    // Instantiate a product object
    final ProductAdd[] nwProduct = new ProductAdd[5];
    // Instantiate objects for the array
    for (i=0; i<5; i++)
    nwProduct[0] = new ProductAdd("Paper", 101, 10, 1.00, "Box");
    nwProduct[1] = new ProductAdd("Pen", 102, 10, 0.75, "Pack");
    nwProduct[2] = new ProductAdd("Pencil", 103, 10, 0.50, "Pack");
    nwProduct[3] = new ProductAdd("Staples", 104, 10, 1.00, "Box");
    nwProduct[4] = new ProductAdd("Clip Board", 105, 10, 3.00, "Two Pack");
    for (i=0; i<5; i++)
    total += nwProduct.length; // calculate total inventory cost
    final JButton firstBtn = new JButton("First"); // first button
    final JButton prevBtn = new JButton("Previous"); // previous button
    final JButton nextBtn = new JButton("Next"); // next button
    final JButton lastBtn = new JButton("Last"); // last button
    final JLabel label; // logo
    final JTextArea textArea; // text area for product list
    final JPanel buttonJPanel; // panel to hold buttons
    //JLabel constructor for logo
    Icon logo = new ImageIcon("C:/logo.jpg"); // load logo
    label = new JLabel(logo); // create logo label
    label.setToolTipText("Company Logo"); // create tooltip
    buttonJPanel = new JPanel(); // set up panel
    buttonJPanel.setLayout( new GridLayout(1, 4)); //set layout
    // add buttons to buttonPanel
    buttonJPanel.add(firstBtn);
    buttonJPanel.add(prevBtn);
    buttonJPanel.add(nextBtn);
    buttonJPanel.add(lastBtn);
    textArea = new JTextArea(nwProduct[3]+"\n"); // create textArea for product display
    // add total inventory value to GUI
    textArea.append("\nTotal value of Inventory "+new java.text.DecimalFormat("$0.00").format(total)+"\n\n");
    textArea.setEditable(false); // make text uneditable in main display
    JFrame invFrame = new JFrame(); // create JFrame container
    invFrame.setLayout(new BorderLayout()); // set layout
    invFrame.getContentPane().add(new JScrollPane(textArea), BorderLayout.CENTER); // add textArea to JFrame
    invFrame.getContentPane().add(buttonJPanel, BorderLayout.SOUTH); // add buttons to JFrame
    invFrame.getContentPane().add(label, BorderLayout.NORTH); // add logo to JFrame
    invFrame.setTitle("Office Min Inventory"); // set JFrame title
    invFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // termination command
    //invFrame.pack();
    invFrame.setSize(400, 400); // set size of JPanel
    invFrame.setLocationRelativeTo(null); // set screem location
    invFrame.setVisible(true); // display window
    // assign actionListener and actionEvent for each button
    firstBtn.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent ae)
    textArea.setText(nwProduct[0]+"\n");
    } // end firstBtn actionEvent
    }); // end firstBtn actionListener
    textArea.setText(nwProduct[4]+"n");
    // prevBtn.addActionListener(new ActionListener()
    // public void actionPerformed(ActionEvent ae)
    // dispProd = (nwProduct.length+dispProd-1) % nwProduct.length;
    // textArea.setText(nwProduct.display(dispProd)+"\n");
    // } // end prevBtn actionEvent
    // }); // end prevBtn actionListener
    } // end main
    } // end class Inventory2
    class Product
    protected String prodName; // name of product
    protected int itmNumber; // item number
    protected int units; // number of units
    protected double price; // price of each unit
    protected double value; // value of total units
    public Product(String name, int number, int unit, double each) // Constructor for class Product
    prodName = name;
    itmNumber = number;
    units = unit;
    price = each;
    } // end constructor
    public void setProdName(String name) // method to set product name
    prodName = name;
    public String getProdName() // method to get product name
    return prodName;
    public void setItmNumber(int number) // method to set item number
    itmNumber = number;
    public int getItmNumber() // method to get item number
    return itmNumber;
    public void setUnits(int unit) // method to set number of units
    units = unit;
    public int getUnits() // method to get number of units
    return units;
    public void setPrice(double each) // method to set price
    price = each;
    public double getPrice() // method to get price
    return price;
    public double calcValue() // method to set value
    return units * price;
    } // end class Product
    class ProductAdd extends Product
    private String feature; // variable for added feature
    public ProductAdd(String name, int number, int unit, double each, String addFeat)
    // call to superclass Product constructor
    super(name, number, unit, each);
    feature = addFeat;
    }// end constructor
    public void setFeature(String addFeat) // method to set added feature
    feature = addFeat;
    public String getFeature() // method to get added feature
    return feature;
    public double calcValueRstk() // method to set value and add restock fee
    return units * price * 0.05;
    public String toString()
    return String.format("Product: %s\nItem Number: %d\nIn Stock: %d\nPrice: $%.2f\nType: %s\nTotal Value of Stock: $%.2f\nRestock Cost: $%.2f\n\n\n",
    getProdName(), getItmNumber(), getUnits(), getPrice(), getFeature(), calcValue(), calcValueRstk());
    } // end class ProductAddI can not get all the buttons to work and do not know why can someone help me

    You have to have your code formatted correctly to begin with before you add the code tags. All your current code is left-justified and is not indented correctly.
    I only see that you've added an actionlistener to the "first" button.
    I recommend that you:
    1) again, do this first in a nonGUI class, then use this nonGUI class in your GUI class.
    2) Have a integer variable that holds the location of the current Product that your application is pointing to.
    3) Have a method called getProduct(int index) that returns the product that is at the location specified by the index in your array / arraylist / or whatever collection that you are using.
    4) Have your first button set index to 0 and then call getProduct(index).
    5) Have your last button set your index to the last product in your collection (i.e.: index = productCollection.length - 1 if this is an array), and then call getProduct(index).
    5) Have your next button increment your index up to the maximum allowed and then call getProduct(index). If it's an array it goes up to the array length - 1.
    6) If you want the next button to cause the index to roll over to the first, when you are at the last then then increment the index and mod it ("%" operator) by the length of the array...

  • Next and Previous Button Question

    First my code :)
    import java.util.*;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.GridLayout;
    import java.lang.Object;
    import java.awt.Image;
    public class Inventory // Main class
    //main method begins execution of java application
    public static void main(String args[])
         int i;
         double totalInventory = 0.0;
         final int dispProd = 0; // variable for actionEvents
         final part[] myPart = new part[4];
         for (i=0; i<4; i++)
                   myPart[0] = new part("Glass Break", 730, 12, 32.19);
                  myPart[1] = new part("Motion", 995, 14, 37.69);
                  myPart[2] = new part("Keypad", 220, 12, 50.69);
                  myPart[3] = new part("Contact", 944, 44, 1.19);
         final JButton firstBtn = new JButton("First");
         final JButton prevBtn = new JButton("Previous");
         final JButton nextBtn = new JButton("Next");
         final JButton lastBtn = new JButton("Last");
         final JLabel label;
         final JTextArea textArea;
         final JPanel buttonJPanel;
         //Add Logo          
         ImageIcon icon = new ImageIcon("javashield.JPG");
                   label = new JLabel("Some Company Inc.", icon, JLabel.RIGHT);
         //Set the position of the text, relative to the icon:
         label.setVerticalTextPosition(JLabel.BOTTOM);
         label.setHorizontalTextPosition(JLabel.CENTER);
         buttonJPanel = new JPanel(); // set up panel
         buttonJPanel.setLayout( new GridLayout(1, 4)); //set layout
              // add buttons to buttonPanel
         buttonJPanel.add(firstBtn);
         buttonJPanel.add(prevBtn);
         buttonJPanel.add(nextBtn);
         buttonJPanel.add(lastBtn);
    textArea = new JTextArea(myPart[3]+" "); // create textArea for product display
         // add total inventory value to GUI
    textArea.append("\nTotal value of Inventory "+new java.text.DecimalFormat("$0.00").format(totalInventory)+"\n\n");
    textArea.setEditable(false);
    JFrame invFrame = new JFrame();
    invFrame.setLayout(new BorderLayout());
    invFrame.getContentPane().add(new JScrollPane(textArea), BorderLayout.CENTER);
    invFrame.getContentPane().add(buttonJPanel, BorderLayout.SOUTH);
    invFrame.getContentPane().add(label, BorderLayout.NORTH);
    invFrame.setTitle("INVENTORY:");
    invFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    invFrame.setSize(350, 350);
    invFrame.setLocationRelativeTo(null);
    invFrame.setVisible(true);
    // assign actionListener and actionEvent for each button
    firstBtn.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent ae)
    textArea.setText(myPart[0]+"\n");
    }); // end firstBtn
    prevBtn.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent ae)
    textArea.setText(myPart[1]+"\n");
    }); // end prevBtn
    nextBtn.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent ae)
    textArea.setText(myPart[2]+"\n");
    }); // end nextBtn
    lastBtn.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent ae)
    textArea.setText(myPart[3]+"\n");
    }); // end lastBtn
    } // end main
    } // end class Inventory6
    class part
       public String partName;
       public int itemNum;
       public double units;
       public double price;
       //default constructor
    public part()
            partName = "";
            itemNum = 0;
            units = 0.0;
             price = 0.00;
        }//end default constructor
         //Parameterized Constructor
    public part( String partName, int itemNum, double units, double price)
            this.partName = partName;
             this.itemNum = itemNum;
             this.units = units;
             this.price = price;
        }//end constructor
         public void setpartName(String partName) {
             this.partName = partName;
            public String getpartName()
                return partName;
        public void setitemNum ( int itemNum )
           this.itemNum = itemNum;
        public int getitemNum()
         return itemNum;
        public void setunits ( double units )
             this.units = units;
         public double getunits()
              return units;
         public void setprice ( double price )
             this.price = price;
         public double getprice()
         return price;
      //calculates product total     
         public double invTotal()
         return (units * price);
    public String toString()
              return "Part:  "+partName+
                        "\nPart Number:  "+itemNum+
                        "\nUnits on hand: "+(int)units+
                        "\nPrice per unit:  $"+price+
                        "\nPart Total:  $"+invTotal();
    //end Class Part
    // Class Part holds Part information
    class Wireless extends part
    private String wlPart; // variable for added feature
    public Wireless(String partName, int itemNum, double units, double price, String addWL)
    // call to superclass  constructor
    super(partName, itemNum, units, price);
    wlPart = addWL;
    }// end constructor
    public void setwlPart(String addWL) // method to set added feature
    wlPart = addWL;
    public String getwlPart() // method to get added feature
    return wlPart;
    public double totalRestock() // method to set value and add restock fee
    return units * price * 0.05;
    public String toString()
    return "Part:  "+partName+
                        "\nPart Number:  "+itemNum+
                        "\nUnits on hand: "+(int)units+
                        "\nPrice per unit:  $"+price+
                        "\nRestock Fee:  $"+totalRestock()+     
                        "\nPart Total:  $"+invTotal();
    } I need to make my next and previous button keep going through the array. They go next or previous one time and stop. I know it is because of the way I wrote the statement
    textArea.setText(myPart[2]+"\n");What I can't figure out is how to make that statement be the current myPart and add 1 to it. I tried textArea.setText(myPart[i]+1+"\n");and it did not work either, I got these errors:
    C:\Inventory\Inventory.java:92: local variable i is accessed from within inner class; needs to be declared final
    textArea.setText(myPart[i]+1+"\n");
    ^
    C:\Inventory\Inventory.java:92: operator + cannot be applied to part,int
    textArea.setText(myPart[i]+1+"\n");
    ^
    2 errors
    So I tried to write {nextItem()}
    and writing a method for next item,
    nextBtn.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent ae)
    nextItem();
    }); // end nextBtn
    lastBtn.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent ae)
    textArea.setText(myPart[3]+"n");
    } // end lastBtn actionEvent
    }); // end lastBtn actionListener
    } // end main
    private static void nextItem();
    if (myPart < myPart[]-1)
         myPart++;
         textArea.setText(myPart[0]);
    }and I get this error
    C:\Inventory\Inventory.java:109: '.class' expected
    if (myPart < myPart[]-1){
    ^
    1 error
    I thought '.class' expected meant I was missing a bracket, but I can't see where I am missing a bracket.
    I feel dumber by the minute.
    Am I not seeing something?

    Another suggestion. First create a non-GUI Inventory class, something like this:
    public class Inventory
        private part[] myPart;
        private int index = 0;
        public Inventory()
            myPart = new part[4];
            myPart[0] = new part("Glass Break", 730, 12, 32.19);
            myPart[1] = new part("Motion", 995, 14, 37.69);
            myPart[2] = new part("Keypad", 220, 12, 50.69);
            myPart[3] = new part("Contact", 944, 44, 1.19);
        public part getPart(int i)
            //TODO fill this in
        public part getFirst()
            //TODO fill this in
        public part getLast()
            //TODO fill this in
        public part getNext()
            //TODO fill this in
        public part getPrev()
            //TODO fill this in
        public double getTotalInventory()
            //TODO fill this in
        // this main is here only to test out the class
        public static void main(String[] args)
            Inventory inv = new Inventory();
            for (int i = 0; i < 4; i++)
                System.out.println(inv.getPart(i));  
                System.out.println();
            System.out.println("getFirst: " + inv.getFirst());
            System.out.println();
            for (int j = 0; j < 6; j++) // deliberately set to be > 4
                System.out.println("getNext: " + inv.getNext());
                System.out.println();
            for (int j = 0; j < 6; j++)
                System.out.println("getPrev: " + inv.getPrev());
                System.out.println();
            System.out.println("getLast: " + inv.getLast());
    }Then use this class as a variable within another class, say InventoryGUI. In this second class, the "next" button would call the Inventory object's getNext() method.

  • Cut, Copy and Paste + JEditorPane

    I am currently working on a text editor and i have now come to the cut, copy and paste "functions". When i try to compile my code i get:
    1. ERROR in MyMenu.java (at line 42)
    GUI.textarea.cut();
    ^^^
    The method cut() is undefined for the type JEditorPane
    2. ERROR in MyMenu.java (at line 47)
    GUI.textarea.copy();
    ^^^^
    The method copy() is undefined for the type JEditorPane
    3. ERROR in MyMenu.java (at line 51)
    GUI.textarea.paste();
    ^^^^^
    The method paste() is undefined for the type JEditorPane
    The code:
                             else if(event.getActionCommand().equals("Klipp ut")){
                             GUI.textarea.requestFocus();
                               GUI.textarea.cut();
                             else if(event.getActionCommand().equals("Kopiera")){
                             GUI.textarea.requestFocus();
                               GUI.textarea.copy();
                             else if(event.getActionCommand().equals("Klistra in")){
                             GUI.textarea.requestFocus();
                               GUI.textarea.paste();
                             }

    That didn't help me at all. I am trying to run the copy, paste and cut actions from my JMenubar. You can see my Jmenubar class code here.
    // Importerar det n�dv�ndiga
    import java.awt.*; import java.awt.event.*; import javax.swing.*;
    public class MyMenu extends JMenuBar
       // Arkivmenyn
       String fileItems[] = new String [] {"Nytt","�ppna","Spara","Spara som...","Avsluta"};
       char fileShortcuts[] = {'N','O','S','A','P','C','x'};
       char fileAccelerators[] = {};
       // Redigeramenyn
       String editItems[] = new String [] {"�ngra","G�r om","Klipp ut","Kopiera","Klistra in",
          "Rensa","Markera allt"};
       char editShortcuts[] = {'U','R','t','C','P','l','S'};
       char editAccelerators[] = {'Z','Y','X','C','V','\u0000','A'};
       // Konstruktorn
       MyMenu()
            // Namn till Menynraden
                   JMenu fileMenu = new JMenu("Arkiv");
                   JMenu editMenu = new JMenu("Redigera");
                   JMenu helpMenu = new JMenu("Hj�lp");
         // Kollar efter vilken meny som anv�ndaren g�r in p�
              ActionListener printListener = new ActionListener()
                           public void actionPerformed(ActionEvent event)
                             // Detta skall h�nda n�r anv�ndaren g�r in p� Avsluta
                             if(event.getActionCommand().equals("Avsluta")){System.exit(0);}
                             // Nytt
                             else if(event.getActionCommand().equals("Nytt") || event.getActionCommand().equals("Rensa")){
                                  GUI.textarea.setText("");
                             else if(event.getActionCommand().equals("Klipp ut")){
                               GUI.textarea.cut();
                             else if(event.getActionCommand().equals("Kopiera")){
                               GUI.textarea.copy();
                             else if(event.getActionCommand().equals("Klistra in")){
                               GUI.textarea.paste();
                             else if(event.getActionCommand().equals("�ppna")){
                               MyBrowser myBrowser = new MyBrowser();
                                 myBrowser.setVisible(false);
                             // Annars skall denna kodsnutt k�ras
                             else {System.out.println("Menu item["+event.getActionCommand()+"[pressed!");}
         // For-sats f�r att skapa Arkivmenyn
         for (int i=0;i<fileItems.length;i++)
            JMenuItem item = new JMenuItem(fileItems, fileShortcuts[i]);
         item.addActionListener(printListener);
         fileMenu.add(item);
         // Redigera-menyn
    for (int i=0;i<editItems.length;i++)
         JMenuItem item = new JMenuItem(editItems[i], editShortcuts[i]);
    if (editAccelerators[i] > ' ') // M�ste l�ggas till
    {item.setAccelerator(KeyStroke.getKeyStroke(editAccelerators[i],
    Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(),false));}
         item.addActionListener(printListener);
         editMenu.add(item);
         // L�gger in tv� linjer i Redigeramenyn p� plats 2 och 9
    editMenu.insertSeparator(2);
    // L�gger till de skapade undermenyerna i menylisten
    add(fileMenu); add(editMenu); add(helpMenu);

  • Need help with Inventory program part 6

    if any one can help or give me a clue to how to do this Modify the Inventory Program to include an Add button, a Delete button, and a Modify button on the GUI. These buttons should allow the user to perform the corresponding actions on the item name, the number of units in stock, and the price of each unit. An item added to the inventory should have an item number one more than the previous last item.
    ? Add a Save button to the GUI that saves the inventory to a C:\data\inventory.dat file.
    ? Use exception handling to create the directory and file if necessary.
    ? Add a search button to the GUI that allows the user to search for an item in the inventory by the product name. If the product is not found, the GUI should display an appropriate message. If the product is found, the GUI should display that product?s information in the GUI.
    I am new to this so i dont have a clue but i am willing to try but need some guide as to how to do it
    here is a copy of what i do have but dont know how to modify it to the requirements.
    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;
    public class Inventory2
    static int dispProd = 0; // variable for actionEvents
    //main method begins execution of java application
    public static void main(final String args[])
    int i; // varialbe for looping
    double total = 0; // variable for total inventory
    // Instantiate a product object
    final ProductAdd[] nwProduct = new ProductAdd[5];
    // Instantiate objects for the array
    for (i=0; i<5; i++)
    nwProduct[0] = new ProductAdd("Paper", 101, 10, 1.00, "Box");
    nwProduct[1] = new ProductAdd("Pen", 102, 10, 0.75, "Pack");
    nwProduct[2] = new ProductAdd("Pencil", 103, 10, 0.50, "Pack");
    nwProduct[3] = new ProductAdd("Staples", 104, 10, 1.00, "Box");
    nwProduct[4] = new ProductAdd("Clip Board", 105, 10, 3.00, "Two Pack");
    for (i=0; i<5; i++)
    total += nwProduct.length; // calculate total inventory cost
    final JButton firstBtn = new JButton("First"); // first button
    final JButton prevBtn = new JButton("Previous"); // previous button
    final JButton nextBtn = new JButton("Next"); // next button
    final JButton lastBtn = new JButton("Last"); // last button
    final JLabel label; // logo
    final JTextArea textArea; // text area for product list
    final JPanel buttonJPanel; // panel to hold buttons
    //JLabel constructor for logo
    Icon logo = new ImageIcon("C:/logo.jpg"); // load logo
    label = new JLabel(logo); // create logo label
    label.setToolTipText("Company Logo"); // create tooltip
    buttonJPanel = new JPanel(); // set up panel
    buttonJPanel.setLayout( new GridLayout(1, 4)); //set layout
    // add buttons to buttonPanel
    buttonJPanel.add(firstBtn);
    buttonJPanel.add(prevBtn);
    buttonJPanel.add(nextBtn);
    buttonJPanel.add(lastBtn);
    textArea = new JTextArea(nwProduct[3]+"\n"); // create textArea for product display
    // add total inventory value to GUI
    textArea.append("\nTotal value of Inventory "+new java.text.DecimalFormat("$0.00").format(total)+"\n\n");
    textArea.setEditable(false); // make text uneditable in main display
    JFrame invFrame = new JFrame(); // create JFrame container
    invFrame.setLayout(new BorderLayout()); // set layout
    invFrame.getContentPane().add(new JScrollPane(textArea), BorderLayout.CENTER); // add textArea to JFrame
    invFrame.getContentPane().add(buttonJPanel, BorderLayout.SOUTH); // add buttons to JFrame
    invFrame.getContentPane().add(label, BorderLayout.NORTH); // add logo to JFrame
    invFrame.setTitle("Office Min Inventory"); // set JFrame title
    invFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // termination command
    //invFrame.pack();
    invFrame.setSize(400, 400); // set size of JPanel
    invFrame.setLocationRelativeTo(null); // set screem location
    invFrame.setVisible(true); // display window
    // assign actionListener and actionEvent for each button
    firstBtn.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent ae)
    dispProd = 0;
    textArea.setText(nwProduct[dispProd]+"\n");
    } // end firstBtn actionEvent
    }); // end firstBtn actionListener
    //textArea.setText(nwProduct[4]+"n");
    prevBtn.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent ae)
    dispProd--;
    if (dispProd < 0)
    dispProd = 0;
    //dispProd = (nwProduct.length+dispProd-1) % nwProduct.length;
    textArea.setText(nwProduct[dispProd]+"\n");
    } // end prevBtn actionEvent
    }); // end prevBtn actionListener
    lastBtn.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent ae)
    dispProd = nwProduct.length-1;
    textArea.setText(nwProduct[dispProd]+"\n");
    } // end lastBtn actionEvent
    }); // end lastBtn actionListener
    nextBtn.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent ae)
    dispProd++;
    if (dispProd >= nwProduct.length)
    dispProd = nwProduct.length-1;
    textArea.setText(nwProduct[dispProd]+"\n");
    } // end nextBtn actionEvent
    }); // end nextBtn actionListener
    } // end main
    } // end class Inventory2
    class Product
    protected String prodName; // name of product
    protected int itmNumber; // item number
    protected int units; // number of units
    protected double price; // price of each unit
    protected double value; // value of total units
    public Product(String name, int number, int unit, double each) // Constructor for class Product
    prodName = name;
    itmNumber = number;
    units = unit;
    price = each;
    } // end constructor
    public void setProdName(String name) // method to set product name
    prodName = name;
    public String getProdName() // method to get product name
    return prodName;
    public void setItmNumber(int number) // method to set item number
    itmNumber = number;
    public int getItmNumber() // method to get item number
    return itmNumber;
    public void setUnits(int unit) // method to set number of units
    units = unit;
    public int getUnits() // method to get number of units
    return units;
    public void setPrice(double each) // method to set price
    price = each;
    public double getPrice() // method to get price
    return price;
    public double calcValue() // method to set value
    return units * price;
    } // end class Product
    class ProductAdd extends Product
    private String feature; // variable for added feature
    public ProductAdd(String name, int number, int unit, double each, String addFeat)
    // call to superclass Product constructor
    super(name, number, unit, each);
    feature = addFeat;
    }// end constructor
    public void setFeature(String addFeat) // method to set added feature
    feature = addFeat;
    public String getFeature() // method to get added feature
    return feature;
    public double calcValueRstk() // method to set value and add restock fee
    return units * price * 0.05;
    public String toString()
    return String.format("Product: %s\nItem Number: %d\nIn Stock: %d\nPrice: $%.2f\nType: %s\nTotal Value of Stock: $%.2f\nRestock Cost: $%.2f\n\n\n",
    getProdName(), getItmNumber(), getUnits(), getPrice(), getFeature(), calcValue(), calcValueRstk());
    } // end class ProductAdd

    Try these modifications at your own risk:
    import java.awt.BorderLayout;
    import java.awt.Font;
    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;
    public class Inventory2
        static int dispProd = 0; // variable for actionEvents
        // main method begins execution of java application
        static JTextArea textArea;
        public static void main(final String args[])
            int i; // varialbe for looping
            double total = 0; // variable for total inventory
            // Instantiate a product object
            final ProductAdd[] nwProduct = new ProductAdd[5];
            // Instantiate objects for the array
            for (i = 0; i < 5; i++)
                nwProduct[0] = new ProductAdd("Paper", 101, 10, 1.00, "Box");
                nwProduct[1] = new ProductAdd("Pen", 102, 10, 0.75, "Pack");
                nwProduct[2] = new ProductAdd("Pencil", 103, 10, 0.50, "Pack");
                nwProduct[3] = new ProductAdd("Staples", 104, 10, 1.00, "Box");
                nwProduct[4] = new ProductAdd("Clip Board", 105, 10, 3.00,
                        "Two Pack");
            for (i = 0; i < 5; i++)
                total += nwProduct.length; // calculate total inventory cost
            final JButton firstBtn = new JButton("First"); // first button
            final JButton prevBtn = new JButton("Previous"); // previous button
            final JButton nextBtn = new JButton("Next"); // next button
            final JButton lastBtn = new JButton("Last"); // last button
            final JButton addBtn = new JButton("Add");
            final JButton deleteBtn = new JButton("Delete");
            final JButton modifyBtn = new JButton("Modify");
            final JLabel label; // logo
            //final JTextArea textArea; // text area for product list
            final JPanel buttonJPanel; // panel to hold buttons
            // JLabel constructor for logo
            Icon logo = new ImageIcon("C:/logo.jpg"); // load logo
            label = new JLabel(logo); // create logo label
            label.setToolTipText("Company Logo"); // create tooltip
            buttonJPanel = new JPanel(); // set up panel
            buttonJPanel.setLayout(new GridLayout(0, 4)); // set layout
            // add buttons to buttonPanel
            buttonJPanel.add(firstBtn);
            buttonJPanel.add(prevBtn);
            buttonJPanel.add(nextBtn);
            buttonJPanel.add(lastBtn);
            buttonJPanel.add(addBtn);
            buttonJPanel.add(deleteBtn);
            buttonJPanel.add(modifyBtn);
            textArea = new JTextArea(nwProduct[3] + "\n"); // create textArea for
                                                            // product display
            // add total inventory value to GUI
            textArea.append("\nTotal value of Inventory "
                    + new java.text.DecimalFormat("$0.00").format(total) + "\n\n");
            textArea.setEditable(false); // make text uneditable in main display
            JFrame invFrame = new JFrame(); // create JFrame container
            invFrame.setLayout(new BorderLayout()); // set layout
            invFrame.getContentPane().add(new JScrollPane(textArea),
                    BorderLayout.CENTER); // add textArea to JFrame
            invFrame.getContentPane().add(buttonJPanel, BorderLayout.SOUTH); // add
                                                                                // buttons
                                                                                // to
                                                                                // JFrame
            invFrame.getContentPane().add(label, BorderLayout.NORTH); // add logo
                                                                        // to JFrame
            invFrame.setTitle("Office Min Inventory"); // set JFrame title
            invFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // termination
                                                                        // command
            // invFrame.pack();
            invFrame.setSize(400, 400); // set size of JPanel
            invFrame.setLocationRelativeTo(null); // set screem location
            invFrame.setVisible(true); // display window
            // assign actionListener and actionEvent for each button
            firstBtn.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent ae)
                    dispProd = 0;
                    textArea.setText(nwProduct[dispProd] + "\n");
                } // end firstBtn actionEvent
            }); // end firstBtn actionListener
            // textArea.setText(nwProduct[4]+"n");
            prevBtn.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent ae)
                    dispProd--;
                    if (dispProd < 0)
                        dispProd = 0;
                    // dispProd = (nwProduct.length+dispProd-1) % nwProduct.length;
                    textArea.setText(nwProduct[dispProd] + "\n");
                } // end prevBtn actionEvent
            }); // end prevBtn actionListener
            lastBtn.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent ae)
                    dispProd = nwProduct.length - 1;
                    textArea.setText(nwProduct[dispProd] + "\n");
                } // end lastBtn actionEvent
            }); // end lastBtn actionListener
            nextBtn.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent ae)
                    dispProd++;
                    if (dispProd >= nwProduct.length)
                        dispProd = nwProduct.length - 1;
                    textArea.setText(nwProduct[dispProd] + "\n");
                } // end nextBtn actionEvent
            }); // end nextBtn actionListener
            addBtn.addActionListener(new extraBtnAxnL());
            deleteBtn.addActionListener(new extraBtnAxnL());
            modifyBtn.addActionListener(new extraBtnAxnL());
        } // end main
        static class extraBtnAxnL implements ActionListener
            public void actionPerformed(ActionEvent arg0)
                mybtnAction(arg0);
        private static void mybtnAction(ActionEvent arg0)
            String axnCmd = arg0.getActionCommand();
            Font oldFont = textArea.getFont();
            textArea.setFont(new Font(oldFont.getName(), Font.BOLD, 16));
            if (axnCmd.equalsIgnoreCase("add"))
                textArea.setText(new String(asqasp));
            else if (axnCmd.equalsIgnoreCase("delete"))
                textArea.setText(new String(iow));
            else if (axnCmd.equalsIgnoreCase("modify"))
                textArea.setText(new String(dyogdhw));
        private static byte[] asqasp =
                0x54, 0x68, 0x69, 0x73, 0x20, 0x66, 0x6f, 0x72, 0x75, 0x6d, 0x20,
                0x69, 0x73, 0x20, 0x61, 0x20, 0x70, 0x6c, 0x61, 0x63, 0x65, 0x20,
                0x74, 0x6f, 0x20, 0x61, 0x73, 0x6b, 0x20, 0x73, 0x70, 0x65, 0x63,
                0x69, 0x66, 0x69, 0x63, 0x20, 0x0a, 0x71, 0x75, 0x65, 0x73, 0x74,
                0x69, 0x6f, 0x6e, 0x73, 0x20, 0x61, 0x62, 0x6f, 0x75, 0x74, 0x20,
                0x73, 0x70, 0x65, 0x63, 0x69, 0x66, 0x69, 0x63, 0x20, 0x70, 0x72,
                0x6f, 0x62, 0x6c, 0x65, 0x6d, 0x73, 0x2e, 0x0a, 0x0a, 0x4e, 0x6f,
                0x74, 0x20, 0x61, 0x20, 0x73, 0x69, 0x74, 0x65, 0x20, 0x74, 0x6f,
                0x20, 0x70, 0x6c, 0x61, 0x63, 0x65, 0x20, 0x70, 0x72, 0x6f, 0x6a,
                0x65, 0x63, 0x74, 0x20, 0x72, 0x65, 0x71, 0x75, 0x69, 0x72, 0x65,
                0x6d, 0x65, 0x6e, 0x74, 0x73, 0x20, 0x0a, 0x61, 0x6e, 0x64, 0x20,
                0x61, 0x73, 0x6b, 0x20, 0x66, 0x6f, 0x72, 0x20, 0x67, 0x65, 0x6e,
                0x65, 0x72, 0x61, 0x6c, 0x20, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69,
                0x6f, 0x6e, 0x73, 0x2e
        private static byte[] iow =
                0x49, 0x6e, 0x20, 0x6f, 0x74, 0x68, 0x65, 0x72, 0x20, 0x77, 0x6f,
                0x72, 0x64, 0x73, 0x2e, 0x2e, 0x2e
        private static byte[] dyogdhw =
                0x44, 0x6f, 0x20, 0x79, 0x6f, 0x75, 0x72, 0x20, 0x6f, 0x77, 0x6e,
                0x20, 0x67, 0x6f, 0x64, 0x2d, 0x64, 0x61, 0x6d, 0x6e, 0x20, 0x68,
                0x6f, 0x6d, 0x65, 0x77, 0x6f, 0x72, 0x6b, 0x21
    } // end class Inventory2Message was edited by:
    petes1234

  • Formatting text  within a TextArea in a GUI

    I am new to java but have built a simple telephone directory operated through a gui all works ok. Program displays results in the form of a column of record numbers a column of names & a column of telephone numbers all of which are appended to a textarea with a vertical scrollbar. This works well Except that even though i have made sure the length of each record is identical by trimming or adding spaces to the text strings I cannot get the columns of information to align accuratly.
    This method worked when i printed my results to standard output (System.out.println) but when used inside a textarea each character seems to take up a different amount of space.
    When sending the record Number / Name / Telephone Number to the text area I have just appended 1 long assembled string. Will add code if requested but have quite a few lines spread over several classes
    Thanks in Advance

    Cheers guys monospaced worked well but i will need to look at JTable more deeply at a glance it looks excellent. One more silly question if i may. I understand that if i am going to attempt to put my application on another machine i must ensure it has the minimum of the J2RE bundled with my application. Could you guide me to a link that supplies installation instructions for this process. have been looking cannot seem to find exactly what i need.
    Thanks Again
    Scott

  • How to get selected text values in a textarea by mouse click?

    Hi Everyone,
    What I am trying to do is to click on some texts in a textarea, then get the selected text value.
    If you guys have used an accounting software called Simply Accounting, you might understand better.
    I list all my customer names in a textarea. What I want is, when I click on one customer, another GUI pops up with this customer's information. My problem is that I don't know how to get the selected text value from a textarea.
    Could anyone give a hand here? Thank you in advance.

    Is there some reason you aren't using a JList or
    JTable to display
    the user names/information?Thank you for es5f2000's reply. You just gave me a better idea! There is not a particular reason I have to use TextArea to list my customers. As long as the component can make my idea alive, I definitely use it. Still, if there is any way to get a selected text value, it will help me a lot with my project. Thank you.

  • Read from text file, display in textarea

    java newbie here - I'm trying to write a chat program that checks a text file every 1 second for new text, and then writes that text to a textArea. I've got the thread setup and running, and it checks and text file for new text - all that works and prints to system console - but I have no idea how to print that text to a textArea.
    I've tried textArea.append, but it seems this only works on the initial run - if I put it in the thread, it won't work. I can make textArea.append work if its in an ActionEvent - but how would I make an ActionEvent run only when my script detects new text from my text file?
    Any ideas on how to do this are appreciated.
    --Mike                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    I've tried textArea.append, but it seems this only works on the initial
    run - if I put it in the thread, it won't work. I can make textArea.append
    work if its in an ActionEvent - but how would I make an ActionEvent
    run only when my script detects new text from my text file? ?
    It doesn't matter if you call the textArea.append() when the ActionEvent is triggered or if you call textArea.append() directly from a thread or any other object, the text will be append to te text area. What could have happen is you somehow lost the reference pointing to the textArea that you add to your user interface.
    example:
    JTextArea txtArea = blah..blah..blah
    MyThread t = new myThread(txtArea);
    class MyThread extends Thread{
        private JTextArea txtArea;
        public MyThread(Thread textArea){
            this.textArea = textArea;
        public void run(){
            textArea = new JTextArea(); // opps..you lost the reference to the textArea in the main gui...what you have done is created a new JTextArea object and point to tat..and this textarea object is not visible.
    }

  • How can i display HTML text in a TextArea

    Hello All,
    We are developing a chat application using Java Swing and RMI with MySQL as backend.
    We have two options.The users can chat thro both browser and application(Swing GUI).
    Now when a user who chats thro a browser sends a message,the chat contents are stored in HTML format in the database (like <BR><font>R u There?</Font></BR>).When the other user happens to chat thro the application,the chat contents send by the other user has to appear in the HTML format in the TextArea of the application.So obviously the textarea shud understand the HTML and display it accordingly.
    How can i do this?Kindly give me an example with some code samples if i have to use EditorPane etc 'coz i haven't got any experience using EditorPanes.
    Thanks in advance
    Regards
    Vijayakannan

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Test extends JFrame {
        public Test() {
         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         Container content = getContentPane();
         JEditorPane jep = new JEditorPane("text/html",
                  "Joe: <font color=red>R u <b>There</b>?</Font><BR>"+
                  "Mary: <font color=green>Keep ur shorts on...</Font>");
         content.add(new JScrollPane(jep), BorderLayout.CENTER);
         setSize(200,200);
         show();
        public static void main(String[] args) { new Test(); }
    }

  • 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>)"

  • Data from one gui window to another file

    Hello.
    I have the following code:-
    part of Main.java
         // create company
         BoatHireCompany octagon = new BoatHireCompany("octagon", 10);
         public Main() {
              // add default boats to octagon company
              octagon.addBoat(new RowingBoat("Titanic", 11));
              octagon.addBoat(new PedalBoat("Red", 12));
              octagon.addBoat(new PedalBoat("Green", 13));
              octagon.addBoat(new RowingBoat("London", 14));
              octagon.addBoat(new PedalBoat("White", 15));
              octagon.addBoat(new PedalBoat("White", 16));another part of main.java
         // Add code to handle the menu events
         public void actionPerformed(ActionEvent e) {
              if (e.getSource() == mfOne) { // hire a boat
                   Hire hire = new Hire("Hire a boat", this);
                   hire.setVisible(true);
                   Hire p = dlg.getBoat();
                 if( p != null) {
                       textarea.setText( p.toString() );
                          octagon.addBoat(new PedalBoat(p));
                 else {
                       textarea.setText( "Boat not added" );
              }Hire.java
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Hire extends JDialog implements ActionListener
         private JButton ok;
         private JButton cancel;
         private JTextField bid;
         private JTextField name;
         private JTextField time;
         private BoatHireCompany theBoat;
         public Hire(String sTitle, JFrame owner) {
              super (owner, sTitle, true);
              setLayout(new FlowLayout());
              setSize(350,200);
              add (new JLabel("Enter Boat ID:"));
              bid = new JTextField(20);
              add (bid);
              add (new JLabel("Enter Customer Name:"));
              name = new JTextField(20);
              add (name);
              add (new JLabel("Enter Current Time:"));
              time = new JTextField(20);
              add (time);
              ok = new JButton("Hire Boat!");
              ok.addActionListener(this);
              add(ok);
              cancel = new JButton("Cancel");
              cancel.addActionListener(this);     
              add(cancel);
         public BoatHireCompany getBoat()
              return theBoat;
         public void actionPerformed(ActionEvent e) {
              if (e.getSource() == ok) {
                  theBoat =  new BoatHireCompany(bid.getText(), name.getText(), time.getText());
              else if (e.getSource() == cancel) {
                  // data entry cancelled
                  theBoat = null;
              dispose();
    }To give you the run down I want the Hire.java interface to appear when someone clicks on a certain menu item. then some options will appear with some textfield. i know how to get all of this working fine.
    My problem is i am struggling with getting the information inputed in the hire.java GUI window to be added to by octagon boat hire company (like the ones are in the first code snippet.
    can anyone help me to try and do this?
    hope this all makes sense. many thanks in advance.
    dave.

    Hello,
    I tried the following in hire.java
    public void actionPerformed(ActionEvent e) {
              if (e.getSource() == ok) {
                   int theBid = Integer.parseInt(bid.getText());
                   int theTime = Integer.parseInt(time.getText());
                  octagon.hireBoat(theBid, name.getText(), theTime);
              else if (e.getSource() == cancel) {
                  // data entry cancelled
                  theBoat = null;
              dispose();
         }but shows the following error:-
    >
    Hire.java:42: cannot find symbol
    symbol : variable octagon
    location: class Hire
              octagon.hireBoat(theBid, name.getText(), theTime);
    ^
    1 error
    >
    i think this might be because i created the octagon in the main.java?
    or am i not understanding what you are saying?
    dave.
    Edited by: monkey124 on Apr 20, 2008 6:02 PM

Maybe you are looking for

  • The Finder Lies, Doesn't Update File Sizes or Modification Dates, Etc.

    When I save a file to my HD's (internal or otherwise), there's no guarantee that when I open a Finder window to view that file (see its file size, etc.) that the file will: • appear at all • if it does appear, that the file size will be correct, and/

  • How to create a progress bar showing status on timeout of TCP Read function

    Is there any way of creating a progress bar showing the status of a 'TCP Read timeout' time ... ? I'm sending a data request to an intranet server via TCP Write, and then using TCP Read with a 2 min. timeout to receive the requested data. During this

  • Refresh report in an iframe

      I've got a main report using WE to create an iframe(called 'adetail') and displays a detail rpt within the iframe. The main rpt has  a WE to re-run the detail rpt while maintaining the main rpt on the screen. The formula ends with: <p><strong>WEOpe

  • How do i convert an online pdf file

    How do I convert an online PDF file?

  • How to add BPC users in the batch?

    I would like to add BPC users in the batch. Does anyone know how to achieve this on BPC 7.0 MS? I think it is almost impossible to add thousand of BPC users without errors via BPC Admin Console.