New to Java (Bound Properties)

Hi all
I am working on an assignment for college, trying to learn Java etc,
Basically I need one object to react to events in another
Code is as follows
// Extra Panel
package myPackage1;
import java.awt.GridLayout;
import java.beans.PropertyChangeEvent;
import javax.swing.JPanel;
public class ExtraPanel extends JPanel implements
java.beans.PropertyChangeListener,
java.io.Serializable
private static final long serialVersionUID = 1L;
public JPanel thisPanel;
public JPanel ExtraPanelMethod()
thisPanel = new JPanel();
             GridLayout grid = new GridLayout();
             grid.setColumns(1);
             grid.setHgap(10);
             grid.setRows(6);
             grid.setVgap(5);
             thisPanel.setLayout(grid);
return thisPanel;
public void propertyChange(PropertyChangeEvent evt)
// The Slider Class
package myPackage1;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.text.NumberFormatter;
public class TheSliderClass extends JPanel implements ChangeListener
private static final long serialVersionUID = 1L;
//Add a formatted text field to supplement the slider.
public JFormattedTextField textField,textField2;
JFormattedTextField newValue = null;
JFormattedTextField oldValue = null;
public String publicSliderName = "";
public int fps;
//And here's the slider.
public JSlider sliderParameterValue;
JPanel labelAndTextField,allTogether;
int TractiveEffort = 0;
public JPanel TheSliderClassMethod(String sliderName, int minimumValue, int maximumValue)
JPanel allTogether = new JPanel();
Font font = new Font("palatino linotype regular", Font.BOLD, 12);
int initialValue = ((minimumValue+maximumValue)/2);
int tickMarkValue = (maximumValue-minimumValue);
publicSliderName = sliderName;
//Create the label.
JLabel sliderLabel = new JLabel(sliderName,JLabel.CENTER);
sliderLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
sliderLabel.setFont(font);
sliderLabel.setForeground(Color.BLUE);
//Create the formatted text field and its formatter.
java.text.NumberFormat numberFormat =
java.text.NumberFormat.getIntegerInstance();
NumberFormatter formatter = new NumberFormatter(numberFormat);
formatter.setMinimum(new Integer(minimumValue));
formatter.setMaximum(new Integer(maximumValue));
textField = new JFormattedTextField(formatter);
textField.setValue(new Integer(initialValue));
textField.setColumns(3); //get some space
textField.setEditable(false);
textField.setForeground(Color.red);
textField2 = new JFormattedTextField(formatter);
textField2.setValue(new Integer(initialValue));
textField2.setColumns(3); //get some space
textField2.setEditable(false);
textField2.setForeground(Color.red);
//Create the slider.
sliderParameterValue = new JSlider(JSlider.HORIZONTAL,
minimumValue, maximumValue, initialValue);
sliderParameterValue.addChangeListener(this);
//Turn on labels at major tick marks.
sliderParameterValue.setMajorTickSpacing(tickMarkValue);
sliderParameterValue.setMinorTickSpacing(10);
sliderParameterValue.setPaintTicks(true);
sliderParameterValue.setPaintLabels(true);
sliderParameterValue.setBorder(
BorderFactory.createEmptyBorder(0,0,0,0));
sliderParameterValue.setBackground(Color.cyan);
//Create a subpanel for the label and text field.
JPanel labelAndTextField = new JPanel(); //use FlowLayout
labelAndTextField.setBackground(Color.cyan);
labelAndTextField.add(sliderLabel);
labelAndTextField.add(textField);
//Put everything together.
GridLayout gridThis = new GridLayout();
gridThis.setColumns(1);
gridThis.setRows(2);
allTogether.setLayout(gridThis);
allTogether.add(labelAndTextField);
allTogether.add(sliderParameterValue);
allTogether.setBorder(BorderFactory.createBevelBorder(1,Color.red,
Color.red));
return allTogether;
/** Listen to the slider. */
public void stateChanged(ChangeEvent e)
JSlider source = (JSlider)e.getSource();
fps = (int)source.getValue();
textField.setText(String.valueOf(fps));
textField2.setText(String.valueOf(fps));
}How do I get a method in Extra Panel to multiple the values in textField2 to react to the slider in the Slider Class being moved?
Thanks all
Message was edited by:
N_Gen_Steam_Dev
Message was edited by:
N_Gen_Steam_Dev

The code now is
// The Slider Class
package myPackage1;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.text.NumberFormatter;
public class TheSliderClass extends JPanel implements ChangeListener
     private static final long serialVersionUID = 1L;
     //Add a formatted text field to supplement the slider.
     public JFormattedTextField textField,textField2;
     JFormattedTextField newValue = null;
     JFormattedTextField oldValue = null;
     public String publicSliderName = "";
     public int fps;
     //And here's the slider.
     public JSlider sliderParameterValue;
     JPanel labelAndTextField,allTogether;
     int TractiveEffort = 0;
     public JPanel TheSliderClassMethod(String sliderName, int minimumValue, int maximumValue)
          JPanel allTogether = new JPanel();
          Font font = new Font("palatino linotype regular", Font.BOLD, 12);
          int initialValue = ((minimumValue+maximumValue)/2);
          int tickMarkValue = (maximumValue-minimumValue);
          publicSliderName = sliderName;
          //Create the label.
          JLabel sliderLabel = new JLabel(sliderName,JLabel.CENTER);
          sliderLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
          sliderLabel.setFont(font);
          sliderLabel.setForeground(Color.BLUE);
          //Create the formatted text field and its formatter.
          java.text.NumberFormat numberFormat =
               java.text.NumberFormat.getIntegerInstance();
          NumberFormatter formatter = new NumberFormatter(numberFormat);
          formatter.setMinimum(new Integer(minimumValue));
          formatter.setMaximum(new Integer(maximumValue));
          textField = new JFormattedTextField(formatter);
          textField.setValue(new Integer(initialValue));
          textField.setColumns(3); //get some space
          textField.setEditable(false);
          textField.setForeground(Color.red);
          textField2 = new JFormattedTextField(formatter);
          textField2.setValue(new Integer(initialValue));
          textField2.setColumns(3); //get some space
          textField2.setEditable(false);
          textField2.setForeground(Color.red);
          //Create the slider.
          sliderParameterValue = new JSlider(JSlider.HORIZONTAL,
          minimumValue, maximumValue, initialValue);
          sliderParameterValue.addPropertyChangeListener(new ExtraPanel());
          sliderParameterValue.addChangeListener(this);
          //Turn on labels at major tick marks.
          sliderParameterValue.setMajorTickSpacing(tickMarkValue);
          sliderParameterValue.setMinorTickSpacing(10);
          sliderParameterValue.setPaintTicks(true);
          sliderParameterValue.setPaintLabels(true);
          sliderParameterValue.setBorder(
          BorderFactory.createEmptyBorder(0,0,0,0));
                                                  sliderParameterValue.setBackground(Color.cyan);
          //Create a subpanel for the label and text field.
          JPanel labelAndTextField = new JPanel(); //use FlowLayout
          labelAndTextField.setBackground(Color.cyan);      
          labelAndTextField.add(sliderLabel);
          labelAndTextField.add(textField);
          //Put everything together.
          GridLayout gridThis = new GridLayout();
          gridThis.setColumns(1);
          gridThis.setRows(2);
          allTogether.setLayout(gridThis);
          allTogether.add(labelAndTextField);
          allTogether.add(sliderParameterValue);
          allTogether.setBorder(BorderFactory.createBevelBorder(1,Color.red,
                                                                                Color.red));
          return allTogether;
     /** Listen to the slider. */
     public void stateChanged(ChangeEvent e)
          JSlider source = (JSlider)e.getSource();
          fps = (int)source.getValue();
          textField.setText(String.valueOf(fps));
          textField2.setText(String.valueOf(fps));
}//Extra Class
package myPackage1;
import java.awt.GridLayout;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.JPanel;
import javax.swing.JSlider;
public class ExtraPanel extends JPanel implements
                                                       PropertyChangeListener
     private static final long serialVersionUID = 1L;
     public JPanel thisPanel;
     public TheSliderClass aPointer = new TheSliderClass();
     public JPanel ExtraPanelMethod()
          thisPanel = new JPanel();
          GridLayout grid = new GridLayout();
          grid.setColumns(1);
          grid.setHgap(10);
          grid.setRows(6);
          grid.setVgap(5);
          thisPanel.setLayout(grid);
          return thisPanel;
     public void propertyChange(PropertyChangeEvent e)
          JSlider source = (JSlider)e.getSource();
          int fps = (int)source.getValue();
          System.out.println("Here  "+ fps);
}What i now does is that the method propertyChange is called but does not react to the slider being moved. It print "Here " + fps a number of times for each instance of the slider class, then it prints the initial values of fps and sits there even though the slider is being moved.
Help again
Thanks

Similar Messages

  • Java system properties

    In weblogic 10.3, is it possible to set java arguments by using the console only?
    I tried to put:
    -DmyArg=XXX
    inside the Arguments section of my weblogic server under the tab "Server start".
    However, when I start the server and look at the logs, the Java system properties are printed there, but I can't see my new property..
    Thanks.

    Well, if you use script to start server, then you need to add required settings to the script.
    Arguments field in startup properties are processed by the NodeManager while executing command to start server. See here for more details: http://e-docs.bea.com/wls/docs92/server_start/nodemgr.html#wp1081792

  • Compiling message "cannot read" (new to java)

    Sorry about yet another question on compiling. I'm new to java. I've read alot of the threads on this, but my HelloJava.java won't compile.
    I'm working on w2k. I've set my path to
    %SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;c:\j2sdk1.4.0\bin
    using the environment variables in the system properties box.
    This seems to work fine.
    but I keep getting the "cannot read" when compiling.
    I've created a classpath variable in the environment variables
    CLASSPATH = .;C:\src
    and my java file is definately .java not .java.txt and it's in the src folder on my c drive.
    Do I need to set classpath? Also I've put my HelloJava.java file in the same folder as my javac and it still won't compile. What am I doing wrong?
    By the way, the HelloJava file came from the book "Learning Java".
    thanks in advance.

    OK -
    If you place your .java files in C:\src, to compile you must either
    1. Go to (change the current directory to, using cd command) c:\src and then enter "javac ...."
    or
    2 From any directory enter "javac C:\src\...."
    Classpath is used by javac and java, but not in this way.
    Read here for the full story:
    The Path is a set of pointers that Windows uses to locate programs that you execute, like javac.exe and java.exe. This setting is explained here:
    http://java.sun.com/j2se/1.4/install-windows.html
    Scroll down to: 5. Update the PATH variable
    The CLASSPATH is another set of pointers that is used by Java to find the files that you create and want compiled and/or run. This setting is explained here:
    Setting the Classpath:
    http://java.sun.com/j2se/1.4/docs/tooldocs/windows/classpath.html
    [NOTE: always start your classpath with ".;" which means the current directory. See my classpath, below]
    How Classes are Found:
    http://java.sun.com/j2se/1.4/docs/tooldocs/findingclasses.html

  • Error in Parser.fx file "incompatible types found   : java.util.Properties"

    Hi,
    In parser file "Parser.fx",
    public-read def PROPERTIES_PARSER = StreamParser {
    override public function parse(input : java.io.InputStream) : RecordSet {
    var props = javafx.util.Properties {};
    props.load(input);
    input.close();
    MemoryRecordSet {
    records: [
    MapRecord {
    fields: props
    due to under line portion an error is appearing:
    "incompatible types
    found : javafx.util.Properties
    required: java.util.Map
    fields: props".
    Please suggest some solution.
    Thanks in advance.
    regards,
    Choudhary Nafees Ahmed
    Edited by: ChoudharyNafees on Jul 5, 2010 3:48 AM

    Parser.fx
    package org.netbeans.javafx.datasrc;
    import javafx.data.pull.PullParser;
    import javafx.data.pull.Event;
    import org.netbeans.javafx.datasrc.MemoryRecordSet;
    public-read def PROPERTIES_PARSER = StreamParser {
        override public function parse(input : java.io.InputStream) : RecordSet {
            var props =java.util.Properties{};
            props.load(input);
            input.close();
            MemoryRecordSet {
                records: [
                    MapRecord {
                        fields: props
    public-read def LINE_PARSER_FIELD_LINE = ".line";
    public-read def LINE_PARSER = StreamParser {
        override public function parse(input : java.io.Reader) : RecordSet {
            var line : String;
            var result : Record [] = [];
            line = readLine(input);
            // BEWARE  ("" == null) is true
            while (line != null or "".equals(line)) {
                var map = new java.util.HashMap();
                map.put(LINE_PARSER_FIELD_LINE, line);
                var record = MapRecord {
                    fields: map
                insert record into result;
                line = readLine(input);
            MemoryRecordSet {
                records: result
    function readLine(in : java.io.Reader) : String {
        var str = new java.lang.StringBuilder;
        while (true) {
            var c = in.read();
            if (c == -1) {
                return if (str.length() == 0) then null else str.toString();
            } else if (c == 0x0D) {
                c = in.read();
                if (c == 0x0A or c == -1) {
                    return str.toString();
                str.append(0x0D);
            } else if (c == 0x0A) {
                return str.toString();
            str.append(c as Character);
        str.toString()
    public-read def JSON_PARSER = StreamParser {
        function toSequence(list : java.util.List) : Record [] {
            var result : Record [] = [];
            var ii = list.iterator();
            while (ii.hasNext()) {
                var r = ii.next() as Record;
                insert r into result;
            result
        override public function parse(input : java.io.InputStream) : RecordSet {
            var topLevel : Object;
            def parser = PullParser {
                documentType: PullParser.JSON
                input: input
                var mapStack = new java.util.Stack();
                var currentMap : java.util.Map;
                var recordsStack = new java.util.Stack();
                var currentRecords : java.util.List;
                var lastEvent: Event;
                onEvent: function(event: Event) {
                    if (event.type == PullParser.TEXT) {
                        currentMap.put(event.name, event.text)
                    } else if (event.type == PullParser.INTEGER) {
                        currentMap.put(event.name, event.integerValue)
                    } else if (event.type == PullParser.NULL) {
                        currentMap.put(event.name, null)
                    } else if (event.type == PullParser.START_ELEMENT) {
                        if (lastEvent.type == PullParser.START_ARRAY_ELEMENT) return;
                        var oldMap = currentMap;
                        var temp = new java.util.HashMap();
                        temp.put(new Object(), null);
                        currentMap = temp;
                        currentMap.clear();
                        mapStack.push(currentMap);
                        if (topLevel == null) topLevel = currentMap;
                        if (oldMap != null) {
                            var mr = MapRecord {
                                fields: currentMap
                            if (event.name == "" and lastEvent.type == PullParser.START_VALUE) {
                                oldMap.put(lastEvent.name, mr)
                            } else {
                                oldMap.put(event.name, mr)
                    } else if (event.type == PullParser.START_ARRAY_ELEMENT) {
                        var temp = new java.util.HashMap();
                        temp.put(new Object(), null);
                        currentMap = temp;
                        currentMap.clear();
                        mapStack.push(currentMap);
                        var mr = MapRecord {
                            fields: currentMap
                        currentRecords.add(mr);
                    } else if (event.type == PullParser.END_ELEMENT) {
                        mapStack.pop();
                        if (not mapStack.empty()) {
                            currentMap = mapStack.peek() as java.util.HashMap;
                        } else {
                            currentMap = null;
                    } else if (event.type == PullParser.END_ARRAY_ELEMENT) {
                        if (lastEvent.type == PullParser.END_ELEMENT) return;
                        mapStack.pop();
                        if (not mapStack.empty()) {
                            currentMap = mapStack.peek() as java.util.HashMap;
                        } else {
                            currentMap = null;
                    } else if (event.type == PullParser.START_ARRAY) {
                        currentRecords = new java.util.ArrayList();
                        recordsStack.push(currentRecords);
                        if (topLevel == null) topLevel = currentRecords;
                    } else if (event.type == PullParser.END_ARRAY) {
                        var set = MemoryRecordSet {
                            records: toSequence(currentRecords)
                        currentMap.put(event.name, set);
                        recordsStack.pop();
                        if (not recordsStack.empty()) {
                            currentRecords = recordsStack.peek() as java.util.List;
                        } else {
                            currentRecords = null;
                    lastEvent = event;
            parser.parse();
            if (topLevel instanceof java.util.Map) {
                var mr = MapRecord {
                    fields: topLevel as java.util.Map
                MemoryRecordSet {
                   records: [mr]
            } else {
                // List
                var rs = MemoryRecordSet {
                    records: toSequence(topLevel as java.util.List)
                rs
            parser.parse();
            var mr = MapRecord {
                fields: topLevel as java.util.Map
            MemoryRecordSet {
               records: [mr]

  • Java.util.properties ? Using Config.getProperty

    Hi all,
    This one has been causing me a bit of a headache! I am using the Java.util.properties to create a file which looks like this:
    #Tue Sep 13 19:15:06 GMT+02:00 2002
    User=tristan
    Password=bristol
    Name=Tristan\ Webb
    Rights=Tristan\ Webb
    #Tue Sep 13 19:15:35 GMT+02:00 2002
    User=adam
    Password=newcastle
    Name=Adam\ Jones
    Rights=Adam\ Jones
    The problem comes when I try to read the information back and put it in a Vector. Using the code below, it only ever puts the last users details (i.e. adam, Newcastle etc..) into the file and skips the first one. I have tried adding more users details, but it only ever reads the last entry. Is there anyway of forcing the config.getProperty to read the first entry in the file and then all the subsequesnt user details ?? I am thinking there must be a way of looping through the file, but im not sure where to start and am quite lost!
    Many Thanks,
    Properties config;
    FileInputStream file;
    file = new FileInputStream("password.cfg");
    config = new Properties();
    config.load(file);
    User2 = config.getProperty("User");
    Password = config.getProperty("Password");
    name = config.getProperty("Name");
    rights = config.getProperty("Rights");
    UserDetails user = new UserDetails(User2, Password, name, rights);
    userDetails.add(user);

    The java.util.Properties class works like a dictionary: it stores values, which you can access using the keys.
    The keys must be unique. In your case, the keys are not unique. If you do: String s = config.getProperty("User"); then how do you expect to get two values back (tristan and adam)?
    You must make the keys unique in some way. For example, write your properties file like this:
    #Tue Sep 13 19:15:06 GMT+02:00 2002
    User.1=tristan
    Password=.1bristol
    Name.1=Tristan\ Webb
    Rights.1=Tristan\ Webb
    #Tue Sep 13 19:15:35 GMT+02:00 2002
    User.2=adam
    Password.2=newcastle
    Name.2=Adam\ Jones
    Rights.2=Adam\ Jones
    Now use for example: String s = config.getProperty("User.1"); to get the name of the first user, etc.
    Jesper

  • Retrofitting java.util.Properties

    Hi all,
    why was java.util.Properties in JDK 1.5 not retrofitted to implement java.util.Map<String,String>?
    This would have been the "natural" way to take advantage of typesafety.
    I'm sure this has something to do with backwards compatibility, but what exactly woud it break?
    Thanks

    java.util.Properties extends java.util.Hashtable
    java.util.Properties : private java.util.HashtableWhat does that actually buy you though?
    I mean its really the difference between:
    class Properties {
        final Hashtable m_contents = new Hashtable();
        public String getProperty(String key) {
                return (String) m_contents.get(key);
    }vs.
    class Properties private extends Hashtable {
        public String getProperty(String key) {
                return (String) super.get(key);
    }Which is nice and all, but it strikes me as syntactic sugar more than anything else.
    I don't disagree: Properties should never have extended Hashtable, it should have encapsulated a Hashtable. Also Stack should not extend Vector, Booleans should not have a public constructor, it would even have been nicer if people actually used the Dictionary interface occassionally in 1.0/1.1.
    Its easy to say these things now with the benefit of 20-20 hindsight.

  • Invalid data returned when iterating a java.util.Properties

    Hi all,
    I'm having trouble iterating thru the values in a java.util.Properties object.
    This problem only occurs when passing in a java.util.Properties object into the constructor of a java.util.Properties.
    Here's some example code. (A picture is worth....)
    <pre>
    import java.util.Properties;
    import java.util.Iterator;
    public class PropertyTest {
    public static void main(String[] args) {
    Properties validProp = new Properties();
    //add some data
    validProp.put("key1", "key1Value");
    validProp.put("key2", "key2Value");
    validProp.put("key3", "key3Value");
    System.out.println("This will iterate...");
    dumpPropertyFile(validProp); //This will iterate correctly
    Properties inValidProp = new Properties(validProp);
    System.out.println("This doesn't iterate correctly");
    dumpPropertyFile(inValidProp); //This will not iterate
    public static void dumpPropertyFile(Properties prop) {
    Iterator iter = prop.keySet().iterator();
    while (iter.hasNext()) {
    String key = (String)iter.next();
    System.out.println(key + "=" + prop.getProperty(key));
    </pre>
    I have searched the bug database, but didn't find any open bugs related to this issue.
    Could someone let me know if this is a existing bug or has this bug already been addressed.
    My setup.
    NT 4.0 / jdk1.3.1
    Thanks,

    I found this works.
    Iterator e = _props.keySet().iterator();
    while(e.hasNext())
    String str = (String)e.next();
    System.out.println("key(" + str + ")=" + _props.getProperty(str));
    but the display sequence is always in descending order ???
    Anyone has a clue ?
    Input :
    catch#2 Prop catch#2
    prop2 Properties.test.2
    catch#6 Prop catch#6
    catch#3 Prop catch#3
    catch#5 Prop catch#5
    catch#4 Prop catch#4
    prop3 test Properties
    prop4 test Properties4
    prop1 Properties.test.1
    catch#1 Prop catch#1
    Output:
    prop4=test Properties4<
    prop3=test Properties<
    prop2=Properties.test.2<
    prop1=Properties.test.1<
    catch#6=Prop catch#6<
    catch#5=Prop catch#5<
    catch#4=Prop catch#4<
    catch#3=Prop catch#3<
    catch#2=Prop catch#2<
    catch#1=Prop catch#1<

  • Unable to validate a java.util.Properties XML based File

    I cannot for the life of me figure out what is wrong with this xml file, but it fails the validation of java.util.Properties and as such won't be parsed in. Help!
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
    <properties version="1.0">
      <entry key="bottleneckServer.address"></entry>
      <entry key="bottleneckServer.port">8206</entry>
      <entry key="bottleneckServer.confirmDelay">10</entry>
      <entry key="bottleneckServer.cleanupDelay">120</entry>
    </properties>Thanks in advance!

    This xml file works perfectly.
    Here is some test code:
            Properties p = new Properties();
            p.loadFromXML(getClass().getClassLoader().getResourceAsStream("someFilePath/someFileName.xml"));
            assert "8206".equals(p.getProperty("bottleneckServer.port")) : "Property 'bottleneckServer.port' != 8206";

  • New to java...  Having problems with Stringbuffer - FileReader

    I believe what I am trying to do is quite simple but I am missing something...
    Basically I need to read the contents of a text file and append the text to an email message. As I said, I am new to java and I certainly don't understand everything, but I will do my best to answer any questions you may have.
    My attempt at writing the code is below. The relevant sections are in bold
    private void emailDevLicense(HttpServletRequest request, HttpServletResponse response, String operatorId) {
    String configId = request.getParameter("configurationId");
    String deployPath = cdlcmConfig.getLmLicensePath();
    String cName = request.getParameter("cName");
    String aName = request.getParameter("aName");
    String lPath = request.getParameter("lPath");
    String licenseName = request.getParameter("name");
    String description = request.getParameter("licenseConfigDesc");
    String contents = null;
    Properties emailProperties = new Properties();
    emailProperties.put("mail.smtp.host", cdlcmConfig.getEmsMailServer());
    Session mailSession = Session.getDefaultInstance(emailProperties, null);
    String mailFrom = cdlcmConfig.getEmsMailFrom();
    MimeMessage message = new MimeMessage(mailSession);
    MimeBodyPart p1 = new MimeBodyPart();
    MimeBodyPart p2 = new MimeBodyPart();
    MimeBodyPart p3 = new MimeBodyPart();
    String operatorName = DbHelper.getOperatorName(operatorId);
    String recipient = "[email protected]";
    String filename1 = deployPath + "/l-" + configId + "/license.dat";
    String filename2 = deployPath + "/l-" + configId + "/company.dat";
    log.info("emailDevLicense");
    *try {*
    File f = new File(lPath, "license.dat");
    BufferedReader br = new BufferedReader(new FileReader(f));
    StringBuffer sb = new StringBuffer();
    String eachLine = br.readLine();
    *while (eachLine != null) {*
    eachLine = br.readLine();
    sb.append(contents); }
    *catch (java.io.FileNotFoundException ex) {*
    log.error("Unable to find license file license.dat", ex);
    *catch (java.io.IOException ex) {*
    log.error("Unable to read lines from license.dat", ex);
    try {
    /* Set user-entered RFC822 headers to a message (mmsg). */
    message.setHeader ("From", "[email protected]");
    message.setHeader ("Reply-To", "[email protected]");
    message.setHeader ("To", recipient);
    message.setSubject("License files for Customer Name: " + cName + " / Account Name: " + aName + "");
    /* Add any other desired headers. */
    p1.setText("Configuration Name: " + licenseName + "\n\nOrder Number: " + description + "" + contents + "");
    // Put a file in the second part
    FileDataSource fds1 = new FileDataSource(filename1);
    p2.setDataHandler(new DataHandler(fds1));
    p2.setFileName(fds1.getName());
    // Put a file in the second part
    FileDataSource fds2 = new FileDataSource(filename2);
    p3.setDataHandler(new DataHandler(fds2));
    p3.setFileName(fds2.getName());
    // Create the Multipart. Add BodyParts to it.
    Multipart mp = new MimeMultipart();
    mp.addBodyPart(p1);
    mp.addBodyPart(p2);
    mp.addBodyPart(p3);
    // Set Multipart as the message's content
    message.setContent(mp);
    log.info("Sending Dev License");
    Transport.send(message);
    } catch (MessagingException ex) {
    log.error("Unable to send license mail to address " + recipient, ex);
    }

    You guys\gals rock...
    This solved my problem and taught me something in the process. I have been trying to do this myself for 3 days now...so...thanks so much for the help.
    Once that worked I had to add a return after each line was read and I actually got that right on the first try.
    The final code is below.
    Thanks everyone..
    try {
                File f = new File(lPath, "license.dat");
                BufferedReader br = new BufferedReader(new FileReader(f));
                StringBuffer sb = new StringBuffer();
                String eachLine = br.readLine();
                while (eachLine != null) {
                    sb.append(eachLine + "\n");
                    eachLine = br.readLine();
               contents = sb.toString();
                catch (java.io.FileNotFoundException ex) {
                log.error("Unable to find license file license.dat", ex);
                catch (java.io.IOException ex) {
                log.error("Unable to read lines from license.dat", ex);
                }

  • I am completealy new at java.  HELP!!!!

    K, hi, well, i am experienced in HTML and Macromedia Flash, and Game Maker 5, a shit game maker prog. Ne ways, i admire games like RuneScape and would like to know how i would get around to making one. I know that i can't just jut out and make a rs type game. But i would like to know where to start? Are there programs i need to buy or DL, or are there books? And btw, is Java like HTML where u sit in front of a notepad prog, and type? or is it like u type and see whats happening? or do u add objects and give them properties..... Its a whole lot to ask! lol, Help me out.......try to answer it all.

    Resources for Beginners
    Sun's basic Java tutorial
    Sun's New To Java Center. Includes an overview of what Java is, instructions for setting up Java, an intro to programming (that includes links to the above tutorial or to parts of it), quizzes, a list of resources, and info on certification and courses.
    http://javaalmanac.com. A couple dozen code examples that supplement The Java Developers Almanac.
    jGuru. A general Java resource site. Includes FAQs, forums, courses, more.
    JavaRanch. To quote the tagline on their homepage: "a friendly place for Java greenhorns." FAQs, forums (moderated, I believe), sample code, all kinds of goodies for newbies. From what I've heard, they live up to the "friendly" claim.
    Bruce Eckel's Thinking in Java (Available online.)
    Joshua Bloch's Effective Java
    Bert Bates and Kathy Sierra's Head First Java. This one has been getting a lot of very positive comments lately.
    But i would like to know where to start? With reading the "New To Java" tutorials.
    Are there programs i need to buy or DLTo start with you only need Notepad, and the JDK (AKA the Java SDK), downloadable from http://java.sun.com/j2ee/1.4/download-sdk.html
    Later on, you might also want an IDE, or maybe just a better text editor. But for now, just stick with Notepad.
    And btw, is Java like HTML where u sit in front of a notepad prog, and type?Mostly, after writing something (in Notepad), then compile it, then run it. And extra step than HTML has.
    or is it like u type and see whats happening?You can also get interactive shells for it, but for now, do not worry about them.
    r do u add objects and give them propertiesYou can get IDEs which let you work this way, but for now, do not worry about them.

  • How can I open help file (HTML or .chm) from Java Web Start (new to JAVA)

    Hi All,
    Im trying to open the help file of my application.
    When trying to access the help file from the GUI (pressing F1 for launching the help file), I'm geting the an error, something like:
    "Can't show help URL: jar:file:C:\Documents and Settings\%USER%\Application Data\Sun\Java\Deployment\javaws\cache\http\Dlocalhost\P7001\DMwebstart\RMjar-name!/com/resources/helpFiles/MyHelpFile.html"
    It seems that the file which is packed in a jar, was downloaded to the Java Web Start cache directory:
    C:\Documents and Settings\%USER%\Application Data\Sun\Java\Deployment\javaws\cache\http\Dlocalhost\P7001\DMwebstart
    The code which is activated when launching the help file is:
    try
                ResourceBundle resourceBundle = DoubleResourceBundle.getBundle("Resource", "ResourceImpl");
                RuntimeUtil.launchFile(new File(resourceBundle.getString("help.file")));
            } catch (IOException e)
                // TODO Auto-generated catch block
                e.printStackTrace();
            }where the property "help.file" is in some property file in the resource bundle named "Resource", and looks like this :
    help.file="com/trax/docs/help/global/MyHelpFile.html"
    The function "RuntimeUtil.launchFile" knows how to launch any file in its default application, and indeed it does launches the html, when giving it an absolute path to the file on my PC, as "C:\Helpfiles\MyHelpFile.html" as such:
    RuntimeUtil.launchFile("C:\Helpfiles\MyHelpFile.html");My question is :
    The application is going to be deployed on a Customer PC. How can I access the html file from the code, with a relative path and not its absolute path on the customer pc, which I can't know?
    I found these restrictions regarding web start:
    (copied from "http://rachel.sourceforge.net/"):
    *Rule 1: Java Archives only. No loose files.* All your resources have to be packaged in Java Archives (jar) if you want to have
    them delivered to the user's machine and kept up-to-date automatically by Java Web Start.
    *Rule 2: No file paths.* You can't use absolute or relative file paths to locate your
    jars holding your resources (e.g. <code>jar:file:///c:/java/jws/.cache/resources.jar</code>).
    Absolute file paths won't work because you never know where Java Web Start
    will put your jar on the user's machine. Relative file paths won't work because Java Web Start
    mangles the names of your jars (e.g. <code>venus.jar</code> becomes <code>RMvenus.jar</code>)
    and every JNLP client implementation has the right to mangle your names
    in a different way and you, therefore, can't predict the name with
    which your jar will be rechristend and end up on the user's machine in
    the application cache.Seems complex or impossible, to perform a simple task like opening a file.
    Please advise (I'm new to Java and Web Start).
    BTW, I'm working with IntelliJ IDEA 5.0.
    Thanks,
    Zedik.
    {font:Tahoma}{size:26pt}
    {size}{font}

    the follwing method i have used to open html file ...
    so to access html file i am shipping resources folder with jar file ..
    private void openHtmlPages(String pageName) {
         String cmd[] = new String[2];
         String browser = null;
         File file = null;
         if(System.getProperty("os.name").indexOf("Linux")>-1) {
              file = new File("/usr/bin/mozilla");
              if(!file.exists() ) {
              }else     {
                   browser = "mozilla";
         }else {
              browser = "<path of iexplore>";
         cmd[0] = browser;
         File files = new File("");
         String metaData = "/resources/Help/Files/"+pageName+".html"; // folder inside jar file
         java.net.URL url = this.getClass().getResource(metaData);
         String fileName = url.getFile();
         fileName = fileName.replaceAll("file:/","");
         fileName = fileName.replaceAll("%2520"," ");
         fileName = fileName.replaceAll("%20"," ");
         fileName = fileName.replaceAll("jarfilename.jar!"," ").trim();
         cmd[1] = fileName;     
         try{
              Process p = Runtime.getRuntime().exec(cmd);
         }catch(java.io.IOException io){
                   //Ignore
    can anyone give me the solution..???
    Regards
    Ganesan S

  • What is new in Java syntaxes in new Java versions?

    What is new in Java syntaxes in new Java versions?
    What about this sentenses
    1. for (int c:data), where data is array of integer
    2. ArrayList<Object> () ...
    3. Class<?>...
    I can't find this syntaxes in my books and documentation...
    And what Java version is latest?

    dont crosspost
    Edited by language police

  • What's new in Java 4

    Anybody can quickly explain the things are added in Java 4 newly.
    Thnx in advance.

    Nothing's new in Java 4 because there is no Java 4.
    Maybe you mean Java 5?
    Or maybe you mean Java 1.4?
    In either case, either the download page for that version, or the installation, should have release notes that answer your question.
    In fact, here they are for Java 5:
    http://java.sun.com/j2se/1.5.0/docs/relnotes/features.html

  • New TO JAVA Programming

    Dear Forummembers,
    I am student doing postgraduate studies in IT.i have some queries related to one of my programming staff.i am very much new into Java programming and i am finding it a bit difficult to handle this program.The synopsis of the program is given below -
    You are required to design and code an object-oriented java program to process bookings for a theatre perfomance.
    Your program will read from a data file containing specifications of the performance,including the names of the theatre, the play and its author and the layout of the theatre consisting of the number of seats in each row.
    It will then run a menu driven operation to accept theatre bookings or display the current
    status of seating in the theatre.
    The name of the file containing the details of the performance and the theatre should be
    provided at the command line, eg by running the program with the command:
    java Booking Theatre.txt
    where Theare.txt represents an example of the data file.
    A possible data file is:
    Opera
    U and Me
    Jennifer Aniston
    5 10 10 11 12 13 14
    The data provided is as follows
    Line 1
    Name of the Theatre
    Line 2
    Name of the play being performed
    Line 3
    Name of the author of the play being performed
    Line 4
    A list of the lengths (number of seats) of each row in the theatre, from front to
    back.
    The program must start by reading this file, storing all the appropriate parameters and
    establishing an object to accept bookings for this performance with all details for the theatre
    and performance.
    The program should then start a loop in which a menu is presented to the user, eg:
    Select from the following:
    B - Book seats
    T - Display Theatre bookings
    Q - Quit from the program
    Enter your choice:
    And keep performing selected operations until the user�s selects the quit option, when the
    program should terminate.
    T - Display Theatre bookings
    The Display Theatre Bookings option should display a plan of the theatre. Every available
    seat should be displayed containing its identification, while reserved seats should contain an
    Rows in each theatre are indicated by letters starting from �A� at the front. Seats are
    numbered from left to right starting from 1. A typical seat in the theatre might be designated
    D12, representing seat 12 in row D.
    B - Book seats
    The booking of seats is to offer a number of different options.
    First the customer must be asked how many adjacent seats are
    required. Then start a loop offering a further menu of choices:
    Enter one of the following:
    The first seat of a selected series, eg D12
    A preferred row letter, eg F
    A ? to have the first available sequence selected for you
    A # to see a display of all available seats
    A 0 to cancel your attempt to book seats
    Enter your selection:
    1. If the user enters a seat indentifier such B6, The program should attempt to
    reserve the required seats starting from that seat. For example if 4 seats are
    required from B6, seats B6, B7, B8 and B9 should be reserved for the customer,
    with a message confirming the reservation and specifying the seats reserved..
    Before this booking can take place, some testing is required. Firstly, the row
    letter must be a valid row. Then the seat number must be within the seats in the
    row and such that the 4 seats would not go beyond the end of the row. The
    program must then check that none of the required seats is already reserved.
    If the seats are invalid or already reserved, no reservation should be made and the
    booking menu should be repeated to give the customer a further chance to book
    seats.
    If the reservation is successful, return to the main menu.
    2. The user can also simply enter a row letter, eg B.IN this case, the program should
    first check that the letter is a valid row and then offer the user in turn each
    adjacent block of the required size in the specified row and for each ask whether
    the customer wants to take them. Using the partly booked theatre layout above, if
    the customer wanted 2 seats from row B, the customer should be offered first:
    Seats B5 to B6
    then if the customer does not want them:
    Seats B10 to B11
    and finally
    Seats B11 to B12
    If the customer selects a block of seats, then return to the main menu. If none are
    selected, or there is no block of the required size available in the row, then report
    that no further blocks of the required size are available in the row and repeat the
    booking menu.
    3. If the user enters a ? the program should offer the customer every block of seats
    of the required size in the whole theatre. This process should start from the first
    row and proceed back a row at a time. For example, again using the partially
    booked theatre shown above, if the user requested 9 seats, the program should
    offer in turn:
    Seats A1 to A9
    Seats C1 to C9
    Seats C2 to C10
    Seats E3 to E11
    Seats E4 to E12
    If the customer selects a block of seats, then return to the main menu. If none are
    selected, or there is no block of the required size available in the whole theatre,
    then report that no further blocks of the required size are available and repeat the
    booking menu.
    4. If the user enters a # the program should display the current status of the seating
    in the theatre, exactly the same as for the T option from the main menu and then
    repeat the booking menu.
    5. If the user enters a 0 (zero), the program should exit from the booking menu back
    to the main menu. If for example the user wanted 9 seats and no block of 9 was
    left in the theatre, he would need to make two separate smaller bookings.
    The program should perform limited data validation in the booking process. If a single
    character other than 0, ? and # is entered, it should be treated as a row letter and then tested
    for falling within the range of valid rows, eg A to H in the example above. Any invalid row
    letters should be rejected.
    If more than one character is entered, the first character should be tested as a valid row letter,
    and the numeric part should be tested for falling within the given row. You are NOT
    required to test for valid numeric input as this would require the use of Exception handling.
    You are provided with a class file:
    Pad.java
    containing methods that can be used for neat alignment of the seat identifiers in the theatre
    plan.
    File Processing
    The file to be read must be opened within the program and if the named file does not exist, a
    FileNotFoundException will be generated. It is desirable that this Exception be caught and
    a corrected file name should be asked for.
    This is not required for this assignment, as Exception handling has not been covered in this
    Unit. It will be acceptable if the method simply throws IOException in its heading.
    The only checking that is required is to make sure that the user does supply a file on the
    command line, containing details of the performance. This can be tested for by checking the
    length of the parameter array args. The array length should be 1. If not, display an error
    message telling the user the correct way to run the program and then terminate the program
    System.exit(0);
    The file should be closed after reading is completed.
    Program Requirements
    You are expected to create at least three classes in developing a solution to this problem.
    There should be an outer driving class, a class to represent the theatre performance and its
    bookings and a class to represent a single row within the theatre.
    You will also need to use arrays at two levels. You will need an array of Rows in the Theatre
    class.
    Each Row object will need an array of seats to keep track of which seats have been reserved.
    Your outer driving class should be called BookingOffice and should be submitted in a file named BookingOffice.java
    Your second, third and any additional classes, should be submitted in separate files, each
    class in a .java file named with the same name as the class
    I am also very sorry to give such a long description.but i mainly want to know how to approach for this program.
    also how to designate each row about it's column while it is being read from the text file, how to store it, how to denote first row as row A(second row as row B and so on) and WHICH CLASS WILL PERFORM WHICH OPERATIONS.
    pls do give a rough guideline about designing each class and it's reponsibilty.
    thanking u and looking forward for your help,
    sincerely
    RK

    yes i do know that........but can u ppl pls mention
    atleast what classes shud i consider and what will be
    the functions of each class?No, sorry. Maybe somebody else will, but in general, this is not a good question for this forum. It's too broad, and the question you're asking is an overall problem solving approach that you should be familiar with at this point.
    These forums are best suited to more specific questions. "How do I approach this homework?" is not something that most people are willing or able to answer in a forum like this.

  • New to JAVA, but old school to programming

    Objects & Classes & Methods, Oh my!
    I'm pretty new to java, but I've been programming in several languages over the years. I thought it was about time to update my skill set, especially with the job market as it is today. I wanted to go JAVA because it's not specific to any environment.
    I picked up a begining JAVA book and was a little confused. When I was learning programming a program was called a program. a peice of code in a program called by a statement was called a subroutine (it was performed then control returned to the calling line and continued).
    Now I'm trying to make sense of everything I have read so far and trying to relate it back to my old school of thinking. I was hoping it would make it easier to retain and I could expand it as I learn and possibly realize that it IS different. I know it's a new way of thinking, but stay with me for minute.
    What I used to call a program is now a CLASS in JAVA (this can be a collection of code or other objects). A sub-routine in a CLASS is a Method. I know that the language part will come as I use it since I understand if's then's and whatever you use to gosub or goto, but I want to make sure I have down the lingo before I go to deep.

    I have no idea how you can compare Java to Cobol.
    DataFlex? How about that! In about '84 I switched to
    DataFlex from dBaseII. In '91 DataFlex changed from
    procedural to OOP. It took most of us at least a year
    to adjust, and then some to write concrete code. It
    was tough. They had bugs and we were limited with DOS.
    BUT, it was a great OOP training experience. Anyhow,
    needless to day Java is miles ahead on all fronts.Small world. I was stuck in the old DataFlex Ver 2.3 at that time. The company I worked for had the newer OOP package. I did get to work with it some, but not enough to become totally familiar with it. We started to move out of DataFlex towards PowerBuilder towards the end of 1995. I did get some OOP from that experience, but again only enough to learn about global variables, instance variables, and a few other items. I hoping that I will be able to get the solid OOP background that I need from JAVA since I hear through the grapevine that it may be a new tool that we will be looking at to enhance our programming. I was looking at PERL but even the PERL programmers we have agree that JAVA is more scalable.

Maybe you are looking for