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.

Similar Messages

  • Suddenly, my java programs won't compile : Class not found error

    Hello, the strangest things happened on my win xp pro computer...
    My java-files wo'nt compile anymore. The compiler (javac) is complaning about classes he can't find. But these classes are in the same directory....
    Can anyone help me?

    generally female version are more complaining then the male versions!!
    if the male version is complaining then it must be something wrong in your path or classpath!!
    1) have you tried before to complie? and it has been complied successfully in past?
    2) check out your classpath.. is it containing "." ( a dot)? if not then just put a ".;" in starting of your classpath & start compiling your code in new command prompt...
    hope now your compiler will not complain... :)

  • Program won't compile!!! - HELP!!!!!

    Here's the COMPLETE code:
    import javax.swing.*;
    import java.io.*;
    import java.util.*;
    public final class QABugTracker extends JFrame {
          public QABugTracker() {
               initComponents();
               pack();
         // Variable & component declarations
        private javax.swing.JMenuBar menuBar;
        private javax.swing.JMenu fileMenu;
        private javax.swing.JMenuItem openMenuItem;
        private javax.swing.JMenuItem saveMenuItem;
        private javax.swing.JMenuItem saveAsMenuItem;
        private javax.swing.JMenuItem exitMenuItem;
        private javax.swing.JMenu editMenu;
        private javax.swing.JMenuItem cutMenuItem;
        private javax.swing.JMenuItem copyMenuItem;
        private javax.swing.JMenuItem pasteMenuItem;
        private javax.swing.JMenuItem deleteMenuItem;
        private javax.swing.JMenu helpMenu;
        private javax.swing.JMenuItem contentMenuItem;
        private javax.swing.JMenuItem aboutMenuItem;
        private javax.swing.JDesktopPane desktopPane;
        private javax.swing.JInternalFrame jInternalFrame1;
        private javax.swing.JTabbedPane jTabbedPane1;
        private javax.swing.JScrollPane currentScrollPane;
        private javax.swing.JTable Current;
        private javax.swing.JScrollPane resolvedScrollPane;
          private javax.swing.JTable Resolved;
        private javax.swing.JScrollPane knownScrollPane;
          private javax.swing.JTable Known;
         private void initComponents() { // Instantiate all major components
                // GUI components
                menuBar = new javax.swing.JMenuBar();
            fileMenu = new javax.swing.JMenu();
            openMenuItem = new javax.swing.JMenuItem();
            saveMenuItem = new javax.swing.JMenuItem();
            saveAsMenuItem = new javax.swing.JMenuItem();
            exitMenuItem = new javax.swing.JMenuItem();
            editMenu = new javax.swing.JMenu();
            cutMenuItem = new javax.swing.JMenuItem();
            copyMenuItem = new javax.swing.JMenuItem();
            pasteMenuItem = new javax.swing.JMenuItem();
            deleteMenuItem = new javax.swing.JMenuItem();
            helpMenu = new javax.swing.JMenu();
            contentMenuItem = new javax.swing.JMenuItem();
            aboutMenuItem = new javax.swing.JMenuItem();
            desktopPane = new javax.swing.JDesktopPane();
            jInternalFrame1 = new javax.swing.JInternalFrame();
            jInternalFrame1.setVisible(true);
            jTabbedPane1 = new javax.swing.JTabbedPane();
            currentScrollPane = new javax.swing.JScrollPane();
            Current = new javax.swing.JTable();
            resolvedScrollPane = new javax.swing.JScrollPane();
                Resolved = new javax.swing.JTable();
            knownScrollPane = new javax.swing.JScrollPane();
                Known = new javax.swing.JTable();
                fileMenu.setText("Main"); // Add 'Main' menu & contents to menuBar
                          openMenuItem.setText("Maunual Refresh");
                        fileMenu.add(openMenuItem);
                        saveMenuItem.setText("Login");
                        fileMenu.add(saveMenuItem);
                        saveAsMenuItem.setText("Local Save");
                        fileMenu.add(saveAsMenuItem);
                        exitMenuItem.setText("Exit");
                             exitMenuItem.addActionListener(new java.awt.event.ActionListener() {
                                  public void actionPerformed(java.awt.event.ActionEvent evt) {
                                       exitMenuItemActionPerformed(evt);
                                       } // End actionPerformed function
                                  } // Encapsulate actionPerformed as 'param' for new ActionListner
                             ); // Added Listener to exitMenuItem to detect click & close application
                        fileMenu.add(exitMenuItem);
                        menuBar.add(fileMenu); // Add fileMenu to the main menuBar
              editMenu.setText("Options"); // Add 'Options' menu & contents to menuBar
                        cutMenuItem.setText("Cut");
                        editMenu.add(cutMenuItem);
                        copyMenuItem.setText("Copy");
                        editMenu.add(copyMenuItem);
                        pasteMenuItem.setText("Paste");
                        editMenu.add(pasteMenuItem);
                        deleteMenuItem.setText("Delete");
                        editMenu.add(deleteMenuItem);
                        menuBar.add(editMenu);
              helpMenu.setText("Help"); // Add 'Help' menu & contents to menuBar
                        contentMenuItem.setText("Contents");
                        helpMenu.add(contentMenuItem);
                        aboutMenuItem.setText("About");
                        helpMenu.add(aboutMenuItem);
                        menuBar.add(helpMenu);
              // Simple tweaks to main JFrame
              setTitle("QA Bug Tracker"); // Set the Title at top of JFrame
              setForeground(java.awt.Color.white);
              setBackground(java.awt.Color.black);
              addWindowListener(new java.awt.event.WindowAdapter() {
                   public void windowClosing(java.awt.event.WindowEvent evt) {
                        exitForm(evt);
                        } // End of windowClosing method
                   } // Encapsulate windowClosing as 'param' for new WindowListner
              ); // Added WindowListner to be able to close the Jframe
              // Starting on the JFrame's primary components
              desktopPane.setSelectedFrame(jInternalFrame1);
              desktopPane.setPreferredSize(new java.awt.Dimension(300, 200));
                   jInternalFrame1.getContentPane().setLayout(new java.awt.BorderLayout());
                   jInternalFrame1.setMaximizable(true);
                   jInternalFrame1.setDoubleBuffered(true);
                   jInternalFrame1.setTitle("Tracking List");
                   jInternalFrame1.setIconifiable(true);
                   jInternalFrame1.setResizable(true);
                        // Start on the internal frame's contents
                        jTabbedPane1.setDoubleBuffered(true);
                        jTabbedPane1.setForeground(java.awt.Color.white);
                        jTabbedPane1.setBackground(java.awt.Color.black);
                                  // Set options for first Tab (the 'Present' JTable with scrollpane
                                  currentScrollPane.setName("Present");
                                  currentScrollPane.setDoubleBuffered(true);
                                  currentScrollPane.setColumnHeader(currentScrollPane.getColumnHeader());
                                  currentScrollPane.setBackground(java.awt.Color.black);
                                  currentScrollPane.setOpaque(false);
                                  // Start setting up the 'Present' JTable
                                  Current.setEditingColumn(1);
                                  Current.setTableHeader(Current.getTableHeader());
                                  Current.setSelectionForeground(java.awt.Color.white);
                                  Current.setDoubleBuffered(true);
                                  Current.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
                                  Current.setModel(new javax.swing.table.DefaultTableModel (
                                       new Object [][] {
                                            {null, null, null, null, null, null, null, null},
                                            {null, null, null, null, null, null, null, null},
                                            {null, null, null, null, null, null, null, null},
                                            {null, null, null, null, null, null, null, null},
                                            {null, null, null, null, null, null, null, null},
                                            {null, null, null, null, null, null, null, null},
                                            {null, null, null, null, null, null, null, null},
                                            {null, null, null, null, null, null, null, null},
                                            {null, null, null, null, null, null, null, null},
                                            {null, null, null, null, null, null, null, null},
                                            {null, null, null, null, null, null, null, null}
                                       new String [] {
                                            "Software Package", "Issue Reported", "Reported By", "Date Reported", "QA Rep. Assigned", "Date Assigned", "Status", "Date Due"
                                       )); // Created TableModel for 'Current' JTable
                                  Current.setName("Current");
                                  Current.setEditingRow(1);
                                  currentScrollPane.setViewportView(Current);
                                  jTabbedPane1.addTab("Current", currentScrollPane);
                                  resolvedScrollPane.setName("Resolved");
                                  resolvedScrollPane.setDoubleBuffered(true);
                                  jTabbedPane1.addTab("Resolved", resolvedScrollPane);
                                  knownScrollPane.setName("Known");
                                  knownScrollPane.setDoubleBuffered(true);
                                  jTabbedPane1.addTab("Known", knownScrollPane);
                                  // Add the TabbedPane to the Center of Internal Frame - then Internal Frame to JDesktop
                                  jInternalFrame1.getContentPane().add(jTabbedPane1, java.awt.BorderLayout.CENTER);
                                  desktopPane.add(jInternalFrame1, javax.swing.JLayeredPane.DEFAULT_LAYER);
                                  jInternalFrame1.setBounds(8, 3, 234, 154);
                                  // Add the JDesktopPane to the Center portion of the main JFrame
                                  getContentPane().add(desktopPane, java.awt.BorderLayout.CENTER);
                                  // Set the JMenuBar for the main JFrame
                                  setJMenuBar(menuBar);
              } // End of initComponents
              private void exitMenuItemActionPerformed (java.awt.event.ActionEvent evt) {
                   System.exit (0);
              /** Exit the Application */
              private void exitForm(java.awt.event.WindowEvent evt) {
                   System.exit (0);
         public static void main (String args[]) {
              new OABugTracker ().show ();
    }*** End of Program ***
    Now the error I get is this:
    C:\jipe0.93\QABugTracker.java:204: can't resolve symbol
    symbol : class QABugTracker
    location : class QABugTracker
    new QABugTracker().show();
    ^

    Hi there is a typo in the main()
    you have used
    new OABugTracker ().show();
    Where the class name is QABugTacker Try changing this code, I tried it it works fine
    QABugTracker x =new QABugTracker ();
    x.show();

  • Java.sun example won't compile

    hello..
    I've just succefully installed the JDK and am trying a few things ou to ensure it works, which as yet it doesn't.
    I'm using VIDE for the time being for my IDE
    and try to compile this.... which has been taken straight out of the tutorial pages
    //v 1.3
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class SwingApplication {
    private static String labelPrefix = "Number of button clicks: ";
    private int numClicks = 0;
    public Component createComponents() {
    final JLabel label = new JLabel(labelPrefix + "0 ");
    JButton button = new JButton("I'm a Swing button!");
    button.setMnemonic(KeyEvent.VK_I);
    button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    numClicks++;
    label.setText(labelPrefix + numClicks);
    label.setLabelFor(button);
    * An easy way to put space between a top-level container
    * and its contents is to put the contents in a JPanel
    * that has an "empty" border.
    JPanel pane = new JPanel();
    pane.setBorder(BorderFactory.createEmptyBorder(
    30, //top
    30, //left
    10, //bottom
    30) //right
    pane.setLayout(new GridLayout(0, 1));
    pane.add(button);
    pane.add(label);
    return pane;
    public static void main(String[] args) {
    try {
    UIManager.setLookAndFeel(
    UIManager.getCrossPlatformLookAndFeelClassName());
    } catch (Exception e) {}
    //Create the top-level container and add contents to it.
    JFrame frame = new JFrame("SwingApplication");
    SwingApplication app = new SwingApplication();
    Component contents = app.createComponents();
    frame.getContentPane().add(contents, BorderLayout.CENTER);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
    the following errors occur, there are four and they all reffer to a swing component.
    Type JLabel not found in the declaration of the local variable 'label'.
    final JLabel label = new JLabel(labelPrefix + "0 ");
    and there's a hat under the very first 'J'. Ditto for JFrame JButton and JPanel
    Really confussed on this one everything seems to be in place the CLASSPATH is pointing to the lib directory where Javax et all are...
    Cheers
    A

    well...
    I'm using linix rehat 8 and my 'path' variable is set up the same as the installation instructions on a post close to this one... it is..
    "PATH=/usr/local/bin:/usr/bin:/bin:/usr/X11R6/bin:/usr/X11R6/bin:/usr/local/vnc:/var/www:/home/software:/usr/java/j2sdk1.4.1_01/bin:/var/home/adam/bin"
    I'm new to unix and so am still a little confused.. This is the path to the executables and not the library files such as javax.swing, correct?? I have also ditched the IDE and running from the command promt. I am trying again this morning and am geting an extra error apparently.....
    " Can't find default package `javax.swing'. Check the CLASSPATH environment variable and the access to the archives"
    could someone explain what CLASSPATH is please as I thought it was only applicable to Windows. The javax package has been unpacked.
    Cheers
    Adam

  • Is it possible to have one java GUI program run  from another Java program

    If it is possible let me know and if you could write some code that would be greatly appreciated.
    Frank

    hm ... what will happen, if one of these applications
    invoke System.exit(...)?- The JVM starts its shut down
    sequence and both applications will shut down this
    way.You're right. If you don't want that - or you can't rely on the behaviour of the second app - you have to start another VM in a separate process calling Runtime.exec().
    If you only want to "use" the second app from the first one (and you have the sources) you can write a method like main() which do not call System.exit() at the end.
    Alex

  • JAVA GUI project

    I want to make a JAVA GUI program, it must do the next things.
    1) Input right answers
    (You have a text file with the right answers. Let's say the following 10 right answers in a text file: answer.txt --->[y?nyyyyn??]---> ?= you don't no the answer
    2) Input right answers of the student's.
    Example
    20026830 [nyn?nynnyn]
    20029321 [nn???yyyny]
    3) View the results.
    Per student you get the result of how many question's where right, wrong, ?=(didn't no)
    Who can help me.....!!!
    Greetings,
    Ronnie

    ...perhaps this will help you a bit:
    http://forum.java.sun.com/thread.jsp?forum=54&thread=338071&tstart=100&trange=100

  • How to Compile & Deploy the Java Concurrent Program File

    Hi,
    There is a requirement to create the Java Concurrent Program in Oracle eBusiness. I am able to create the Java Concurrent Program file. But unable to do the following things:
    1.Since it is custom file, which location I will deploy the file?
    2. How to compile the file?
    3. In the execution file path and executable file name what should I specify for JCP?
    Please guide me.
    Thanks

    Please see (How to register and execute Java Concurrent Program ?in Oracle Applications R11i ? [ID 186301.1]) for the complete steps (i.e. define concurrent program and add it to the request group, .etc.) -- This is also applicable to R12.
    You may also see:
    Classpath Setting of Third Party Jar Files in R12 Java Concurrent Program (JCP) [ID 1292694.1]
    Integrating Custom Applications with Oracle Applications [ID 176852.1]
    Java Concurrent Program FAQ [ID 827575.1]
    https://forums.oracle.com/forums/search.jspa?threadID=&q=Java+AND+Concurrent+AND+Program&objID=c3&dateRange=all&userID=&numResults=15&rankBy=10001
    Thanks,
    Hussein

  • How can I run C programs under a Java GUI?

    Hi
    I'm looking for some info on how to run a command line program written in another language behind a Java GUI, any advice greatly appreciated, particularly in how to transfer data between the two.
    Thanks

    Runtime.getRuntime().exec(...)
    Transfering info is more complicated. Maybe write and read status from disk?

  • My accounts program won't run without legacy Java SE6 runtime since I upgraded to OS x Yosemite but I can't download it

    My "Solar" accounts program won't run without "legacy Java SE6 runtime" since I upgraded my iMac desktop to OS x Yosemite but I can't download it, nothing happens when you click on the link to apple support

    Okay, I'm not a Genius, but, I'm smarter than the one I spoke to at the Apple Store.They told me that they couldn't help me with Legacy Java SE6 Runtime. Adobe has the worst support in the industry so don't call them.
    If you have a Time Machine backup, go to one that pre dates your install of Yosemite. Go to the System/Library/Java and drag copy the folder to your internal hard disk. Now you will need the Administrator password. Once copied, drag the old Java folder into your System/Library folder and when asked to replace, click OK. Restart your Mac and you will have use of your software that requires Legacy Java SE6 Runtime.
    I'm totally done with Apple since they are trying to box me into a corner. Have fun kids.

  • My Compiled Program Won't Run

    I am relatively new to Java. I am having a problem with a very simple program I decided would be my first. I am able to compile it but it will not run. Here is the code.
    //A Very Simple Example
    class ExampleProgram {
    public static void main(String args[]){
    System.out.println("I'm a Simple Program");
    It will compile so that I may recieve my .class file but when I use DOS to open it. DOS writes "Exception in thread "main" java.lang.NoClassDefFoundError: Example Program."
    I'm sure this is a runtime error but besides that I have not found anything that will help me fix the problem. I would be greatful for any help.

    Is that the exact error?
    Did you run it as
    java Example Program
    (that's what it looks like)
    try:
    java ExampleProgram
    ~David
    If not, it relates to the 'classpath' issue, well documented, and asked at least 1000 times prior in this forum (see the search engine on the top right corner?)

  • Msg.addRecipient(Message.RecipientType.TO,to) - won't compile in program

    I have had success in one of my servlets using JavaMail. I was able to send an email to my inbox to test it out. I proceeded to create another servlet based on that 1st one, and for reasons I can't explain, the servlet won't compile.
    I get this error.
    cannot resolve symbol :
             variable : RecipientType
             location : java.lang.String
                           msg.setRecipient(Message.RecipientType.TO, to); I get the same error when I switch out setRecipient for addRecipient.
    However, through further testing, I've found that not only does my 1st servlet still compile, but I'm also able to run the code from the 2nd servlet, successfully in a JSP page. This is driving me nuts...how could there be a problem compiling? There's no reason why one servlet compiles (with similar if not almost exactly the same code) and the other won't. Plus this runs fine in a JSP page...what's going on??? I've spent hours on this and I can't figure it out...please help, any input is appreciated.
    Here is the JSP page that runs successfully :
    <%@page import="java.io.*"%>
    <%@page import="java.util.Properties"%>
    <%@page import="javax.mail.*"%>
    <%@page import="javax.mail.Message.RecipientType"%>
    <%@page import="javax.mail.internet.*"%>
    <%@page import="javax.servlet.*"%>
    <%@page import="javax.servlet.http.*"%>
    <%@page import="javax.naming.*"%>
    <%@page import="javax.sql.*"%>
    <%@page import="java.sql.*"%>
    <%                         
               Connection conn = null;
               Statement stmt = null;
               ResultSet rs = null;
                  try {                              
                   Context ctx = new InitialContext();
                         if(ctx == null )
                     throw new Exception("Boom - No Context");
                           DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/myDB");     
                      conn = ds.getConnection();
                      stmt = conn.createStatement();                   
                      //get the POP3 and SMTP property values from db
                            rs = stmt.executeQuery("Select Tech_Support_Email, POP3, SMTP from sitewide_info");                                               
                            String hostemailaddress = "";
                            String POP3 = "";  //mail.smtp.host, this one 1st
                            String SMTP = ""; //smtp.stratos.net, this one 2nd
                            if(rs.next()) {
                               hostemailaddress = rs.getString(1);
                               POP3 = rs.getString(2);
                               SMTP = rs.getString(3);
                  // Specify the SMTP Host
                 Properties props = new Properties();                                           
                  //POP3 = mail.smtp.host & SMTP = smtp.stratos.net - must be in this order
                  props.put(POP3, SMTP);
                  // Create a mail session
                  Session ssn = Session.getDefaultInstance(props, null);
                  ssn.setDebug(true);                                            
                  String subject = "Testing out Email";
                  String body = "hello";
                  //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
                  rs = stmt.executeQuery("Select Customer_Name, Email_Address from customer_profiles where "
                                                           +"Customer_Number=1111");
                             String fromName = "";
                             String fromEmail = "";
                             if(rs.next()) {
                                fromName = rs.getString(1);
                                fromEmail = rs.getString(2);
                  InternetAddress from = new InternetAddress(fromEmail,fromName);                                
                  String toName = "Bob";          
                  InternetAddress to = new InternetAddress(hostemailaddress,toName);             
                      // Create the message
                      Message msg = new MimeMessage(ssn);
                      msg.setFrom(from);
                      msg.addRecipient(Message.RecipientType.TO, to);
                      msg.setSubject(subject);
                      msg.setContent(body, "text/html");
                      Transport.send(msg);             
                  }//try
                   catch (MessagingException mex) {                     
                          mex.printStackTrace(); }
                   catch(Exception e) {}
            finally {         
                try {
                  if (rs!=null) rs.close();
                     catch(SQLException e){}             
                  try {
                  if (stmt!=null) stmt.close();
                     catch(SQLException e){}
                  try {
                  if (conn!=null) conn.close();
                     catch(SQLException e){}
            }//finally          
    %>                           
    Here's the servlet that won't compile :
    package testing.servlets.email;
    import java.io.*;
    import java.util.Properties;
    import javax.mail.*;
    import javax.mail.Message.RecipientType;
    import javax.mail.internet.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import javax.naming.*;
    import javax.sql.*;
    import java.sql.*;
         public class MessageCenterServlet extends HttpServlet {
              public Connection conn = null;
              public Statement stmt = null;
              public Statement stmt2 = null;
              public ResultSet rs = null;
              public ResultSet rss = null;
              public PrintWriter out = null;
              public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
                   doPost(req,res);
              public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
                  try {               
                        out = res.getWriter();
                        Context ctx = new InitialContext();
                         if(ctx == null )
                     throw new Exception("Boom - No Context");
                           DataSource ds =
                     (DataSource)ctx.lookup(
                        "java:comp/env/jdbc/myDB");     
                      conn = ds.getConnection();
                      stmt = conn.createStatement(); 
                      stmt2 = conn.createStatement();                 
                      HttpSession session = req.getSession();                                                             
                         String Subject = (String)session.getAttribute("Subject");
                         String Message = (String)session.getAttribute("Message");
                         sendAnEmail(rs,stmt,Subject,Message,res);                                     
                        }//try
                      catch (Exception e) { }
                      finally { cleanup(rs,rss,stmt,stmt2,conn); }
              }//post       
             public void cleanup(ResultSet r, ResultSet rs, Statement s, Statement s2, Connection c){
                try {
                  if (r!=null) r.close();
                     catch(SQLException e){}
                  try {
                  if (rs!=null) rs.close();
                     catch(SQLException e){}
                  try {
                  if (s!=null) s.close();
                     catch(SQLException e){}
                  try {
                  if (s2!=null) s2.close();
                     catch(SQLException e){}
                  try {
                  if (c!=null) c.close();
                     catch(SQLException e){}
            }//cleanUp          
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~                
            public void sendAnEmail(ResultSet rs, Statement stmt, String Subject,String Message, HttpServletResponse res) {          
                 try {               
                      //get the POP3 and SMTP property values from db
                            rs = stmt.executeQuery("Select Tech_Support_Email, POP3, SMTP from sitewide_info");                                               
                            String hostemailaddress = "";
                            String POP3 = "";
                            String SMTP = "";
                            if(rs.next()) {
                               hostemailaddress = rs.getString(1);
                               POP3 = rs.getString(2);
                               SMTP = rs.getString(3);
                  // Specify the SMTP Host
                 Properties props = new Properties();                                                         
                  props.put(POP3, SMTP);
                  // Create a mail session
                  Session ssn = Session.getDefaultInstance(props, null);
                  ssn.setDebug(true);                                            
                  String subject = "Testing out Email";
                  String body = "hello";
                  //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
                  rs = stmt.executeQuery("Select Customer_Name, Email_Address from customer_profiles where "
                                                           +"Customer_Number=1111");
                             String fromName = "";
                             String fromEmail = "";
                             if(rs.next()) {
                                fromName = rs.getString(1);
                                fromEmail = rs.getString(2);
                  InternetAddress from = new InternetAddress(fromDealerEmail,fromDealerName);                    
                String toName = "Bob";                            
                InternetAddress to = new InternetAddress(hostemailaddress,toName);
                      // Create the message
                      Message msg = new MimeMessage(ssn);
                      msg.setFrom(from);
                      msg.setRecipient(Message.RecipientType.TO, to);
                      msg.setSubject(subject);
                      msg.setContent(body, "text/html");
                      Transport.send(msg);             
                  }//try
                   catch (MessagingException mex) {                     
                          mex.printStackTrace(); }
                   catch(Exception e) {}
                 }//end
    }//class              -Love2Java
    Edited by: Love2Java on Mar 11, 2008 9:15 PM

    I have similar problem
    I have the below code in Eclipse and I was able to compile and run it and everything works fine...
    but I have code over in Oracle Jdev and jdev is complaining that "Message.RecipientType.TO" is not found....
    I do have all the jars in the class path.... can't figure out what's wrong
    can some one plz help me out.
    import java.util.Date;
    import java.util.Properties;
    import javax.activation.DataHandler;
    import javax.activation.FileDataSource;
    import javax.mail.Authenticator;
    import javax.mail.Message;
    import javax.mail.MessagingException;
    import javax.mail.Multipart;
    import javax.mail.PasswordAuthentication;
    import javax.mail.Session;
    import javax.mail.Transport;
    import javax.mail.internet.AddressException;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeBodyPart;
    import javax.mail.internet.MimeMessage;
    import javax.mail.internet.MimeMultipart;
    import javax.mail.util.ByteArrayDataSource;
    public void postMail( String recipients, String subject,
    String message , String from) throws MessagingException
    boolean debug = false;
    //Set the host smtp address
    Properties props = new Properties();
    props.put("mail.smtp.host", "server");
    props.put("mail.smtp.auth", "true");
    Authenticator auth = new SMTPAuthenticator();
    Session session = Session.getDefaultInstance(props, auth);
    session.setDebug(debug);
    // create a message
    Message msg = new MimeMessage(session);
    // set the from and to address
    InternetAddress addressFrom = new InternetAddress(from);
    msg.setFrom(addressFrom);
    msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients, false));
    // Setting the Subject and Content Type
    msg.setSubject(subject);
    msg.setContent(message, "text/plain");
    Transport.send(msg);
    private class SMTPAuthenticator extends javax.mail.Authenticator
    public PasswordAuthentication getPasswordAuthentication()
    String username ="user";
    String password = "pass";
    return new PasswordAuthentication(username, password);
    }

  • Integrating Another Program Into A Java GUI

    HI
    I have 3 classes here. One is a Java GUI, the other two are involed in
    stripping and processing of information off a webpage.
    Of these latter two classes, one contains a main method which connects
    to a webpage and reads the info off it, it calls the other class which
    parses this information and holds the variables I need to create
    buttons for the main gui!
    Is it possible at all to integrate, the class that reads the webpage,
    into, the Java GUI class.I need to do this to access the variables
    that the parsing class is holding, as previously I have had to create
    an instance of this class in the webpage reader class, but this was no
    good to me as the GUI could not access this information, i.e can I
    create an instance of this stripper at the begining of main in the GUI
    class so as I can use the results for this for producing my buttons?
    I've tried to do this but I am getting unresolved symbol errors. I was
    wondering should I use global variables to hold the needed info also ?
    Any help at all greatly appreciated,
    Thanks
    Gerry

    I did what you're describing. Sounded simple enough. You put the same logic in main() into the applets init() and you can run as app or applet. Worked well in my IDE. Then the troubles start.
    Visit
    http://www.martinrinehart.com
    and read the Article, Launching Applets. That will get you started on launching a Swing application. (Try my Sample, DawnPainter, to give you an idea about how nice this can be when it works.) I promise but don't deliver (yet) an article on the javascript library I wrote that solves all the problems. For non-commercial use you can get your own copy:
    http://www.martinrinehart.com/examples/launchApplet.js

  • Trying to use a java 32bit program in Arch 64bit

    After giving up some time ago, I decided once more to try to run a commercial 32bit Java application in my Arch 64bit. The same program runs fine in a vm with Ubuntu 64bit. Also, I installed bin32-jre from aur and I messed up the jre.sh and jdk.sh scripts in /etc/profile.d/ and made it work, but then my native Java 64 bit programs won't run.
    To sum up, is there a way to achieve the same Java compatibility that Ubuntu offers? What libs or packages do I have to install and how should I configure them to run every java program, no matter if it is 32 or 64 bit?
    Thanks.

    Awebb wrote:
    Java applications are compiled to bytecode. This bytecode is interpreted by the JRE to run on your specific environment. I don't see how a Java application could be either "32bit" or "64bit". This is the big benefit of Java: Write your code, compile it and run it on every machine that has Java installed.
    Let's try to run your "32bit Java application" on 64bit JRE. What errors do you encounter that make you think you need a different environment?
    Truth is that things are not so simple. This application uses the SWT toolkit for its interface and has other dependencies besides jre (gtk is one for sure). I would be very grateful if you could download the fully functional demo version from here http://www.wordfast.com/zip/2.4.0.1/lin … nux.tar.gz and give it a try. If you can't do that, I can provide some logs. I am sure the problem is not how Java behaves but the way this app is developed and packaged. I have bought a license some years ago, but I still haven't managed to run it properly on any of my Arch machines and I just wait for the devs to take some action on this issue. I have also asked for help, but it seems that they take for granted that their Linux users use distros with mixed libs (like Ubuntu).
    Anyways, thx for your reply.

  • Code won't compile - array

    This is my first in depth attempt to understand the code for enabling arrays. I THINK I have a fairly simple problem, but the code won't compile and NetBeans is telling me I'm missing a symbol &/or class, which I just don't get. Here is the code for the Inventory1 module as well as the main module - what am I not seeing?
    Inventory1 module
    import java.util.Scanner;
    import static java.lang.System.out;
    public class Inventory1
      //declare and initialize variables
      int[] itemNumber = new int [5];
      String[] productName = new String[5];
      int[] stockAmount = new int[5];
      double[] productCost = new double[5];
      double[] totalValue = new double[5];
      int i;
      //int i = 0;
      //initialize scanner
      Scanner sc = new Scanner(System.in);
      Inventory1 info = new Inventory1
    public void inventoryInput()
      while (int i = 0; i < 5; i++)
         out.println("Please enter item number: "); //prompt - item number
         info.itemNumber[i] = sc.nextInt(); // input
         out.println( "Enter product name/description: "); //prompt - product name
         info.productName[i] = sc.nextLine(); // input
         out.println("Quantity in stock: "); // prompt - quantity
         int temp = sc.nextInt(); // capture temp number to verify
         if( temp <=0 )
         { // ensure stock amount is positive number
             out.println( "Inventory numbers must be positive. Please" +
                 "enter a correct value." ); // prompt for correct #
             temp = sc.nextInt(); // exit if statement
         else info.stockAmount[i] = temp; // input
         out.println("What is the product cost for each unit? "); // prompt - cost
         double temp2 = sc.nextDouble();
         if( temp <=0 )
             out.println( "Product cost must be a positive dollar " +
                  "amount. Please enter correct product cost." );
             temp2 = sc.nextDouble();
         else info.productCost[i] = temp2;
      out.println( "We hope this inventory program was helpful. Thank you for " +
          "using our program." );
      } // end method inventoryInput   
    }main module
    public class Main {
      public static void main(String[] args) { //start main method
            Inventory1 currentInventory = new Inventory1(); //call Inventory class
            currentInventory.inventoryInput();
    }

    init:
    deps-jar:
    Compiling 1 source file to C:\Documents and Settings\Tammy\My Documents\School\JavaProgramming\Inventory\build\classes
    C:\Documents and Settings\Tammy\My Documents\School\JavaProgramming\Inventory\src\inventory\Inventory1.java:28: '(' or '[' expected
    public void inventoryInput()
    C:\Documents and Settings\Tammy\My Documents\School\JavaProgramming\Inventory\src\inventory\Inventory1.java:30: '.class' expected
    while (int i = 0; i < 5; i++)
    C:\Documents and Settings\Tammy\My Documents\School\JavaProgramming\Inventory\src\inventory\Inventory1.java:30: illegal start of type
    while (int i = 0; i < 5; i++)
    C:\Documents and Settings\Tammy\My Documents\School\JavaProgramming\Inventory\src\inventory\Inventory1.java:30: not a statement
    while (int i = 0; i < 5; i++)
    C:\Documents and Settings\Tammy\My Documents\School\JavaProgramming\Inventory\src\inventory\Inventory1.java:30: ';' expected
    while (int i = 0; i < 5; i++)
    5 errors
    BUILD FAILED (total time: 0 seconds)

  • JDeveloper 10.1.2.1 won't compile my code?

    Hi,
    I'm pretty new to JDeveloper, and Java in general.
    I've just downloaded and tried to run JDeveloper 10g (10.1.2.1.0, Build 1913) and I've having problems.
    When the application loads, I get a dialog message titled "Java Virtual Machine Launcher", with the message "Could not find the main class. Program will exit"
    JDeveloper then finishes loading.
    I've knocked up a quick JSP page, but it won't compile. I get the message "Internal compilation error, terminated with a fatal exception."
    Also, I've notived that if I go to Project Properties and try to look at Profiles->Development->Libraries, JDeveloper throws a NullPointerException.
    I've got JDeveloper 10.1.3 on my machine, and it has none of these problems?
    After looking around on the web, I'm thinking it might be a CLASS_PATH problem, but how can I confirm this, and how can I fix it?
    Any ideas on what is wrong would be appreciated?
    Thanks
    Thom

    Thanks thahn.
    That fixed the "Java Virtual Machine Launcher" error - I would never have thought spaces in the directory name could have caused this problem!
    The other problems remain though, so I still can't compile any code.

Maybe you are looking for