Creating variables in a java swing program useing event

This is my code:
*Old School Calculator
*@Collin Doering
*Version 2.00
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class OSC {
     private static void createAndShowGUI() {
          int first = 0;
          int second = 0;
          int third = 0;
          int fourth = 0;
          int fifth = 0;
          int answer;
          System.out.println ("Calculations");
          System.out.println ("-------------");
          JFrame.setDefaultLookAndFeelDecorated(true);
          JFrame frame = new JFrame("OSC");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button1 = new JButton("1");
button1.setMnemonic(1);
button1.addActionListener
     new ActionListener() {
          public void actionPerformed (ActionEvent e) {
first = 1;
//This is when the error says "Local variable first is accesed from
with in inner class; needs to be declared final;
               System.out.println ("first = ");
JButton button2 = new JButton("2");
button2.setMnemonic(2);
button2.addActionListener
     new ActionListener() {
          public void actionPerformed (ActionEvent e) {
               System.out.println ("Second = ");
JButton buttonx = new JButton("x");
buttonx.addActionListener
     new ActionListener() {
          public void actionPerformed (ActionEvent e) {
               System.out.println ("answer: ");
JPanel panel = new JPanel(new GridLayout(10,10));
panel.add(button1);
          panel.add(button2);
          panel.add(buttonx);
          frame.getContentPane().add(panel);
panel.setBorder(BorderFactory.createEmptyBorder(
30, //top
30, //left
10, //bottom
30) //right
frame.pack();
frame.setVisible(true);
     public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
I am trying to create variables so i can make a calculator (right now i only have buttons 1, 1 and multiply). //This is when the error says "Local variable first is accesed from
with in inner class; needs to be declared final; then when i declare it final it says <identifier expected>. Could some one please help me. thanx.

Please post code within code tags (press the "code" button).
Why are you using an inner class? Simplify:
public class OSC implements ActionListener {
button1.addActionListener( this );
public void actionPerformed( ActionEvent e ) {
    if ( e.getSource() == button1 ) . . .

Similar Messages

  • Placing a telnet session within a java swing program

    I was wondering if there was a way to maybe anchor a telnet session into a JPanel within a Java Swing program. Most of my users end up running a telnet session while using my Swing Program and I was hoping to find a way to bring the two together. If this is possible could someone point me in the right direction (like an online resource) that might show me how to do this.

    You could use sockets and a TextArea and build your own simple telnet application.
    Socket tutorial: http://java.sun.com/docs/books/tutorial/networking/sockets/index.html

  • How to convert oracle form fmb file to java swing file using Jdeveloper

    how to convert oracle form fmb file to java swing file using Jdeveloper.Please explain with detailes steps if possible or please give a link where it is available
    thanks
    Message was edited by:
    user591884

    There is no automatic way to do this in JDeveloper. I know there are some Oracle Partners offering forms to java conversion, I don't know how much of their tools are automated and done with JDeveloper. With JDeveloper+ADF you basically rewriting the Forms application from scratch (and using ADF is helpful during this process).

  • How to create desktop application for simple server program using netbeans?

    Hi,can anyone help me on this one??
    I'm am very new to java,and I already trying different example program to create desktop applications
    for simple server program but it's not working.
    This is the main program for the simple server.
    import java.io.*;
    import java.net.*;
    public class Server {
    * @param args the command line arguments
    public static void main(String[] args) {
    try{
    ServerSocket serverSocket = new ServerSocket(4488);
    System.out.println("Server is waiting for an incoming connection on port 4488");
    Socket socket = serverSocket.accept();
    System.out.println(socket.getInetAddress() + "connected");
    PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
    BufferedReader in = new BufferedReader( new InputStreamReader(socket.getInputStream()));
    String inputLine;
    while ((inputLine = in.readLine()) != null){
    out.println(inputLine);
    System.out.println("Connection will be cut");
    out.close();
    in.close();
    socket.close();
    serverSocket.close();
    }catch(IOException e){
    e.printStackTrace();
    // TODO code application logic here
    }

    and this is the Main Processing :
    import java.awt.*;
    import java.awt.event.*;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.swing.*;
    import java.text.*;
    import java.util.*;
    import java.net.*;
    import java.io.*;
    public class MainProcessing {
    private static final long serialVersionUID = 1L;
    static private boolean isApplet_ = true;
    static private InetAddress argIp_ = null;
    static private int argPort_ = 0;
    public TCPIP TCPIP_ = null;
    private InetAddress ip_ = null;
    private int port_ = 10001;
    static private boolean conectFlag = false;
    private BufferedWriter bw;
    FileOutputStream fos;
    OutputStreamWriter osw;
    public int[] current = new int[400];
    public int[] volt = new int[400];
    public int[] revolution = new int[400];
    public void init() {
    public void start() {
    if (isApplet_) {
    try {
    ip_ = InetAddress.getByName(getCodeBase().getHost());
    } catch (UnknownHostException e) {
    } else {
    ip_ = argIp_;
    if (argPort_ != 0) {
    port_ = argPort_;
    // IP&#12450;&#12489;&#12524;&#12473;&#12364;&#19981;&#26126;&#12394;&#12425;&#20309;&#12418;&#12375;&#12394;&#12356;
    if (ip_ != null) {
    // &#12467;&#12493;&#12463;&#12471;&#12519;&#12531;&#12364;&#25104;&#31435;&#12375;&#12390;&#12356;&#12394;&#12356;&#12394;&#12425;&#12289;&#25509;&#32154;
    if (TCPIP_ == null) {
    TCPIP_ = new TCPIP(ip_, port_);
    if (TCPIP_.getSocket_() == null) {
    System.out.println("&#12511;&#12473;&#65297;");
    // &#12456;&#12521;&#12540;&#12513;&#12483;&#12475;&#12540;&#12472;&#12434;&#34920;&#31034;
    return;
    if (TCPIP_ == null) {
    System.out.println("&#12511;&#12473;&#65298;");
    return;
    System.out.println("&#25104;&#21151;");
    conectFlag = true;
    try {
    TCPIP_.sendF();
    } catch (IOException ex) {
    Logger.getLogger(MainProcessing.class.getName()).log(Level.SEVERE, null, ex);
    System.out.println("" + conectFlag);
    return;
    public void receive() {
    try {
    // Calendar cal1 = Calendar.getInstance(); //(1)&#12458;&#12502;&#12472;&#12455;&#12463;&#12488;&#12398;&#29983;&#25104;
    // int year = cal1.get(Calendar.YEAR); //(2)&#29694;&#22312;&#12398;&#24180;&#12434;&#21462;&#24471;
    // int month = cal1.get(Calendar.MONTH) + 1; //(3)&#29694;&#22312;&#12398;&#26376;&#12434;&#21462;&#24471;
    // int day = cal1.get(Calendar.DATE); //(4)&#29694;&#22312;&#12398;&#26085;&#12434;&#21462;&#24471;
    // int hour = cal1.get(Calendar.HOUR_OF_DAY); //(5)&#29694;&#22312;&#12398;&#26178;&#12434;&#21462;&#24471;
    // int min = cal1.get(Calendar.MINUTE); //(6)&#29694;&#22312;&#12398;&#20998;&#12434;&#21462;&#24471;
    // int sec = cal1.get(Calendar.SECOND); //(7)&#29694;&#22312;&#12398;&#31186;&#12434;&#21462;&#24471;
    byte[] rev = TCPIP_.receive();
    // System.out.println("&#21463;&#20449;");
    if (rev != null) {
    byte[] Change = new byte[1];
    int j = 0;
    for (int i = 0; i < 1200; i++) {
    Change[0] = rev;
    current[j] = decimalChange(Change);
    i++;
    Change[0] = rev[i];
    volt[j] = decimalChange(Change);
    i++;
    Change[0] = rev[i];
    revolution[j] = decimalChange(Change);
    } catch (NullPointerException e) {
    public int decimalChange(byte[] byteData) {
    int bit0, bit1, bit2, bit3, bit4, bit5, bit6, bit7;
    int bit = 0;
    for (int i = 0; i < 8; i++) {
    int a = (byteData[0] >> i) & 1;
    System.out.print(a);
    System.out.println();
    return 1;
    public void destroy() {
    // &#20999;&#26029;
    if (TCPIP_ != null) {
    TCPIP_.disconnect();
    if (TCPIP_.getSocket_() != null) {
    try {
    System.out.println("\ndisconnect:" + TCPIP_.getSocket_().getInetAddress().getHostAddress() + " " + TCPIP_.getSocket_().getPort());
    } catch (Exception e) {
    TCPIP_ = null;
    public boolean conect(int IP) {
    conectFlag = false;
    String address = "192.168.1." + IP;
    System.out.println(address);
    try {
    argIp_ = InetAddress.getByName(address);
    } catch (UnknownHostException e) {
    // xp.init();
    isApplet_ = false;
    start();
    return (conectFlag);
    public void send(String command, int value, int sendData[][], int i) {
    int j = 0;
    Integer value_ = new Integer(value);
    byte values = value_.byteValue();
    Integer progNum = new Integer(i);
    byte progNums = progNum.byteValue();
    try {
    TCPIP_.send(command, values, progNums);
    for (j = 1; j <= i; j++) {
    Integer time = new Integer(sendData[j][0]);
    byte times = time.byteValue();
    Integer power = new Integer(sendData[j][1]);
    byte powers = power.byteValue();
    TCPIP_.send(times, powers);
    TCPIP_.flush();
    } catch (IOException ex) {
    Logger.getLogger(MainProcessing.class.getName()).log(Level.SEVERE, null, ex);
    public void file(String name) {
    ublic void fileclose(String name, String command, int value, int sendData[][], int i) {
    try {
    fos = new FileOutputStream("" + name + ".csv");
    osw = new OutputStreamWriter(fos, "MS932");
    bw = new BufferedWriter(osw);
    String msg = "" + command + "," + value + "";
    bw.write(msg);
    bw.newLine();
    for (int j = 1; j <= i; j++) {
    msg = "" + j + "," + sendData[i][0] + "," + sendData[i][1];
    bw.write(msg);
    bw.newLine();
    bw.close();
    } catch (IOException ex) {
    Logger.getLogger(MainProcessing.class.getName()).log(Level.SEVERE, null, ex);

  • Produce EXE files for Swing programs using Visual J++?

    There's a way to make VJ++ to compile Swing programs:
    http://www.stanford.edu/class/cs108/usingvj.html
    But the exe file VJ++ produces won't run though... Does anyone know how to make it work? Thanx in advance

    TestStand 4.0.1 was released well before Visual Studio 2012 existed so the automatic step into behavior from TestStand that launches visual studio and attaches it as a debugger likely does not work.
    But you can just attach to the seqedit.exe process from Visual Studio and set breakpoints in your code and debug teststand just like you would any other process from Visual Studio. Make sure that when you attach with Visual Studio that you make sure you have it set to debug native code.
    Hope this helps,
    -Doug

  • How many threads can be created in a java swing program?

    At first, I intend to use Timer to create a 2D plot repeatedly after a certain number of milliseconds. This is for an animation. However, I discover that it takes a lot of time to generate each 2D plot frame ( about 700 milliseconds on a 1.13 MHz computer, this is a complicated plot requiring a lot of computations). So I think I should use SwingWorkers, that means a new thread for each generated graph image. There might be 1000 images to be created, and thus there might be thousands of threads in my programs. I would like to know if there is any limitation on the number of threads generated in a program so that it will be safe, or is it ok to generate as many threads as you want, as long as you follow strictly the syntax of creating threads?
    I would be thankful if someone can give me some advice.

    as there is no restriction in the Language Specification (http://java.sun.com/docs/books/jls/second_edition/html/memory.doc.html#28457) i would think it's theoretically indefinit. of course, it has a maximum because of your memory. ;-)

  • Create exe from a java prog that uses Jess rule engine

    Hi,
    Im not sure if this is the right forum but how do I do this?
    Im trying to use the free programs at
    http://www.excelsior-usa.com/articles/java-to-exe.html
    which links to java EXE creators like
    JSmooth, Launch4j, jstart32, exeJ, Java Launcher, Janel, jstart, Roxes Ant Tasks ,Marner Java Launcher, jelude
    I can't get them to work with the .clp .jar Jess file. Has anyone tried to convert a java file with Jess rule engine into an EXE? Can you please help me with it?
    thanks n best rgds
    rick

    I never had version 11.5 installed but I had the create bookmarks option. I had version 11.0 installed and had the create bookmarks option.
    I'm still having problems installing Crystal Reports XI R2. It makes it through the entire installation and then a screen pops up telling me that it can not find "CrystalReports.msi". It is looking for this file in a temp file. I use the browse button and point it to the proper file location but it still won't accept it. The only thing I can do is exit out of the installation. Am I doing something wrong? Do I have to do something special to upgrade Crystal Reports?

  • How to allow a user to create his workspace in java(swings)

    hello guys ..
    i have to develop an interface (GUI) where i allow the user to create his own workspace , could anybody tell me what is the code we need. are there any specific inbuilt functions and methods..
    please help
    Imran

    public class Workspaceextends javax.swing.JPanelimplements org.jivesoftware.smack.PacketListener
    The inner Container for Spark. The Workspace is the container for all plugins into the Spark install. Plugins would use this for the following:
    Add own tab to the main tabbed pane. ex.
    Workspace workspace = SparkManager.getWorkspace(); JButton button = new JButton("HELLO SPARK USERS"); workspace.getWorkspacePane().addTab("MyPlugin", button);
    Retrieve the ContactList.

  • Java swing program

    Windows-based Java program that can perform currency conversion for the user. The program will give the user the ability to enter the desired amount to convert, the currency type to convert from and to and a button to invoke the conversion. The program should also provide the user a separate dialog to set the conversion rates between each possible currency combination. The program should handle conversions between dollars, pounds and euros.
    •     The program must offer the user three ways to submit the conversion request: a button, a menu item (described below), or hit the Enter key after entering the amount in the transfer text field.
    •     The menu item method must display a new dialog with all necessary fields to accomplish the conversion. When complete, the menu item window must disappear and its results will be displayed on the main window.
    •     The text field indicating the amount to convert must allow the user to input the values in units and cents. Also, all display values must be in units and cents.
    •     A separate menu item that opens a dialog must be provided to set the conversion rates. The default values when the program starts should be randomly generated between 1.00 and 2.00. Reverse conversions should be the inverse of the opposite conversion.
    •     The program must also provide a button to select an amount to convert that is randomly generated between 1,000 and 2,000 in units and cents.
    Edited by: chota on Sep 21, 2008 7:38 PM

    you could charge for homework assignments :)) // I would
    dont know why its in the swing section tho... no mention in the assignment task of GUI, just email a CLI application IMHO
    does the poster want a pass / credit / distinction ?? the code will vary and so will the cost....

  • New in Java: java applet program using multithreading

    I am trying to write a program, which should move the words "Java Platform2" from left to right every time we 'refresh'.
    Can you please advise what is wrong in the logic??
    import java.applet.*;
    import java.awt.*;
    import java.lang.*;
    public class Ch61appth extends Applet implements Runnable
    int i=30;
    int x=10;
    int y=30;
    Thread t,cur;
         public void start()
              t=new Thread(this);
              t.start();
         public void paint(Graphics g)
              g.setColor(Color.blue);
              g.drawString("Java Platform2",x+i,y);
         public void run()
                   if ((x+i)<400)
                        {     i=i+20;
                        else
                        {     i=20;
              //cur=new Thread.currentThread();
              repaint();

    thanks for reply
    i tried using for loop. Earlier also i had tried using while loop with condition t==Thread.currentThread()
    The problem i am facing is the string just does not move and even after clicking refresh, it appears at same locations.
    CAN U ADVISE>
    bye
    kumar

  • Java/jsp programing using timer

    what I want to do is say
    at 8am every day
    send email news letter to all members on the database.
    without the press of a button on my side.
    anyone done such programing with java?
    Sample codes will bve much appreciated.
    Thanks in advance

    This sounds a good idea nut that means the hosting co
    have to allow the OS job to trigger it az 8 pm on
    their system because something has to be on
    permanently for it to happen.Well, that is information you might have given right away. In that case, you might be short of luck for a reliable way to do it. At least I can't think of a way - if all you can do is call a servlet, you'll need to activate it on 8 am yourself daily. I don't think you can make the servlet run in an endless loop that keeps it "alive" for eternity, to repeatedly trigger the mailing. I mean you probably can, but my bet is that it gets killed by the container after a certain timeout.

  • Problem in java swing programming

    Hello
    I am developing one project. I which i put one main menu from which user choose various options.
    One of the option is associating students with the batch.
    As user choose this option, it opens one frame in which user get one comobox containing list of batches that are already announced in the system.
    As user choose any of these batch number, i want that frame shows the one JLabel control and one JList control shows list of candidates registered for the course for which selected batch has announced.
    For that i put one penal in the frame which implements ActionListener interface and registered this panel as the ActionListener of this batch combobox. As user choose any of the batch from this combobox in the actionPerformed method i call repaint method.
    In the paintComponent method of panel i add two control one JLabel and one JList .
    But my panel or frame does not show these control.
    What should i do.
    I also want to know i develop projects in JDK1.2 will it runs on JDK1.3 or JDK1.4
    Because i was using JDK1.2 but it had deleted and i now i am unable to get that version.

    Here is some good advice. Take time to download a new version of the SDK, it will help you do things more quickly.
    To your problem, I believe it is a matter of switching components within the application. To switch components, you need to use the container.remove(Component c) method, and then use container.add(Component c)Finally you need to validate the container and repaint it to show your newly added component. So in all
    container.remove(somecomponent);
    container.add(anothercomponent);
    container.validate();
    container.repaint();Hope this helps one way or the other
    ICE

  • Java Network Programming using UDP protocol

    I am trying to send the object using UDP protocol.
    In my client class it is giving me NullPointer excetion at clientSocket.send(sendPacket); although sendPacket is not null it has the value that I am passing.
    Here is the code :
    private boolean clientSrvrComm(AuditorData audData) throws Exception
              boolean result = false;
              ByteArrayOutputStream barray_out = new ByteArrayOutputStream();
              ObjectOutputStream obj_out = new ObjectOutputStream(barray_out);
              obj_out.flush();
              obj_out.writeObject(audData);
              obj_out.flush();
              // sending the data to the server
              byte[] sendData = barray_out.toByteArray();
              DatagramPacket sendPacket = new DatagramPacket(sendData,sendData.length,IPAddress,serverPort);
              clientSocket.send(sendPacket); // getting exception at this line
              return result;
         } // method end
    I am passing audData through main method.
    Any help would be appreciate.
    Thanks,
    Swati

    actually it shouldn't give the null pointer exception and send the object to the server.
    I am not able to get, why it is throwing the exception, even there is no class for debugging.

  • How to create a semi circuler slider using java swing or awt

    I am trying to create a Jslider like thing but in semicirculer shape. Thanks in advance for providing any help.

    Is it possible to create such UI in java swing?Just to further illustrate, Swing only provides the raw foundation you need to be able to build a GUI. With the stock components you can create static user interfaces with standard controls. If you want to go further, you need to either find a component that somebody else already wrote, or you go into custom painting as previous posters suggested. To do an animating component for example, you would need all the frames as BufferedImage objects and you would combine custom painting with a Swing timer to update the displayed frame at a specified framerate.
    if you search for "java swing animation" using google, I'm sure you can find the examples you need. And here is the trail about swing timers:
    http://java.sun.com/docs/books/tutorial/uiswing/misc/timer.html

  • Need help for connecting Ms Acces with java Swing in Mac OS

    Hi all,
    i need to connect to Ms Access in MAc os through my java swing program.
    Is it possible for accessing Ms access through dsn in Mac OS.
    If Possible which driver shall i use for Establishing Connection with MS Access in Mac OS.
    Suggestion is needed urgently.
    Can anybody help me out regarding this..
    Thanks in advance.
    Regards,
    sreand

    if I don't find a better solution I'll try your 2nd option but what do you mean by "combo" update?
    My understanding is to simply insert the OS 10.5 installation CD, reinstall the OS and the just keep updating it via the OS SSoftware update panel and stop untill I see the scary Java 8 update. Is that what you meant?
    While you can do it that way, the combo update picks up operating system updates through a collection of releases. When dealing with operating system upgrades, I've found using the combo updates to be more reliable than Software Update, as sometimes Software Update doesn't apply updates correctly, and weird things can happen. Doesn't happen often though, thankfully.
    So the OS X 10.5.5 Combo update contains all updates between 10.5.0 and 10.5. The 10.5.8 combo update contains the updates from 10.5 thru 10.8. Here are the updates:
    10.5 combo update: http://support.apple.com/kb/DL692
    10.8 combo update: http://support.apple.com/kb/DL866
    If you go down the combo path, repair permissions before and after doing each update. Then do Software Update for any other non-OS X updates, and don't apply the Java Update 8.

Maybe you are looking for

  • Error Handling in tables using ABap Webdynpro

    Hi All, I am new to this ABAP webdynpro programming. I have a small question. I am using a table control in one of my iview. I need to check some validations on some columns of this table. Let's say I have a table with 3 columns A,B and C.  Case 1 :

  • InDesign CS5 won't package links. tried trashing pref and saving to idml. HELP

    I've read some threads and tried trashing my preferences as well as exporting the file(s) to idml and going from there but I still get the error message that it cannot package the necessary links. I tested a file with just one link that I recently wo

  • Order by help

    Hei, my first post here, and also a sql newbie. Let's hope this is not too silly. I am trying to extract some info from my table and order the result by date (DD.MM.YYYY). My select works fine, with the resulting date list comes sorted like this: DAT

  • Is it possible to make SAP 4.6C UNICODE enabled??

    Is it possible to make SAP 4.6C UNICODE enabled??

  • Using iMovie 6.0 backups freezes my computer

    Ever since I downloaded the latest iTunes update my iMovie 6.0 backups freeze on my new La Cie 1 Terabit hard Drive. I can escape iMovie 6.0 but I can't reopen it, and I can't shut down my computer internally.