Gui programming (reply to ivcho)

hello ivo,
many thanks for helping me. It worked correctly 11 times, but in the 12th time again 3 Textfields were not visible on the screen. (If I print out the visible-property in the Java Console, it is always reported as visible = true).
Maybe I implemented Your tip wrongly, therefore I show to You how I did it (If You would like to know the complete code, please let me know it):
public class asn055_aendern extends Applet  implements  Runnable, FocusListener, KeyListener, MouseListener, ActionListener, ComponentListener, WindowListener, ItemListener{
    wFrame        f = new wFrame();
    Panel pvorname = new Panel(null);
    TextField tvorname = new TextField(20);    
    //other panels and textfields (every Textfield has its own panel)
    public void init(){
       //Frame f
        f.setBounds((int)fleft,(int)ftop,(int)fwidth,(int)fheight);
        f.setLayout (null);
        f.setBackground(Color.cyan);
        f.setName("ddd");
        f.addComponentListener(this);     
        f.addKeyListener(this);
        f.addFocusListener(this);
        f.addWindowListener(this);
        //tvorname
        tvorname.setBackground(Color.white);
        tvorname.addKeyListener(this);
        tvorname.addActionListener(this);
        tvorname.setName("tvorname"); 
        tvorname.setEnabled(true);
        pvorname.add(tvorname);
        f.add(pvorname); 
         //other Textfields
    }//End of init
   public void start() {
     f.setVisible(true);
     if(t==null){t=new Thread(this); t.start();}
   }//End of start
   public void run() {
         f.setVisible(true);
         tvorname.setText   ("anyvorname");
         wartesek(1); //the program waits one second 
         fwidth=f.getBounds().width;
         double heighttextfield= fheight*0.052;
         fsz = (int)(0.023*(double)fwidth);
         Font ftt = new Font ("SansSerif",Font.BOLD,fsz);
        //tvorname
         tvorname.setFont(ftt);               
         pvorname.setBackground(Color.yellow);
         tvorname.setBackground(Color.green);
         pvorname.setBounds((int)(left1), (int)(top1+heightlabel), (int)(width16), (int)(heighttextfield));
         tvorname.setBounds((int)(0), (int)(0), (int)(width16), (int)(heighttextfield));
         tvorname.setVisible(true);
         pvorname.setVisible(true);
         //other Textfields
         tvorname.requestFocus();
         //more Code
   }//End of run
   class wFrame extends java.awt.Frame {
     public void paint(Graphics g) {
       super.paint(g);
     }//Ende paint
   }//Ende class wFrame
}//End of class asn055_aendern

hello ivo,
yes, all of my TextFieds are added to wFrame, since I changed the Class of f from Frame to wFrame to implent the paint-methode in it, So i could override the paint-methode like You told me. But ithink that is not the problem, because the behaviour of the program is the same, no matter with wFrame or Frame. There must be another reason.
Greetings,
Alex

Similar Messages

  • Running a GUI program with no X?

    Hi,
    I want to run a GUI program on my server, which has no X installed. Of course, the program would normally not run since it needs X (GUI only). I don't really need to be directly using this software, it just needs to run. Anybody here knows if there is any way to fool it into thinking X is there, so it'll still run on my server, preferably as a service in the background?
    PS
    I probably need the same thing for sound too, no alsa or pulse either.
    Any  help's appriciated.

    I probably owe you guys an explanetion: The program in question is Skype. I'm sick and tierd of having skype steal recources when all my other IMing is done in bitlbee. That's why I came up with the following solution: I've done some reading, and turns out skype has a bitlbee plugin.
    However, that plugin uses the skype API which means I can't get around having skype. So, I decided to try the following setup: Run a bitlbee server from my home server. Have skype sorta just run in there doing nothing, and use the bitlebee plugin so I can connect with my own computer and use skype with bitlbee (Note: this is so I can chat with friends, not so I can video / audio chat so I don't care about those features). Basicly that was my idea and i'm exploring the posibility. Skype sadly has no deamon mode, but it does offer a shell pipe login so I'll start skype in my server, and do that setup. Of course now that I see i'll need to install x no matter what i'm not sure if it's worth it. I don't need X on my server for any other purpuse and X will steal recources from my server. I do however love not needing a skype client nativly. Anyone has any experiance / ideas / advice about my idea?
    Stalafin wrote:
    Greenstuff wrote:
    Hi,
    I want to run a GUI program on my server, which has no X installed. Of course, the program would normally not run since it needs X (GUI only). I don't really need to be directly using this software, it just needs to run. Anybody here knows if there is any way to fool it into thinking X is there, so it'll still run on my server, preferably as a service in the background?
    PS
    I probably need the same thing for sound too, no alsa or pulse either.
    Any  help's appriciated.
    Wut? You want to output sound without anything that is able to output sound? Is it me or is that just plain weird....? o.O
    I realize it sounds comfusing but Skype needs somewhere to dump sound apperantly (I found that out on my resharch). So I need a way to fool it into thinking there's such a device.
    Last edited by Greenstuff (2009-11-03 21:24:29)

  • GUI program help

    I'm writing a GUI program that involves drawing several shapes, lines, and images to a JPanel. Some of the shapes need to be dragged around the screen by the user, while others will remain stationary. I can't figure out the overall organization of how the drawing should be done. Some questions are:
    1. what type of code should go in the paintComponent method of JPanel?
    2. Should the JFrame class implement MouseListener and MouseMotionListener, or should some other class implement these?
    3. Will I have to use inner classes? (In my current design, the class that extends JPanel is an inner class of the JFrame class.)
    4. How can I minimize flicker when shapes are repainted?

    1. what type of code should go in the paintComponent
    method of JPanel?Let's say you have a List of all your Shapes:
    private List shapes;
    public void paintComponent(Graphics g) {
        Graphics2D g2d = (Graphics2D) g;
        Iterator i = this.shapes.iterator();
        while (i.hasNext()) {
            //Draw your Shape
    2. Should the JFrame class implement MouseListener and
    MouseMotionListener, or should some other class
    implement these?Your pick. I'd have the listeners on your JPanel.
    3. Will I have to use inner classes? (In my current
    design, the class that extends JPanel is an inner
    class of the JFrame class.)Your pick. I prefer using inner classes instead of anonymous classes, but others will say the opposite.
    4. How can I minimize flicker when shapes are
    repainted?yourPanel.setDoubleBuffered(true);

  • Free ide for gui programming

    can someone tell me what's the best free java ide for gui programming?

    No one can answer the question of which one is better. It's like answering the question - is red more beautiful than yellow?
    I can however say that the plugins into eclipse which lets you build swing ui by drag and drop are not mature, and I don't think they work if you modify the code by hand, and then want to go back into "drag % drop" mode. The ui builder in jbuilder is nice, and doesn't clutter the code, and it works even if you have modified the code by hand.
    /kaj

  • Gui programming Python

    Hi All,
    I'm looking to improve / learn more on gui programming within python.
    I'm not sure if i should be writing the code manualy or using the libglade / glade designer to produce results.
    My main aim with most of my programming is to keep things slim. i use openbox so i don't want to pull in loads of gnome crap to make something work.
    How do you guys go about it etc?
    Regards
    Matthew

    I guess your options are pyQt, pyGtk, Tkinter (included with python), and wxPython.
    I've been playing around with wxpython for a little while now and I quite like it. I really enjoy that it is fairly cross platform (without requiring gtk, qt, or tk/tcl on Windows or Mac) and the wxpython demo program is just fantastic.
    IIRC, the demo isn't packaged with wxpython in Arch, but you can download it separately and extract it to a folder in your home directory with no problems.

  • Best way for gui programming? swing awt jfc swt ....

    hi,
    i have been programming java for some time but exclusively for web, servlets, jsp etc..
    but now i have to do some �real� gui�s. I have no gui experience , (ok I did some basic examples just to see how things work) but/and I�m not able to determine which way I should go.
    So I did some google search and read some threads here im forum on topics swing vs. awt (or so) and found lot of topics with lot of different opinions(some of them also a little bit out of date) so now im CONFUSED more then ever.
    I read people asking questions like :what is better awt or swing and then getting the perfect technical answers like :
    AWT components are NOT native components. AWT components are Java objects. Particular instances of AWT componets (Button, Label, etc.) MAY use peers to handle the rendering and event handling. Those peers do NOT have to be native components. And AWT components are NOT required to use peers for themselves at all.
    Or
    There are some significant differences between lightweight and heavyweight components. And, since all AWT components are heavyweight and all Swing components are lightweight (except for the top-level ones: JWindow, JFrame, JDialog, and JApplet), these differences become painfully apparent when you start mixing Swing components with AWT components.
    But I don�t care that much(at least not now) about this detail answers.
    I would simply like to know from some experienced gui guru, (due to the fact that we have 2005 and java 1.5) if u would like to learn gui in java quickly and know everything u know now which way would u choose:
    AWT
    JFC
    SWING
    SWT
    And which IDE would u use.
    I simply want to get quickly started and do some basic gui programming ,nothing special, but I would like to avoid that after weeks of doing one, then find out the was the wrong one and again learn the another one.
    TIA Nermin

    try swt vs swing and see what you think, its not really a decision someone else can make for you. as long as you don't try and mix the two, it should be a similar learning curve either way.

  • Client-Server side GUI programming

    I want to create a client-server side gui programming with java
    i read this web adress
    http://java.sun.com/docs/books/tutorial/networking/sockets/clientServer.html
    for information but there are some parts that i didnt understand and wait for your help
    i m trying to build an online-help(live chat) system so when people press the start chat button a java page will appear but i wonder how this will connect to the person who is on server side
    i mean is it possible to 2 users connect the same port and chat with each other
    I mean when user press the chat button the online help supporter will be informed somebody wants to speak with him and they will start a chat
    how can i do something like that
    any help would be usefull thanks

    Below is an example of a client/server program.
    It shows how the server listens for multiple clients.
    * TriviaServerMulti.java
    * Created on May 12, 2005
    package server;
    * @author johnz
    import java.io.*;
    import java.net.*;
    import java.util.Random;
    * This TriviaServer can handle multiple clientSockets simultaneously
    * This is accomplished by:
    * - listening for incoming clientSocket request in endless loop
    * - spawning a new TriviaServer for each incoming request
    * Client connects to server with:
    * telnet <ip_address> <port>
    *     <ip_address> = IP address of server
    *  <port> = port of server
    * In this case the port is 4413 , but server can listen on any port
    * If server runs on the same PC as client use IP_addess = localhost
    * The server reads file
    * Note: a production server needs to handle start, stop and status commands
    public class TriviaServerMulti implements Runnable {
        // Class variables
        private static final int WAIT_FOR_CLIENT = 0;
        private static final int WAIT_FOR_ANSWER = 1;
        private static final int WAIT_FOR_CONFIRM = 2;
        private static String[] questions;
        private static String[] answers;
        private static int numQuestions;
        // Instance variables
        private int num = 0;
        private int state = WAIT_FOR_CLIENT;
        private Random rand = new Random();
        private Socket clientSocket = null;
        public TriviaServerMulti(Socket clientSocket) {
            //super("TriviaServer");
            this.clientSocket = clientSocket;
        public void run() {
            // Ask trivia questions until client replies "N"
            while (true) {
                // Process questions and answers
                try {
                    InputStreamReader isr = new InputStreamReader(clientSocket.getInputStream());
                    BufferedReader is = new BufferedReader(isr);
    //                PrintWriter os = new PrintWriter(new
    //                   BufferedOutputStream(clientSocket.getOutputStream()), false);
                    PrintWriter os = new PrintWriter(clientSocket.getOutputStream());
                    String outLine;
                    // Output server request
                    outLine = processInput(null);
                    os.println(outLine);
                    os.flush();
                    // Process and output user input
                    while (true) {
                        String inLine = is.readLine();
                        if (inLine.length() > 0)
                            outLine = processInput(inLine);
                        else
                            outLine = processInput("");
                        os.println(outLine);
                        os.flush();
                        if (outLine.equals("Bye."))
                            break;
                    // Clean up
                    os.close();
                    is.close();
                    clientSocket.close();
                    return;
                } catch (Exception e) {
                    System.err.println("Error: " + e);
                    e.printStackTrace();
        private String processInput(String inStr) {
            String outStr = null;
            switch (state) {
                case WAIT_FOR_CLIENT:
                    // Ask a question
                    outStr = questions[num];
                    state = WAIT_FOR_ANSWER;
                    break;
                case WAIT_FOR_ANSWER:
                    // Check the answer
                    if (inStr.equalsIgnoreCase(answers[num]))
                        outStr="\015\012That's correct! Want another (y/n)?";
                    else
                        outStr="\015\012Wrong, the correct answer is "
                            + answers[num] +". Want another (y/n)?";
                    state = WAIT_FOR_CONFIRM;
                    break;
                case WAIT_FOR_CONFIRM:
                    // See if they want another question
                    if (!inStr.equalsIgnoreCase("N")) {
                        num = Math.abs(rand.nextInt()) % questions.length;
                        outStr = questions[num];
                        state = WAIT_FOR_ANSWER;
                    } else {
                        outStr = "Bye.";
                        state = WAIT_FOR_CLIENT;
                    break;
            return outStr;
        private static boolean loadData() {
            try {
                //File inFile = new File("qna.txt");
                File inFile = new File("data/qna.txt");
                FileInputStream inStream = new FileInputStream(inFile);
                byte[] data = new byte[(int)inFile.length()];
                // Read questions and answers into a byte array
                if (inStream.read(data) <= 0) {
                    System.err.println("Error: couldn't read q&a.");
                    return false;
                // See how many question/answer pairs there are
                for (int i = 0; i < data.length; i++)
                    if (data[i] == (byte)'#')
                        numQuestions++;
                numQuestions /= 2;
                questions = new String[numQuestions];
                answers = new String[numQuestions];
                // Parse questions and answers into String arrays
                int start = 0, index = 0;
                   String LineDelimiter = System.getProperty("line.separator");
                   int len = 1 + LineDelimiter.length(); // # + line delimiter
                boolean isQuestion = true;
                for (int i = 0; i < data.length; i++)
                    if (data[i] == (byte)'#') {
                        if (isQuestion) {
                            questions[index] = new String(data, start, i - start);
                            isQuestion = false;
                        } else {
                            answers[index] = new String(data, start, i - start);
                            isQuestion = true;
                            index++;
                    start = i + len;
            } catch (FileNotFoundException e) {
                System.err.println("Exception: couldn't find the Q&A file.");
                return false;
            } catch (IOException e) {
                System.err.println("Exception: couldn't read the Q&A file.");
                return false;
            return true;
        public static void main(String[] arguments) {
            // Initialize the question and answer data
            if (!loadData()) {
                System.err.println("Error: couldn't initialize Q&A data.");
                return;
            ServerSocket serverSocket = null;
            try {
                serverSocket = new ServerSocket(4413);
                System.out.println("TriviaServer up and running ...");
            } catch (IOException e) {
                System.err.println("Error: couldn't create ServerSocket.");
                System.exit(1);
            Socket clientSocket = null;
            // Endless loop: waiting for incoming client request
            while (true) {
                // Wait for a clientSocket
                try {
                    clientSocket = serverSocket.accept();   // ServerSocket returns a client socket when client connects
                } catch (IOException e) {
                    System.err.println("Error: couldn't connect to clientSocket.");
                    System.exit(1);
                // Create a thread for each incoming request
                TriviaServerMulti server = new TriviaServerMulti(clientSocket);
                Thread thread = new Thread(server);
                thread.start(); // Starts new thread. Thread invokes run() method of server.
    }This is the text file:
    Which one of the Smothers Brothers did Bill Cosby once punch out?
    (a) Dick
    (b) Tommy
    (c) both#
    b#
    What's the nickname of Dallas Cowboys fullback Daryl Johnston?
    (a) caribou
    (b) moose
    (c) elk#
    b#
    What is triskaidekaphobia?
    (a) fear of tricycles
    (b) fear of the number 13
    (c) fear of kaleidoscopes#
    b#
    What southern state is most likely to have an earthquake?
    (a) Florida
    (b) Arkansas
    (c) South Carolina#
    c#
    Which person at Sun Microsystems came up with the name Java in early 1995?
    (a) James Gosling
    (b) Kim Polese
    (c) Alan Baratz#
    b#
    Which figure skater is the sister of Growing Pains star Joanna Kerns?
    (a) Dorothy Hamill
    (b) Katarina Witt
    (c) Donna De Varona#
    c#
    When this Old Man plays four, what does he play knick-knack on?
    (a) His shoe
    (b) His door
    (c) His knee#
    b#
    What National Hockey League team once played as the Winnipeg Jets?
    (a) The Phoenix Coyotes
    (b) The Florida Panthers
    (c) The Colorado Avalanche#
    a#
    David Letterman uses the stage name "Earl Hofert" when he appears in movies. Who is Earl?
    (a) A crew member on his show
    (b) His grandfather
    (c) A character on Green Acres#
    b#
    Who created Superman?
    (a) Bob Kane
    (b) Jerome Siegel and Joe Shuster
    (c) Stan Lee and Jack Kirby#
    b#

  • How to start a Web GUI program from a Web Dynpro application

    I know the program name , and it is a Web GUI program ,is anybody know how to start it from a Web Dynpro application

    hi,
    I use the following program to call a SAP GUI program :
    DATA: l_componentcontroller TYPE REF TO ig_componentcontroller.
      DATA: l_api_componentcontroller type ref to if_wd_component.
      DATA: l_sapgui_manager type ref to cl_wdr_sapgui_integration.
      DATA: lt_parameters    TYPE wdr_name_value_list.
      l_componentcontroller = wd_this->get_componentcontroller_ctr( ).
      l_api_componentcontroller = l_componentcontroller->wd_get_api( ).
      l_sapgui_manager = l_api_componentcontroller->get_sapgui_manager( ).
      IF l_sapgui_manager IS NOT INITIAL.
        l_sapgui_manager->fire( EXPORTING name = 'PROGRAM_NAME 'parameters = lt_parameters ).
    But the l_sapgui_manager is always initial , what can I do ?
    ENDIF.

  • [SOLVED]some console commands without console make gui programs killed

    I'm using openbox as WM. I think it is openbox that causes the trouble
    it seems that when I try ot execute some console application without console but the application needs user input, the problem occurs.
    when the issue arises, gui programs gets killed, leaving its window blank.
    not all of gui programs though, chromium and conky got closed but xterm didn't.
    however, they survive when they are executed with xterm.
    I could reproduce the problem with sudo or alsamixer, run by either right-click menu or gmrun.
    Is there anyone experiencing the same issue?
    sorry for my english.
    Last edited by freaxtux (2012-08-25 03:05:17)

    If you are trying to run a console or terminal application that needs user input, it must be run in a terminal window.  For example, to run alsamixer from the openbox menu I would have this in my ~/.config/openbox/menu.xml:
    <item label="Alsamixer">
    <action name="Execute">
    <execute>xterm -e alsamixer</execute>
    </action>
    </item>
    The command on the line with "<execute>" opens an xterm window and then the '-e' option tells xterm to run the next command on that line.
    Urxvt also uses the '-e' option to run commands.  To get htop to run from the open box menu in a urxvt window, I would use this:
    <item label="Htop">
    <action name="Execute">
    <execute>urxvt -e htop</execute>
    </action>
    </item>
    For gmrun, I believe you use Ctrl-Enter to have it open an app in a terminal.  At least that is what the wiki page says: https://wiki.archlinux.org/index.php/Gmrun

  • Creating GUI programs

    Not that I have any immediate intention to do so, but I was wondering if you can create simple GUI programs like say a a message box with a line of text on it just using your text editor and the j2sdk. Or does it become necessary to use an IDE for that?

    Not that I have any immediate intention to do so, but
    I was wondering if you can create simple GUI programs
    like say a a message box with a line of text on it
    just using your text editor and the j2sdk. Or does it
    become necessary to use an IDE for that?IDE's are not necessary to do anything. You can create any program you want with just a text editor and the SDK.
    IDE's add a level of simplicity to the process (some do).

  • NoSuchMethodError in GUI program

    Howdy, I have a GUI program that gets decimal input from the user and converts it to a binary string. It uses JButtons, JTextFields, and JLabels. When I compile and run the program, it says:
    java.lang.NoSuchMethodError: main
    Exception in thread "main"
    I really can't figure it out. I have asked everyone around me that knows anything about java to no avail. Thank you. Any help would be greatly appreciated.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.lang.Integer;
    public class binConvertGUI extends JFrame implements ActionListener
           JButton enter = new JButton("Calculate");
           JLabel lbl1 = new JLabel("Enter decimal: ");
           JLabel lbl2 = new JLabel("Binary: ");
           JTextField txt1 = new JTextField(12);
           JTextField txt2 = new JTextField(12);
           JPanel panA = new JPanel();
           JPanel panB = new JPanel();
           String userInA;
           String num;
           int decnum;
           public binConvertGUI()
                  getContentPane().setLayout(
                        new FlowLayout());
                  panA.add(lbl1);
                  panA.add(txt1);
                  panB.add(lbl2);
                  panB.add(txt2);
                  getContentPane().setLayout(
                        new BoxLayout( getContentPane(), BoxLayout.Y_AXIS ));
                  getContentPane().add(panA);
                  getContentPane().add(panB);
                  getContentPane().add(enter);
                  enter.addActionListener(this);
                  txt1.addActionListener(this);
                  enter.setActionCommand("Calculate");
                  txt2.setEditable(false);
           public void actionPerformed(ActionEvent evt)
                  if(evt.getActionCommand().equals("Calculate"))
                        userInA = txt1.getText();
                        decnum = Integer.parseInt(userInA);
                        num = Integer.toBinaryString(decnum);
                        txt2.setText(num);
                  repaint();
           public void main (String[] args) throws NoSuchMethodError
                  binConvertGUI frm = new binConvertGUI();
                  WindowQuitter wquit = new WindowQuitter();
                  frm.addWindowListener( wquit );
                  frm.setSize( 300, 300 );
                  frm.setVisible( true );
    class WindowQuitter extends WindowAdapter
      public void windowClosing( WindowEvent e )
        System.exit( 0 );
    }

    You just forgot the fact that the main() method is always static:
       public static void main (String[] args) throws NoSuchMethodError {
       //...

  • GUI program... CALCULATE button not working... help please

    I am trying to make my GUI work... all buttons work except my CALCULATE button... which I want to say...
    if Binary radio button is set... and user inputs string into the txtFieldOne....
    then when click Calculate - go to my function called "convertBinary( )" and do the conversions and display or setText in the other txtFields...
    For now... some of my code is comented out... but if I could get some help.. that would be great!
    I am trying to use:
    //CALCULATE BUTTON FUNCTION AND EXECUTIONS
              private class CalculateButtonHandler implements ActionListener{
                   public void actionPerformed(ActionEvent e){
                        //if (radioBinary.isSelected() == true)
                        //System.convertBinary(); //NEED TO FIX
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.text.*;
    import java.util.*;
    public class cis279hw3_new extends JFrame{
    //class variables
         private Container pane;
         private JTextField txtFieldOne,txtFieldTwo,txtFieldThree,txtFieldFour,txtFieldFive;
         private JButton buttonClear,buttonCalculate,buttonExit;
         private JRadioButton radioBinary,radioDecimal,radioHex,radioOctal;     
         private ButtonGroup RadioButtonGroup;
    //BUTTON AND RADIO BUTTON HANDLERS
         private ExitButtonHandler exitHandler;
         private ClearButtonHandler clearHandler;
         private CalculateButtonHandler calculateHandler;
         private RadioButtonHandler radioHandler;
         cis279hw3_new(){
              //textfields
              txtFieldOne = new JTextField(); //Inputs value from user
              txtFieldTwo = new JTextField();
              txtFieldThree = new JTextField();
              txtFieldFour = new JTextField();
              txtFieldFive = new JTextField(); //Displays error message
              //buttons
              buttonClear = new JButton("Clear");
              buttonCalculate = new JButton("Calculate");
              buttonExit = new JButton("Exit");
              //radio buttons
              radioBinary = new JRadioButton("Binary");
              radioDecimal = new JRadioButton("Decimal");
              radioHex = new JRadioButton("Hexadecimal");
              radioOctal = new JRadioButton("Octal");
              RadioButtonGroup = new ButtonGroup(); //create radio button group
              //add radio buttons to the button group
              RadioButtonGroup.add(radioBinary);
              RadioButtonGroup.add(radioDecimal);
              RadioButtonGroup.add(radioHex);
              RadioButtonGroup.add(radioOctal);
              //pane - create pane and add objects to the pane interface
              pane = getContentPane(); // get the pane and associate with this JFRAME
              pane.setLayout(new GridLayout (6,2));
              //ROW 1          
              pane.add(radioBinary);
              pane.add(txtFieldOne);
              //ROW 2                    
              pane.add(radioDecimal);
              pane.add(txtFieldTwo);
              //ROW 3                    
              pane.add(radioHex);
              pane.add(txtFieldThree);
              //ROW 4                    
              pane.add(radioOctal);
              pane.add(txtFieldFour);
              //ROW 5                    
              pane.add(buttonClear);
              pane.add(txtFieldFive);
              //ROW 6                    
              pane.add(buttonCalculate);
              pane.add(buttonExit);
              setTitle("Convert to Number Bases");
              setSize(600,200);
              setVisible(true);
              //FONT CALL IS TEDIOUS... HOW CAN I APPLY TO THE ENTIRE PANE IN ONE setFont????????????????
              buttonClear.setFont(new Font("Arial",0,16));
              buttonExit.setFont(new Font("Arial",0,16));
              buttonCalculate.setFont(new Font("Arial",0,16));
              radioBinary.setFont(new Font("Arial",0,16));
              radioDecimal.setFont(new Font("Arial",0,16));
              radioHex.setFont(new Font("Arial",0,16));
              radioOctal.setFont(new Font("Arial",0,16));
              txtFieldOne.setFont(new Font("Arial",0,16));
              txtFieldTwo.setFont(new Font("Arial",0,16));
              txtFieldThree.setFont(new Font("Arial",0,16));
              txtFieldFour.setFont(new Font("Arial",0,16));
              txtFieldFive.setFont(new Font("Arial",0,16));
              //create action button listeners
              clearHandler = new ClearButtonHandler();
              buttonClear.addActionListener(clearHandler);
              //create action button listeners
              calculateHandler = new CalculateButtonHandler();
              buttonCalculate.addActionListener(calculateHandler);
              //create action button listeners
              exitHandler = new ExitButtonHandler();
              buttonExit.addActionListener(exitHandler);
              //create radio button item listeners constructors
              radioHandler = new RadioButtonHandler();     
              radioBinary.addActionListener(radioHandler);
              radioDecimal.addActionListener(radioHandler);
              radioHex.addActionListener(radioHandler);
              radioOctal.addActionListener(radioHandler);     
         }     //CLOSES my 2nd class "cis279hw3_new"
              //RADIO BUTTON /TEXT FIELD SELECTION FUNCTION
              private class RadioButtonHandler implements ActionListener{     
                   public void actionPerformed(ActionEvent e){
                   if (e.getSource() == radioBinary){
                        txtFieldOne.setEditable(true);
                        txtFieldTwo.setEditable(false);
                        txtFieldThree.setEditable(false);
                        txtFieldFour.setEditable(false);
                        txtFieldFive.setEditable(false);
                   else if (e.getSource() == radioDecimal){
                        txtFieldOne.setEditable(false);
                        txtFieldTwo.setEditable(true);
                        txtFieldThree.setEditable(false);
                        txtFieldFour.setEditable(false);
                        txtFieldFive.setEditable(false);
                   else if (radioHex.isSelected() == true){
                        txtFieldOne.setEditable(false);
                        txtFieldTwo.setEditable(false);
                        txtFieldThree.setEditable(true);
                        txtFieldFour.setEditable(false);
                        txtFieldFive.setEditable(false);
                   else if (radioOctal.isSelected() == true){
                        txtFieldOne.setEditable(false);
                        txtFieldTwo.setEditable(false);
                        txtFieldThree.setEditable(false);
                        txtFieldFour.setEditable(true);
                        txtFieldFive.setEditable(false);
              //EXIT BUTTON FUNCTION AND EXECUTIONS
              private class ExitButtonHandler implements ActionListener{
                   public void actionPerformed(ActionEvent e){
                        System.exit(0);
              }; //class within a class must end in semicolon
              //CLEAR BUTTON FUNCTION AND EXECUTIONS
              private class ClearButtonHandler implements ActionListener{
                   public void actionPerformed(ActionEvent e){
                        txtFieldOne.setText(null);
                        txtFieldTwo.setText(null);
                        txtFieldThree.setText(null);
                        txtFieldFour.setText(null);
                        txtFieldFive.setText(null);
              }; //class within a class must end in semicolon
    //NEED TO USE THESE IN MY CALCUALTE BUTTON SOMEHOW     (FROM HW #1)
                        //convertBinary();
                        //convertInteger();
                        //convertHex();
                        //convertOctal();
              //CALCULATE BUTTON FUNCTION AND EXECUTIONS
              private class CalculateButtonHandler implements ActionListener{
                   public void actionPerformed(ActionEvent e){ //ActionEvent Class used here     
                        //if (radioBinary.isSelected() == true)
                        //System.convertBinary(); //NEED TO FIX
              //class within a class must end in semicolon
    //NEED TO MAKE CALCULATE BUTTON USE THESE
    //FUNCTION: CONVERT BINARY TO...     
         private static void convertBinary(){
              while (true){  //OPEN WHILE
                   String intSelection;
                   Scanner keyboard = new Scanner(System.in);
                   intSelection = keyboard.nextLine();
                   //ERROR CHECKING FOR BINARY.. TOO LARGE IS GOOD!!!
                   String maximum = "1111111111111111111111111111111";
                   String emptybinary = "";
                   if (intSelection.length() > 31){          
                        txtFieldFive.setText("The value is too large");     
                   else {
                        if (intSelection.equalsIgnoreCase(emptybinary)){
                             txtFieldFive.setText("No value was entered.");
                        else {
                        int i;
                        i = Integer.parseInt(intSelection,2);
                        txtFieldTwo.setText(Integer.toString(i));     
                        txtFieldThree.setText(Integer.toHexString(i));          
                        txtFieldFour.setText(Integer.toOctalString(i));     
                        break;          
    //FUNCTION: CONVERT DECIMAL TO...     
         private static void convertDecimal(){
              while (true){  //OPEN WHILE
    //     System.out.print("Please enter a Binary value: ");
                   String intSelection;
                   Scanner keyboard = new Scanner(System.in);
                   intSelection = keyboard.nextLine();
                   //ERROR CHECKING FOR INTEGER.. TOO LARGE IS GOOD!!!
                   String maximum = "2147483647";
                   String empty = "";
                   if (intSelection.length() > 10){          
                        txtFieldFive.setText("The value is too large");               
                   else {
                        if (intSelection.equalsIgnoreCase(empty)){
                             txtFieldFive.setText("No value was entered.");
                        }     else {
                             int i;
                             i = Integer.parseInt(intSelection,10);
                             txtFieldOne.setText(Integer.toBinaryString(i));     
                             txtFieldThree.setText(Integer.toHexString(i));          
                             txtFieldFour.setText(Integer.toOctalString(i));
                             break;          
    //CLOSE MY MAIN CLASS public "class cis279hw3_new"

    Thank you for the reply. I will try and get this better this time - newbie to programming and this forum.
    Here is the area of code I am having problems with...
    - I get no compiler errors...
    - But when I run the program... the GUI sort of hangs or stalls... and doesn't do anything when I:
    Choose the binary radio button
    enter a binary number into the txtFieldOne
    click Calculate...once I click calculate button... the program GUI locks up and hangs... but I get no errors or error messages I can see.
    On calculate... it is supposed to run the convertBinary( ) method... which
    converts the binary to a decimal, a hex and an octal.
    then display, or setText of each conversion into its appropriate textField...
    I have also simply setText on calculate.. to ensure the button even works... and it does work...
    if (radioBinary.isSelected() == true)
    txtFieldOne.setText("This happens when I click calculate");     ------------------
    //CALCULATE BUTTON FUNCTION AND EXECUTIONS
              private class CalculateButtonHandler implements ActionListener{
                   public void actionPerformed(ActionEvent e){ //ActionEvent Class used here     
                        if (radioBinary.isSelected() == true)
                        convertBinary(); //NEED TO FIX
    //FUNCTION: CONVERT BINARY TO...     
         private void convertBinary(){
              while (true){  //OPEN WHILE
                   String intSelection;
                   Scanner keyboard = new Scanner(System.in);
                   intSelection = keyboard.nextLine();
                   //ERROR CHECKING FOR BINARY.. TOO LARGE IS GOOD!!!
                   String maximum = "1111111111111111111111111111111";
                   String emptybinary = "";
                   if (intSelection.length() > 31){          
                        txtFieldFive.setText("The value is too large");     
                   else {
                        if (intSelection.equalsIgnoreCase(emptybinary)){
                             txtFieldFive.setText("No value was entered.");
                        else {
                        int i;
                        i = Integer.parseInt(intSelection,2);
                        txtFieldTwo.setText(Integer.toString(i));     
                        txtFieldThree.setText(Integer.toHexString(i));          
                        txtFieldFour.setText(Integer.toOctalString(i));     
                        break;          
         }

  • Help with GUI program

    Writing a program that uses menu options of ADD, SUBTRACT, MULTIPLY, and DIVIDE.
    The user enters a number in a field labeled "Number 1" then enters a number in a field labeled "Number 2". The final field is labeled "Result"
    Each of the menu options has an ActionEvent.
    I'm having trouble with how to get the fields for Number 1 and Number 2 to display in the Result field when the user selects one of the menu options.
    Here is the code with an ActionEvent started for "Add" but not finished since I neeed some advice from this point on....
    Please disregard the other menu options, at this point I am just working on the math portion...
    Cheers!
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Brown7 extends JFrame implements ActionListener
    public static final int WIDTH = 400;
    public static final int HEIGHT = 200;
    private JTextField inputField, inputsecondField, resultField;
    private double sum = 0;
    private double difference = 0;
    private double product = 0;
    private double quotient = 0;
    public Brown7()
    setSize (WIDTH, HEIGHT);
    addWindowListener(new WindowDestroyer());
    setTitle ("Menu Demo");
    Container contentPane = getContentPane();
    contentPane.setLayout(new BorderLayout());
    JPanel buttonPanel = new JPanel();
    buttonPanel.setLayout(new FlowLayout());
    JButton sumbutton = new JButton("Add");
    sumbutton.addActionListener(this);
    buttonPanel.add(sumbutton);
    JButton subbutton = new JButton("Subtraction");
    subbutton.addActionListener(this);
    buttonPanel.add(subbutton);
    JButton multbutton = new JButton("Multiply");
    multbutton.addActionListener(this);
    buttonPanel.add(multbutton);
    JButton divbutton = new JButton("Divide");
    divbutton.addActionListener(this);
    buttonPanel.add(divbutton);
    contentPane.add(buttonPanel, BorderLayout.SOUTH);
    JPanel infoPanel = new JPanel();
    infoPanel.setLayout(new FlowLayout());
    JLabel nameLabel = new JLabel("Number 1");
    infoPanel.add(nameLabel);
    inputField = new JTextField("", 3);
    infoPanel.add(inputField);
    JLabel secondnameLabel = new JLabel("Number 2");
    infoPanel.add(secondnameLabel);
    inputsecondField = new JTextField("", 3);
    infoPanel.add(inputsecondField);
    JLabel resultLabel = new JLabel("Result");
    infoPanel.add(resultLabel);
    resultField = new JTextField("", 5);
    infoPanel.add(resultField);
    contentPane.add(infoPanel);
    JMenuBar mBar = new JMenuBar();
    setJMenuBar(mBar);
    JMenu operationsMenu = new JMenu("Operations");
    mBar.add(operationsMenu);
    JMenuItem o;
    o = new JMenuItem("Add");
    o.addActionListener(this);
    operationsMenu.add(o);
    o = new JMenuItem("Subtract");
    o.addActionListener(this);
    operationsMenu.add(o);
    o = new JMenuItem("Multiply");
    o.addActionListener(this);
    operationsMenu.add(o);
    o = new JMenuItem("Divide");
    o.addActionListener(this);
    operationsMenu.add(o);
    JMenu viewMenu = new JMenu("View");
    mBar.add(viewMenu);
    JMenuItem v;
    v = new JMenuItem("Metal");
    v.addActionListener(this);
    viewMenu.add(v);
    v = new JMenuItem("Motif");
    v.addActionListener(this);
    viewMenu.add(v);
    v = new JMenuItem("Windows");
    v.addActionListener(this);
    viewMenu.add(v);
    JMenu exitMenu = new JMenu("Exit");
    mBar.add(exitMenu);
    JMenuItem e;
    e = new JMenuItem("Close");
    e.addActionListener(this);
    exitMenu.add(e);
    public void actionPerformed(ActionEvent e)
    if (e.getActionCommand().equals("Close"))
    System.exit(0);
    else if (e.getActionCommand().equals("Add"))
    else
    System.out.println("Error in Brown7 interface.");
    public static void main(String[] args)
    Brown7 gui = new Brown7();
    gui.setVisible(true);

    You can use a JOptionPane for the textfield input. Here I used a DocumentFilter (new in JDK1.4). It allows only specified characters to be entered and beeps for illegal characters. If you still want a message dialog you can add it in the document filter class with (or in place of) the Toolkit..beep call.
    I also changed the variable result to a double and added a NumberFormat to allow formatting to only one decimal place for fractions (as a result of division) in resultField.
    I gave a choice of YES_NO vs. YES_NO_CANCEL options in the exit dialog.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.text.NumberFormat;    // new
    import javax.swing.text.*;        // new
    public class BrownTest extends JFrame implements ActionListener
        public static final int WIDTH = 400;
        public static final int HEIGHT = 200;
        private JTextField inputField, inputsecondField, resultField;
        private double sum = 0;
        private double difference = 0;
        private double product = 0;
        private double quotient = 0;
        NumberFormat nf;
        JFrame frame = this;
        public BrownTest()
            nf = NumberFormat.getInstance();
            nf.setMaximumFractionDigits(1);
            setSize (WIDTH, HEIGHT);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            setTitle ("Menu Demo");
            Container contentPane = getContentPane();
            contentPane.setLayout(new BorderLayout());
            JPanel buttonPanel = new JPanel();
            buttonPanel.setLayout(new FlowLayout());
            JButton sumbutton = new JButton("Add");
            sumbutton.addActionListener(this);
            buttonPanel.add(sumbutton);
            JButton subbutton = new JButton("Subtract");
            subbutton.addActionListener(this);
            buttonPanel.add(subbutton);
            JButton multbutton = new JButton("Multiply");
            multbutton.addActionListener(this);
            buttonPanel.add(multbutton);
            JButton divbutton = new JButton("Divide");
            divbutton.addActionListener(this);
            buttonPanel.add(divbutton);
            contentPane.add(buttonPanel, BorderLayout.SOUTH);
            JPanel infoPanel = new JPanel();
            infoPanel.setLayout(new FlowLayout());
            JLabel nameLabel = new JLabel("Number 1");
            infoPanel.add(nameLabel);
            inputField = new JTextField("", 3);
            infoPanel.add(inputField);
            JLabel secondnameLabel = new JLabel("Number 2");
            infoPanel.add(secondnameLabel);
            inputsecondField = new JTextField("", 3);
            infoPanel.add(inputsecondField);
            JLabel resultLabel = new JLabel("Result");
            infoPanel.add(resultLabel);
            resultField = new JTextField("", 5);
            infoPanel.add(resultField);
            // set document filter on textfield documents
            String integerDomain = "-.0123456789";
            FieldNumberFilter filter = new FieldNumberFilter(integerDomain);
            AbstractDocument doc = (AbstractDocument)inputField.getDocument();
            doc.setDocumentFilter(filter);
            doc = (AbstractDocument)inputsecondField.getDocument();
            doc.setDocumentFilter(filter);
            doc = (AbstractDocument)resultField.getDocument();
            doc.setDocumentFilter(filter);
            contentPane.add(infoPanel);
            JMenuBar mBar = new JMenuBar();
            setJMenuBar(mBar);
            JMenu operationsMenu = new JMenu("Operations");
            mBar.add(operationsMenu);
            JMenuItem o;
            o = new JMenuItem("Add");
            o.addActionListener(this);
            operationsMenu.add(o);
            o = new JMenuItem("Subtract");
            o.addActionListener(this);
            operationsMenu.add(o);
            o = new JMenuItem("Multiply");
            o.addActionListener(this);
            operationsMenu.add(o);
            o = new JMenuItem("Divide");
            o.addActionListener(this);
            operationsMenu.add(o);
            JMenu viewMenu = new JMenu("View");
            mBar.add(viewMenu);
            ViewMenuListener viewMenuListener = new ViewMenuListener();
            JMenuItem v;
            v = new JMenuItem("Metal");
            v.addActionListener(viewMenuListener);
            viewMenu.add(v);
            v = new JMenuItem("Motif");
            v.addActionListener(viewMenuListener);
            viewMenu.add(v);
            v = new JMenuItem("Windows");
            v.addActionListener(viewMenuListener);
            viewMenu.add(v);
            JMenu exitMenu = new JMenu("Exit");
            mBar.add(exitMenu);
            JMenuItem e;
            e = new JMenuItem("Close");
            e.addActionListener(this);
            exitMenu.add(e);
         * Listener for the Operations and Close menu items
        public void actionPerformed(ActionEvent e)
            String ac = e.getActionCommand();
            if (ac.equals("Close"))
                String message = "Are you sure you want to exit this program?";
                int returnVal = JOptionPane.showConfirmDialog(frame,
                                                              message,
                                                              "Exit Dialog",
                // either this */                             JOptionPane.YES_NO_OPTION,
                /* or this */                                 JOptionPane.YES_NO_CANCEL_OPTION,
                                                              JOptionPane.QUESTION_MESSAGE);
                if(returnVal == JOptionPane.CANCEL_OPTION ||
                   returnVal == JOptionPane.CLOSED_OPTION)
                    return;
                if(returnVal == JOptionPane.YES_OPTION)
                    System.exit(0);
                if(returnVal == JOptionPane.NO_OPTION);
                    frame.dispose();
            // read entered data
            String one = inputField.getText();
            String two = inputsecondField.getText();
            // if no entry, return
            if(one.equals("") || two.equals(""))
                return;
            // attempt to parse data
            double first, second;
            try
                first  = Double.parseDouble(one);
                second = Double.parseDouble(two);
            catch(NumberFormatException nfe)
                System.out.println(nfe.getMessage());
                return;
            // now we have good data, do calculations
            double result = 0;
            if (ac.equals("Add"))
                result = first + second;
            else if(ac.equals("Subtract"))
                result = first - second;
            else if(ac.equals("Multiply"))
                result = first * second;
            else if(ac.equals("Divide"))
                result = first / second;
            else
                System.out.println("Error in Brown7 interface.");
            resultField.setText(nf.format(result));
         * Listener for the View menu items
        private class ViewMenuListener implements ActionListener
            UIManager.LookAndFeelInfo[] info = UIManager.getInstalledLookAndFeels();
            public void actionPerformed(ActionEvent e)
                JMenuItem item = (JMenuItem)e.getSource();
                String ac = item.getActionCommand();
                String name = null;
                for(int i = 0; i < info.length; i++)
                    if(info.getName().indexOf(ac) != -1)
    name = info[i].getClassName();
    if(name == null)
    return;
    try
    UIManager.setLookAndFeel(name);
    catch(ClassNotFoundException cnfe)
    System.out.println(cnfe.getMessage());
    catch(InstantiationException ie)
    System.out.println(ie.getMessage());
    catch(IllegalAccessException iae)
    System.out.println(iae.getMessage());
    catch(UnsupportedLookAndFeelException ulafe)
    System.out.println(ulafe.getMessage());
    SwingUtilities.updateComponentTreeUI(BrownTest.this);
    public static void main(String[] args)
    BrownTest gui = new BrownTest();
    gui.setVisible(true);
    * Document filter for input validation in textfields
    class FieldNumberFilter extends DocumentFilter
    String allowables;
    public FieldNumberFilter(String legalCharacters) {
    allowables = legalCharacters;
    public void insertString(DocumentFilter.FilterBypass fb,
    int offset,
    String str,
    AttributeSet attr) throws BadLocationException {
    replace(fb, offset, 0, str, attr);
    public void replace(DocumentFilter.FilterBypass fb,
    int offset,
    int length,
    String str,
    AttributeSet attrs) throws BadLocationException {
    char[] source = str.toCharArray();
    char[] result = new char[source.length];
    int j = 0;
    for(int i = 0; i < result.length; i++)
    if(allowables.indexOf(source[i]) != -1)
    result[j++] = source[i];
    else
    Toolkit.getDefaultToolkit().beep();
    fb.replace(offset, length, new String(result, 0, j), attrs);

  • Displaying a native Windows GUI program in a JFrame

    Hello,
    I am working on a troubleshooting program that will bring up a control panel applet along with my own JFrame containing instructions on what to do for a certain topic. In order to avoid one window overlapping another, I want to be able to control where both windows appear. One possibility I have thought of is to execute the control panel applet so it appears within the same JFrame or a different JFrame, and then I could control the position of that.
    I am using Runtime.exec to execute the control panel applet from the command prompt. Simply adding the Process that this function returns to the contentPane (Container for my JFrame) does not work because Process is in a different class hierarchy from Container.
    I was wondering if anyone knew either how to do what I just mentioned or how to control the position of a windows gui app that i execute from the command prompt. Any information that at least pointed me in the right direction would be very helpful. Thanks.

    Just to be clear...
    You have two seperate processes (two JVMs.)
    If so "class hierarchy" is meaningless because there is no interaction between the two JVMs that you do not explicitly provide.
    So you have several choices.
    First you can delve deep into the internals of windows and figure out how to determine where the various windows appear on the screen. Unless you are already an expert in the windows API this is going to take a lot of research.
    Second you can simply send use a communication medium (like sockets) to let each application tell the other app where it is. I believe the java api allows you some information on the screen position. If not then you will have to again delve into the windows internals.
    Three when both applications are running then only one application has a gui. The other application uses a communication medium (like a socket) to send relevant info to the other app. And the other app manages both GUIs.

  • Java gui program won't compile.

    The error I am getting in my compiler is missing return statement, then ill add some braces and get a class, interface, or enum expected error, and sometimes when i add some ill end up getting a reached the end without parcing error. Can someone look at this code and tell me what I need to do to make it compile, I am pretty sure it is just a brace thing, but I have run out of ideas:
    here is the code:
    public class Lab14 implements ActionListener
    // Application variables
    private JFrame myFrame;
    private JTextField txtInput;
    private JButton cmdRun;
    private JButton cmdExit;
    private JTextArea txaOutput;
    private static Random rand = new Random();
    private double trials;
    * Schedule a job for the event-dispatching thread
    * to create and show this application's GUI.
    * @param args program arguments
    public static void main(String[] args)
    javax.swing.SwingUtilities.invokeLater(new Runnable()
    public void run()
    Lab14 myLab14 = new Lab14();
    myLab14.createAndShowGUI();
    * Create and show the graphical user interface.
    private void createAndShowGUI()
    Container myPane;
    txtInput = new JTextField(10);
    cmdRun = new JButton("Run");
    cmdRun.addActionListener(this);
    cmdExit = new JButton("Quit");
    cmdExit.addActionListener(this);
    txaOutput = new JTextArea(35, 40);
    txaOutput.setEditable(false);
    // Set up and show the application frame
    myFrame = new JFrame("Lab14");
    myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    myPane = myFrame.getContentPane();
    myPane.setLayout(new FlowLayout());
    myPane.add(new JLabel("Number of Trials"));
    myPane.add(txtInput);
    myPane.add(cmdRun);
    myPane.add(cmdExit);
    myPane.add(txaOutput);
    myFrame.pack();
    myFrame.setVisible(true);
    txtInput.requestFocus();
    * Enable user interaction.
    * @param ae the specified action event
    public void actionPerformed(ActionEvent ae)
    String number;
    String report;
    int dotSum = 0;
    int count = 0;
    int freq = 0;
    int prob = 0;
    Object source = ae.getSource();
    if (source.equals(cmdRun))
    try
    number = txtInput.getText();
    trials = Double.parseDouble(number);
    if (trials <= 0)
    throw new Exception(
    "The number of trials must be positive.");
    else
    while (count < trials)
    dotSum = dotSum + rand.nextInt(6) + 1;
    count++;
    txaOutput.setText(
    getReport(dotSum, freq, prob));
    catch (NumberFormatException nfe)
    txtInput.selectAll();
    txtInput.requestFocus();
    JOptionPane.showMessageDialog(
    myFrame,
    "The number of trials is not a number.",
    "Number Format Error",
    JOptionPane.ERROR_MESSAGE);
    catch (Exception e)
    txtInput.selectAll();
    txtInput.requestFocus();
    JOptionPane.showMessageDialog(
    myFrame,
    e.getMessage(),
    "Number Format Error",
    JOptionPane.ERROR_MESSAGE);
    else
    System.exit(0);
    * Get the report for the specified dot sum, frequency,
    * and probability. The output shows the results from
    * rolling the dice a selected number of trials.
    * @param dotSum the sum of the dots
    * @param frequency the frequency of the dice
    * @param probability the probability of rolling a specified amount
    * @return the report
    private String getReport(int dotSum,
    int freq,
    int prob)
    int count;
    int freq0;
    int freq1;
    int freq2;
    int freq3;
    int freq4;
    int freq5;
    int freq6;
    int freq7;
    int freq8;
    int freq9;
    int freq10;
    double prob0;
    double prob1;
    double prob2;
    double prob3;
    double prob4;
    double prob5;
    double prob6;
    double prob7;
    double prob8;
    double prob9;
    double prob10;
    String report;
    int numDice = 2;
    while (trials != 0)
    Dice myDice = new Dice(numDice);
    freq0 = 0;
    freq1 = 0;
    freq2 = 0;
    freq3 = 0;
    freq4 = 0;
    freq5 = 0;
    freq6 = 0;
    freq7 = 0;
    freq8 = 0;
    freq9 = 0;
    freq10 = 0;
    for (count = 0; count < trials; count++)
    switch (myDice.getDotSum())
    case 2: freq0++;
    break;
    case 3: freq1++;
    break;
    case 4: freq2++;
    break;
    case 5: freq3++;
    break;
    case 6: freq4++;
    break;
    case 7: freq5++;
    break;
    case 8: freq6++;
    break;
    case 9: freq7++;
    break;
    case 10: freq8++;
    break;
    case 11: freq9++;
    break;
    case 12: freq10++;
    prob0 = (double)freq0/(double)trials;
    prob1 = (double)freq1/(double)trials;
    prob2 = (double)freq2/(double)trials;
    prob3 = (double)freq3/(double)trials;
    prob4 = (double)freq4/(double)trials;
    prob5 = (double)freq5/(double)trials;
    prob6 = (double)freq6/(double)trials;
    prob7 = (double)freq7/(double)trials;
    prob8 = (double)freq8/(double)trials;
    prob9 = (double)freq9/(double)trials;
    prob10 = (double)freq10/(double)trials;
    double freqSum = freq0 + freq1 + freq2 + freq3 + freq4 +
    freq5 + freq6 + freq7 + freq8 + freq9 + freq10;
    double probSum = prob0 + prob1 + prob2 + prob3 + prob4 +
    prob5 + prob6 + prob7 + prob8 + prob9 + prob10;
    return
    String.format("%7s %9s %11s%n", "Dot Sum", "Frequency", "Probability")+
    String.format("%7s %9s %11s%n", "-------", "---------", "-----------")+
    String.format(" 2 %9d", freq0)+
    String.format(" %11.3f%n", prob0)+
    String.format(" 3 %9d", freq1)+
    String.format(" %11.3f%n", prob1)+
    String.format(" 4 %9d", freq2)+
    String.format(" %11.3f%n", prob2)+
    String.format(" 5 %9d", freq3)+
    String.format(" %11.3f%n", prob3)+
    String.format(" 6 %9d", freq4)+
    String.format(" %11.3f%n", prob4)+
    String.format(" 7 %9d", freq5)+
    String.format(" %11.3f%n", prob5)+
    String.format(" 8 %9d", freq6)+
    String.format(" %11.3f%n", prob6)+
    String.format(" 9 %9d", freq7)+
    String.format(" %11.3f%n", prob7)+
    String.format(" 10 %9d", freq8)+
    String.format(" %11.3f%n", prob8)+
    String.format(" 11 %9d", freq9)+
    String.format(" %11.3f%n", prob9)+
    String.format(" 12 %9d", freq10)+
    String.format(" %11.3f%n", prob10)+
    String.format("%7s %9s %11s%n", "-------", "---------", "-----------")+
    String.format("%18d", freqSum)+
    String.format("%13.3f%n", probSum);
    }

    border9 wrote:
    yes, but i wrote the bottom part of the code a while ago before I did know what an array list was, so I figured it would be easier just to paste that rather than make new code.Sounds to me like you're the type who just throws code at a wall hoping some of it will stick.
    You're not trying hard enough. Just posting your code here (and unformatted, to boot!) and saying "fix this for me" isn't going to cut it. This is not rent-a-coder.

Maybe you are looking for

  • How can I delete all the duplicate photos I have in iPhoto?  There are hundreds.....

    Can anyone help me?  I have noticed a large number of duplicate photos appearing in my iPhoto.... probably after we have connected several iOS devices that are synced.  Is there a way for iPhoto to identify all these?  If not, is there a third party

  • Direct link to specific page in page flip swf?

    This may have an easy answer, but is there a way to link directly to a specific page in a page-flip swf via direct link from another site/web page/etc.? If my page flip swf is on myzines.com/2010-08-01.html ... Is there a way to link from any other w

  • Music and videos start playing fine but randomly stop and the volume bar disappears

    I have an iPhone 4S and run 6.1.3.  I start to play music or videos (youtube, ESPN, Netflix, any) and they start to play fine but then randomly stop.  The volume bar disappears as well.  But then it reappears and I can play it again.  When I do so it

  • Additional tags in Multi Maping

    Hi all, We are using multimapping 1:n to send separate soap messages for each call to soap receiver. we found there are additional tass (Message 1, Message 2...) after multimapping in the targer structure, which we are passing to soap. message with t

  • Closing programs

    How can I close programs that I have used? The double-klick home button does not work any more as with IOS6.