HTML in JLabel

Hi everybody. I've a strange problem with the Swing application I'm writing: I'm using JLabels to display some html code because i need special character formats (superscript/subscript).
Now when I use:
jLabel1.setText("<html>0,12m<sup>2</sup></html>")in the jLabel "0,12" becomes "0.12"; while when I cut out the <sup> part:
jLabel1.setText("<html>0,12m</html>")I get the correct display of "0,12".
How come this is happening?
Thanks in advance for your help.
Edited by: NeedForSpeed73 on Nov 25, 2008 11:07 AM

It works for me using 1.5.0_14. I tried the String in both the constructor, and in setText(...)
import java.awt.*;
import javax.swing.*;
public class SwingTest extends JFrame
  public SwingTest()
    String html = "<html>0,12m<sup>2</sup></html>";
    JLabel label1 = new JLabel(html);
    JLabel label2 = new JLabel();
    label2.setText(html);
    JPanel p = new JPanel(new GridLayout(0,1));
    p.add(label1);
    p.add(label2);
    add(p);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    pack();
    setLocationRelativeTo(null);
    setVisible(true);
  public static void main(String[] args)
    SwingTest sw = new SwingTest();
}

Similar Messages

  • Java L&F: html on jlabel *always* bold

    I'm trying to use HTML with a JLabel that is serving as a JTable cell editor. The UI default for the table and its cell renderers in the Java L&F (as well as most other L&Fs) is NOT bold.
    Is there some way to use HTML and not have it rendered as bold with the Java look and feel? I do not understand this behavior, bold should only happen when rendering HTML if the bold tag is used.
    JDK in use is 1.4.2.
    Thx

    Oh geez. You can tell it is late. My renderer doesn't actually extend JLabel, the JLabel is a private member, yet I was doing a "this.setFont()" to set a non-bold font before rendering the HTML to the label.
    Sorry for the bonehead post.

  • Html on Jlabel font size varies

    Hi,
    I am trying to put html text on JLabel with different font sizes. The font size reflected on JLabel is different from the font size on swing components. eg. Font size xx large on JLabel with html is looking very different from font size xx large on Just JLabel.
    Please help.
    Thanks

    I am using the Theme 14 - Modern.
    Below is a code snippet.
         <td class="t14data" headers="PAGE_REGION1_DATA">
             <h2><font face="Arial" color="#ff0000"><strong>This is Home Region 1</strong></font></h2>
          </td>
         <td class="t14data" headers="PAGE_REGION2_DATA">  
            <p><font><font face="Comic Sans MS"><font color="#ff00ff">This is Home Region 2</font><br /></font></font></p>
         </td>
         <td class="t14data" headers="PAGE_REGION1_DATA">
              <font><font face="Comic Sans MS"><font size="5">This is Process Region 1<br/></font></font></font>
         </td>
         <td class="t14data" headers="PAGE_REGION3_DATA">
            <div align="center"><font><font face="Comic Sans MS">This is Home Region 3</font></font><br/>
            <font><font face="Comic Sans MS"> </font></font></div>
         </td>With all the above code, only the font color & <strong> is rendered.
    Rest of the html formatting are ignored.
    Thanks
    Edited by: snagaraj on Aug 25, 2009 12:54 AM
    Edited by: snagaraj on Aug 25, 2009 12:55 AM
    Edited by: snagaraj on Aug 25, 2009 1:33 PM

  • Html on JLabel

    I tried to put a html text on JLabel. The JLabel displays the text on two lines, which I don't want. How do I avoid the text from going on to the second line. I want the text to be on one line even if the whole content is not shown.

    this is what i did previously..
    JPanel lblPanel = new JPanel(new BorderLayout());
    lblPanel.setBackground(Color.white);
    lblPanel.setSize(100,100);
    lblPanel.add(new JLabel("all your HTML"));
    add a new lblPanel @ your JLabel place

  • Chinese fonts in html not showing up properly sometimes

    I have the following lines in my program :
    JLabel A_Label=new JLabel("<Html><Font Size=3>\u8F93\u5165</Font></Html>");
    JPanel A_Panel=new Jpanel();
    A_Panel.add(A_Label);
    Sometimes the Chinese shows up correctly, but sometimes it shows up as blank rectangles, if I change the font size to 5, it will always show up, why ? How can I make it always show up in size 3 font ?
    Frank

    Hi, thanks for replying.
    I know it works for JLabel without html, but I need to display a lot of information in the label, there are formatted tables, different size fonts, html input fields, etc. , so my only choice is to use html to format them.
    I found it has something to do with the power of the PC running it, isn't it strange ? When the program starts, it needs to initialize, takes a while, from a few seconds to half a minute, sometimes if it didn't have a lot of data to load, the fonts shows up correctly, other times when it takes a while to load a lot of data before it displays the html formatted JLabel, the fonts may not all show up correctly. Size 5 always shows up correctly, the size 3 & 4 font sometimes could show up as blank rectangles.
    I wonder if there is anything I can do in my program to stabilize this when I use html in JLabel ?
    Frank

  • Html in labels / hot links

    hi! i want to know the restrictions if using html in labels? is the standard stricly defined or is it platform dependend like the differences when displaying webpages in different browsers?
    1.
    - does it have to include the html, head, and body tags?
    - does it have to be in xhtml standard?
    - is javascript allowed (or other scripts)?
    - can i use stylesheets?
    - can i embed applets? (an applet in an applet - how funny)
    - frames?
    2.
    is there another way to display hot links in an aboutbox?

    i cannot answer all questions. but i would like to share my experience to use html in JLabels. my Java enviornment is SDK1.4.0.01. I tried some tags in my labels. I used some tags that work as below:
    <html>
    <B>bold</B>
    <P>line return
    </html>
    I also tested some CSS properties like font-size, font-color which do not work. So it seems not to support all HTML functions.
    In all, I suggest you to test the tags when you want to use them.

  • Address book .... importing text file

    I am designing an address book which opens a text file called AddressBook.txt which reads in the information in the following format:
    lastname,firstname,street,city,state,zip,phonenumber,birthday,persontype
    lastname2,firstname2,street2,city2,state2,zip2,phonenumber2,birthday2,persontype2
    etc. (with a maximum entries of 500)
    I am having a problem reading in the information without the commas and wrapping to the next line. I can either use the BufferedReader or Scanner to input the file and as you can see below, my code is not complete yet. I can't figure out how to code the storeAddress() method in order to get the addressBookEntries[] to include the necessary information for outputting, sorting, etc. If I can get the information read into the addressBookEntries[], I think I will probably be able to proceed in the rest of the required tasks (i.e. sorting by last name, searching by last name, etc.)
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    import java.util.*;
    import java.text.SimpleDateFormat;
    import java.io.*;
    import java.lang.*;
    *  @created September 14, 2004
    *  This program uses a JFrame to manipulate data and form an
    *  address book.  The user will be able to load data from a file,
    *  sort it by last name, print the address, phone number, and date
    *  of birth, print the names of people whos birthday are between 2
    *  dates, print the names of people between 2 last names, and/or
    *  print the names of different person types.
    public class AddressBook extends JPanel implements ActionListener{
        JFrame frame;
        final int numButtons = 7;
        JRadioButton[] radioButtons = new JRadioButton[numButtons];
        JButton process = new JButton("Process Request");
        JLabel title;
        JTextArea output = new JTextArea(30,50);
        int MAX_ADDRESS_ENTRIES = 500;
        AddressBookEntry addressBookEntries[] =
            new AddressBookEntry[MAX_ADDRESS_ENTRIES];
        String FILE_NAME="AddressBook.txt";
        public AddressBook(JFrame frame){
            super(new BorderLayout());
            this.frame=frame;
            JPanel choicePanel = createSimpleDialogBox();
            choicePanel.setBorder(BorderFactory.createTitledBorder("Choices" +
            " to choose from:"));
            title = new JLabel("<html><h2> Thank you for opening the " +
            "Address Book.  " +
            "Please Press the \"Process Request\" " +
            "after making a choice.</h2></html>\n",JLabel.CENTER);
            title.setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
            output.setEditable(false);
            add(title, BorderLayout.NORTH);
            add(choicePanel, BorderLayout.CENTER);
            add(output, BorderLayout.SOUTH);
            final ButtonGroup group = new ButtonGroup();
            final String saveCommand = "Save";
            final String sortByLN = "Sort by Last Name";
            final String searchLNCommand = "Search By Last Name";
            final String printAPD = "Print address, phone number, and DOB";
            final String printNamesDOB = "Print names of people whose birthday" +
            " falls between 2 dates";
            final String printNamesLN = "Print names of people who fall" +
            " between 2 last names";
            final String printPType = "Print all family members, friends, or" +
            " business associates";
        private JPanel createSimpleDialogBox(){
            radioButtons[0] = new JRadioButton(
              "<html>Save the address file</html>");
            radioButtons[0].setActionCommand(saveCommand);
            radioButtons[1] = new JRadioButton(
              "<html>Sort the address file by last name</html>");
            radioButtons[1].setActionCommand(sortByLN);
            radioButtons[2] = new JRadioButton(
              "<html>Search the address file by last name</html>");
            radioButtons[2].setActionCommand(searchLNCommand);
            radioButtons[3] = new JRadioButton(
              "<html>Print the address, phone number, and DOB of a specified" +
              " person</html>");
            radioButtons[3].setActionCommand(printAPD);
            radioButtons[4] = new JRadioButton(
              "<html>Print the names of people whose birthday falls between" +
              " two dates</html>");
            radioButtons[4].setActionCommand(printNamesDOB);
            radioButtons[5] = new JRadioButton(
              "<html>Print the names of people who fall between two" +
              " specified last names</html>");
            radioButtons[5].setActionCommand(printNamesLN);
            radioButtons[6] = new JRadioButton(
              "<html>Print all family members, friends, <u>OR</u>" +
              " business associates</html>");
            radioButtons[6].setActionCommand(printPType);
            for (int i=0; i<numButtons; i++){
                group.add(radioButtons);
    //set the first button (open file) to be selected
    radioButtons[0].setSelected(true);
    return createPane(radioButtons, process);
    private JPanel createPane(JRadioButton[] radioButtons,
    JButton showButton) {
    int numChoices = radioButtons.length;
    JPanel box = new JPanel();
    box.setLayout(new BoxLayout(box, BoxLayout.PAGE_AXIS));
    for (int i = 0; i < numChoices; i++) {
    box.add(radioButtons[i]);
    JPanel pane = new JPanel(new BorderLayout());
    pane.add(box, BorderLayout.NORTH);
    pane.add(showButton, BorderLayout.SOUTH);
    return pane;
    public void actionPerformed(ActionEvent e) {
    String command = group.getSelection().getActionCommand();
    //else if button pushed is save
    if (command == saveCommand){
    // save file
    //else if button pushed is search by last name
    else if (command == sortByLN){
    // search by last name
    //else if button pushed is sort by last name
    else if (command == searchLNCommand){
    // sort by last name
    // print to screen
    //else if button pushed is display address, ph#, dob
    else if (command == printAPD){
    // display "search by last name" dialog
    // search last names
    // if last name found
    // print data
    // else
    // print error notification "person not found"
    //else if button pushed is list names of people whose
    //bday between 2 days
    else if (command == printNamesDOB){
    // ask for which dates
    // search bday
    // print to screen
    //else if button pushed is print names of people between 2 last names
    else if (command == printNamesDOB){
    // ask for which two last names
    // search last names
    // if people found
    // print to screen
    //else
    //print error notification "no one found"
    //else if button pushed is print all family members, friends
    //or business associates
    else if (command == printPType){
    //ask for what person type
    //search person types
    //if people found
    //print to screen
    //else print "no one found"
    public void storeAddress(File addressFile){
         Scanner sc=null;
    String lname,fname,street,city,state,zip,phone,persontype,bday;
    try {
    // Delimiters specifiy where to parse tokens in a scanner
    sc = new Scanner(addressFile).useDelimiter("\\s*[\\p{,}*\\s+]\\s*");
    catch (FileNotFoundException fnfe) {
         JOptionPane.showMessageDialog(this,"Could not open the file");
    System.exit(-1);
    for(int i=0; i<MAX_ADDRESS_ENTRIES; i++){
         while (sc.hasNext()) {
    lname=(sc.next());
         if (!lname.equals("")){
         addressBookEntries[i].setLName()=lname;
    public class AddressBookEntry{
    private extPerson address;
    private String date;
    private extPerson ExtPerson;
    public class Person{
    protected String lastName, firstName;
    private String address;
    private String city;
    private String state;
    private String zipcode;
    private String homephone;
    private String extPersonType;
    private Date bday;
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-mm-DD");
    public String toString() {
    return lastName+" "+firstName;
    public void setLName(String last) {
    lastName=last;
    public void setFName(String first){
    firstName=first;
    public String getLastName() {
    return lastName;
    public String getFirstName() {
    return lastName;
    public Person() {
    lastName="";
    firstName="";
    public Person(String first, String last){
    setLName(last);
    setFName(first);
    //Set the address and return it
    public void setAddress( String addr ){
    address = addr;
    public String getAddress(){
    return address;
    //set the city and return it
    public void setCity( String town ){
    city = town;
    public String getCity(){
    return city;
    //set the state and return it
    public void setState( String st )
    state = st;
    public String getState()
    return state;
    //Set the zip code and return it
    public void setZipCode( String zip ){
    zipcode = zip;
    public String getZipCode(){
    return zipcode;
    //Set the home phone and return it
    public void setHomePhone( String homeph ){
    homephone = homeph;
    public String getHomePhone(){
    return homephone;
    //Set the bday and return it
    public Date getBday(){
    return bday;
    public void setBday(Date newBday) {
    bday = newBday;
    dateFormat.format(bday);
    //Set the extPerson type and return it
    public String getPType(){
    return extPersonType;
    public void setPBusiness(){
    extPersonType = "Business Associate";
    public void setPFamily(){
    extPersonType = "Family Member";
    public void setPFriend(){
    extPersonType = "Friend";
    public class extPerson extends Person{
    //new clss People
    public class People {
         int MAX_PEOPLE=500;
         BufferedReader bf;
    public String toString() {
              StringBuffer sb=new StringBuffer();
              for (int i=0; i<nPeople; i++)
              sb=sb.append(group[i]+"\n");
              return sb.toString();
    public void read(){
              String str;
              try {
              bf=new BufferedReader(new FileReader(new File(FILE_NAME)));
              str=bf.readLine();
              while (str!=null) {
              insert(str);
                   str=bf.readLine();
         catch (IOException e) {
              // Will jump to here on an eof condition.
         try {
              bf.close();
         catch (IOException e) {}
         public void save() {
              try {
              PrintWriter pw=new PrintWriter(FILE_NAME);
              for (int i=0; i<nPeople; i++)
              pw.println(group[i]+",");
              pw.close();
         catch (FileNotFoundException fne) {
                   System.out.println("Could not Save "+FILE_NAME);
    public People() {
              group=new extPerson[MAX_PEOPLE];
              nPeople=0;
         public boolean insert(String data) {
              if (nPeople<MAX_PEOPLE) {
              //extPerson guy=new extPerson(data);
              //group[nPeople]=guy;
              nPeople++;
              return true;
         else {
         JOptionPane.showMessageDialog(null,"Error in People" +
    "::insert: Max size reached.");
         return false;
         public void clear() {
              // This loop frees up the memory used by each extPerson
              for (int i=0; i<nPeople; i++)
              group[i]=null;
              nPeople=0;
    extPerson group[];
    int nPeople;
    * Create the GUI and show it. For thread safety,
    * this method should be invoked from the
    * event-dispatching thread.
    public static void createAndShowGUI(){
    JFrame.setDefaultLookAndFeelDecorated(true);
    JDialog.setDefaultLookAndFeelDecorated(true);
    JFrame frame = new JFrame("Address Book Program");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container c = frame.getContentPane();
    c.add(new AddressBook(frame));
    frame.pack();
    frame.setVisible(true);
    public static void main (String s[]){       
    //Schedule a job for the event-dispatching thread:
    //creating and showign this application's GUI
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();

    Ok, I have changed my code to reflect your suggested changes, but I'm still unsure how to use the findInLine you suggested.... This is all very new to me and I've been looking on the java website for suggestions, but I'm still stumped on how to pull this together. I'm unsure on how to set the lastname,firstname,etc. for retrieval...
    Here's my code:
    //ADDRESS BOOK
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    import java.util.*;
    import java.text.SimpleDateFormat;
    import java.io.*;
    import java.lang.*;
    *  @created September 14, 2004
    *  This program uses a JFrame to manipulate data and form an
    *  address book.  The user will be able to load data from a file,
    *  sort it by last name, print the address, phone number, and date
    *  of birth, print the names of people whos birthday are between 2
    *  dates, print the names of people between 2 last names, and/or
    *  print the names of different person types.
    public class AddressBook extends JPanel implements ActionListener{
        JFrame frame;
        final int numButtons = 7;
        JRadioButton[] radioButtons = new JRadioButton[numButtons];
        JButton process = new JButton("Process Request");
        JLabel title;
        JTextArea output = new JTextArea(30,50);
        int MAX_ADDRESS_ENTRIES = 500;
        AddressBookEntry addressBookEntries[] = new
        AddressBookEntry[MAX_ADDRESS_ENTRIES];
        public AddressBook(JFrame frame){
            super(new BorderLayout());
            this.frame=frame;
            JPanel choicePanel = createSimpleDialogBox();
            choicePanel.setBorder(BorderFactory.createTitledBorder("Choices" +
            " to choose from:"));
            title = new JLabel("<html><h2> Thank you for opening the " +
            "Address Book.  " +
            "Please Press the \"Process Request\" " +
            "after making a choice.</h2></html>\n",JLabel.CENTER);
            title.setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
            output.setEditable(false);
            add(title, BorderLayout.NORTH);
            add(choicePanel, BorderLayout.CENTER);
            add(output, BorderLayout.SOUTH);
            final ButtonGroup group = new ButtonGroup();
            final String saveCommand = "Save";
            final String sortByLN = "Sort by Last Name";
            final String searchLNCommand = "Search By Last Name";
            final String printAPD = "Print address, phone number, and DOB";
            final String printNamesDOB = "Print names of people whose birthday" +
            " falls between 2 dates";
            final String printNamesLN = "Print names of people who fall" +
            " between 2 last names";
            final String printPType = "Print all family members, friends, or" +
            " business associates";
        private JPanel createSimpleDialogBox(){
            radioButtons[0] = new JRadioButton(
              "<html>Save the address file</html>");
            radioButtons[0].setActionCommand(saveCommand);
            radioButtons[1] = new JRadioButton(
              "<html>Sort the address file by last name</html>");
            radioButtons[1].setActionCommand(sortByLN);
            radioButtons[2] = new JRadioButton(
              "<html>Search the address file by last name</html>");
            radioButtons[2].setActionCommand(searchLNCommand);
            radioButtons[3] = new JRadioButton(
              "<html>Print the address, phone number, and DOB of a specified" +
              " person</html>");
            radioButtons[3].setActionCommand(printAPD);
            radioButtons[4] = new JRadioButton(
              "<html>Print the names of people whose birthday falls between" +
              " two dates</html>");
            radioButtons[4].setActionCommand(printNamesDOB);
            radioButtons[5] = new JRadioButton(
              "<html>Print the names of people who fall between two" +
              " specified last names</html>");
            radioButtons[5].setActionCommand(printNamesLN);
            radioButtons[6] = new JRadioButton(
              "<html>Print all family members, friends, <u>OR</u>" +
              " business associates</html>");
            radioButtons[6].setActionCommand(printPType);
            for (int i=0; i<numButtons; i++){
                group.add(radioButtons);
    //set the first button (open file) to be selected
    radioButtons[0].setSelected(true);
    return createPane(radioButtons, process);
    private JPanel createPane(JRadioButton[] radioButtons,
    JButton showButton) {
    int numChoices = radioButtons.length;
    JPanel box = new JPanel();
    box.setLayout(new BoxLayout(box, BoxLayout.PAGE_AXIS));
    for (int i = 0; i < numChoices; i++) {
    box.add(radioButtons[i]);
    JPanel pane = new JPanel(new BorderLayout());
    pane.add(box, BorderLayout.NORTH);
    pane.add(showButton, BorderLayout.SOUTH);
    return pane;
    public void actionPerformed(ActionEvent e) {
    String command = group.getSelection().getActionCommand();
    //else if button pushed is save
    if (command == saveCommand){
    // save file
    //else if button pushed is search by last name
    else if (command == sortByLN){
    // search by last name
    //else if button pushed is sort by last name
    else if (command == searchLNCommand){
    // sort by last name
    // print to screen
    //else if button pushed is display address, ph#, dob
    else if (command == printAPD){
    // display "search by last name" dialog
    // search last names
    // if last name found
    // print data
    // else
    // print error notification "person not found"
    //else if button pushed is list names of people whose
    //bday between 2 days
    else if (command == printNamesDOB){
    // ask for which dates
    // search bday
    // print to screen
    //else if button pushed is print names of people between 2 last names
    else if (command == printNamesDOB){
    // ask for which two last names
    // search last names
    // if people found
    // print to screen
    //else
    //print error notification "no one found"
    //else if button pushed is print all family members, friends
    //or business associates
    else if (command == printPType){
    //ask for what person type
    //search person types
    //if people found
    //print to screen
    //else print "no one found"
    public class AddressBookEntry{
    private extPerson address;
    private String date;
    private extPerson ExtPerson;
    * Create the GUI and show it. For thread safety,
    * this method should be invoked from the
    * event-dispatching thread.
    public static void createAndShowGUI(){
    JFrame.setDefaultLookAndFeelDecorated(true);
    JDialog.setDefaultLookAndFeelDecorated(true);
    JFrame frame = new JFrame("Address Book Program");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container c = frame.getContentPane();
    c.add(new AddressBook(frame));
    frame.pack();
    frame.setVisible(true);
    public static void main (String s[]){       
    //Schedule a job for the event-dispatching thread:
    //creating and showign this application's GUI
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();
    //PERSON
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    import java.util.*;
    import java.text.SimpleDateFormat;
    import java.io.*;
    import java.lang.*;
    public class Person{
    protected String lastName, firstName;
    private String address;
    private String city;
    private String state;
    private String zipcode;
    private String homephone;
    private String extPersonType;
    private String bday;
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-mm-DD");
    public void parseString(String s) {
              try {
              lastName = s.substring(0,s.indexOf(","));
              firstName = s.substring(s.indexOf(",")+1);
    address = s.substring(s.indexOf(",")+2);
    city = s.substring(s.indexOf(",")+3);
    state = s.substring(s.indexOf(",")+4);
    zipcode = s.substring(s.indexOf(",")+5);
    homephone = s.substring(s.indexOf(",")+6);
    extPersonType = s.substring(s.indexOf(",")+7);
    bday = s.substring(s.indexOf(",")+8);
    catch(StringIndexOutOfBoundsException sbe) {
              JOptionPane.showMessageDialog(null,"Error " +
    "in Person: Could not parse the line "+s);
    public String toString() {
    return lastName+","+firstName+","+address+","+city+","+
    state+","+zipcode+","+homephone+","+bday+","+extPersonType;
    public void setLName(String last) {
    lastName=last;
    public void setFName(String first){
    firstName=first;
    public String getLastName() {
    return lastName;
    public String getFirstName() {
    return lastName;
    public Person() {
    lastName="";
    firstName="";
    public Person(String first, String last){
    setLName(last);
    setFName(first);
    //Set the address and return it
    public void setAddress( String addr ){
    address = addr;
    public String getAddress(){
    return address;
    //set the city and return it
    public void setCity( String town ){
    city = town;
    public String getCity(){
    return city;
    //set the state and return it
    public void setState( String st )
    state = st;
    public String getState()
    return state;
    //Set the zip code and return it
    public void setZipCode( String zip ){
    zipcode = zip;
    public String getZipCode(){
    return zipcode;
    //Set the home phone and return it
    public void setHomePhone( String homeph ){
    homephone = homeph;
    public String getHomePhone(){
    return homephone;
    //Set the bday and return it
    public String getBday(){
    return bday;
    public void setBday(String newBday) {
    bday = newBday;
    dateFormat.format(bday);
    //Set the extPerson type and return it
    public String getPType(){
    return extPersonType;
    public void setPBusiness(){
    extPersonType = "Business Associate";
    public void setPFamily(){
    extPersonType = "Family Member";
    public void setPFriend(){
    extPersonType = "Friend";
    public Person(String data) {
    parseString(data);
    //EXTPERSON
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    import java.util.*;
    import java.text.SimpleDateFormat;
    import java.io.*;
    import java.lang.*;
    //new clss extPerson
    public class extPerson extends Person {       
         int MAX_PEOPLE=500;
         BufferedReader bf;
    String lname,fname,street,city,state,zip,phone,persontype,bday;
    String FILE_NAME="AddressBook.txt";
    public String toString() {
              StringBuffer sb=new StringBuffer();
              for (int i=0; i<nPeople; i++)
              sb=sb.append(group1[i]+"\n");
              return sb.toString();
         public void save() {
              try {
              PrintWriter pw=new PrintWriter(FILE_NAME);
              for (int i=0; i<nPeople; i++)
              pw.println(group1[i]+",");
              pw.close();
         catch (FileNotFoundException fne) {
                   System.out.println("Could not Save "+FILE_NAME);
    public extPerson() {
              group1=new extPerson[MAX_PEOPLE];
              nPeople=0;
         public boolean insert(String data) {
              if (nPeople<MAX_PEOPLE) {
              Person guy = new Person(data);
              group1[nPeople]=guy;
              nPeople++;
              return true;
         else {
         JOptionPane.showMessageDialog(null,"Error in People" +
    "::insert: Max size reached.");
         return false;
    Person group1[];
    int nPeople;

  • How can I see   more than one text line?

    Can anyone help me??
    I know to write more than one line in a HstaticText with the following code
    label = new HStaticText("This is some text.  It's a fairly long " +
                                    "\npiece of text that should show \nword wrapping on most " +
                                    "receivers.\nMultiple lines of text are\n supported " +
                                    "by the text layout\n manager if them are\n separated " +
                                    "by a \\n", 0,0, 600, 600, new Font("Tiresias", Font.BOLD, 30), Color.blue, colors[0], new HDefaultTextLayoutManager());but when I have tried the following code and I can�t.
    private String texto="Pulse cualquier bot�n. \n para averiguar su Keycode";
    g.drawString(texto,x_pos,y_pos);     // Graphics gPlease help me!

    Graphics.drawString() doesn't format the text into lines based on embedded linefeeds. You have to split the text into lines yourself and use multiple drawStrng() calls, giving it the correct starting location each time. This "HstaticString" class is obviously doing that for you behind the scenes. If you want to draw multiline text without using an HstaticString, I suggest using either a JTextArea, or a JLabel with HTML text:  JLabel lbl = new JLabel("<html>Pulse cualquier bot�n.<br><br>para averiguar su Keycode</html>");

  • Rendering a carriage return

    I have an issue, in which the user can enter text in to a textfield on a dialog box, when closing the dialog the text is saved and displayed in a JTable. The problem I am having is that if the user uses the carriage return to to format their text - a box is displayed for each carriage return. Is there any way to look for those carriage returns in the renderer and not display them?
    thanks
    example:
    "test" is entered by the user followed by 3 carriage returns
    "test[][][]" - is displayed

    A few of the graphical components that explicitly just draws the text, will not paint anything else than the famous square for unprintable characters. Unprintable characters has the value < 32 and 127 and there might be others in the big unicode that I do not know about. Recommended here is to use Character.isLetter() ensure that it is a printable character.
    This does not visualise itself when printed to the console for example, because the shell will interpret the unprintable character to whatever it should be. So \n will become a carriage return and a \g (hmmm... just got a bit unsure if this works in java, anyway printing ascii 7 if \g does not work) would produce a beep.
    Solution:
    Make sure that the component handles the unprintable characters correctly, either by ignoring them or by interpreting them and paint accordingly.
    Hack:
    A few of the components supporting HTML, like JLabel, can become multilined if \n is replaced with HTML and the newlines offcourse are replaced with HTML newlines (<br> or <p> for paragraphs).
    Regards,
    Peter Norell

  • Chinese fonts not showing up properly sometimes

    I have the following lines in my program :
    JLabel A_Label=new JLabel("<Html><Font Size=3>\u8F93\u5165</Font></Html>");
    JPanel A_Panel=new Jpanel();
    A_Panel.add(A_Label);Sometimes the Chinese shows up correctly, but sometimes it shows up as blank rectangles, if I change the font size to 5, it will always show up, why ? How can I make it always show up in size 3 font ?
    Frank

    Hi, thanks for replying.
    I know it works for JLabel without html, but I need to display a lot of information in the label, there are formatted tables, different size fonts, html input fields, etc. , so my only choice is to use html to format them.
    I found it has something to do with the power of the PC running it, isn't it strange ? When the program starts, it needs to initialize, takes a while, from a few seconds to half a minute, sometimes if it didn't have a lot of data to load, the fonts shows up correctly, other times when it takes a while to load a lot of data before it displays the html formatted JLabel, the fonts may not all show up correctly. Size 5 always shows up correctly, the size 3 & 4 font sometimes could show up as blank rectangles.
    I wonder if there is anything I can do in my program to stabilize this when I use html in JLabel ?
    Frank

  • Swings with servlets

    Hi,
    how we can use swings with servlets or jsps.
    or
    how we can display the browser in the swings.
    please give me a valid answer with examples.

    Hi,
    Your question is not clear... are you trying to display HTML using swing components or are you trying to use swing in a server-side application?
    Some Swing components (e.g. JLabel) natively support simple html, so:
    JLabel lbl = new JLabel("<html>hello <b>world</b></html>");would result in a JLabel that looks with the word "world" in bold. If you need also frames, css and javascript support - you'll need to reach for a 3^rd^ party library, I'm afraid.
    As for using swing in servers, look at this article:
    http://today.java.net/pub/a/today/2006/04/20/bringing-swing-to-the-web.html
    If you meant neither, please explain more.
    Hope this helps, though.
    Michael Bar-Sinai

  • Aligning text in a JtextPane

    I am trying to display text in a JTextPane. I want to be able to change the background color, the foreground color and the border (color and width). Furthermore, I need multiple lines of text, and later I might want to change the font too. The text need not be editable. All this works ok with a JTextPane, except the alignment of the text. The text is always left-aligned. So the question is: what can I do to center the text in a JTextPane?
    Thanx in advance.

    Try somthing like this then
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    public class TestHTMLLabel {
    public static void main(String[] args) {
    JFrame frame= new JFrame("HTML Label");
    JLabel lbl = new JLabel("<html><p align=\"left\"><B>Thanx</B> for the reply, but I am really looking for a much simpler solution. Let me rephrase my question: I want to display a rectangular area on the screen that displays wrapped text within that rectangle. I also want to be able to change the colors (<font color=\"red\">foreground</font> and background) and the border (width, color and style). The text need not be editable<p></html> ");
    frame.getContentPane().add(lbl);
    frame.setSize(300,300);
    frame.show();
    Goodluck...

  • Connecting view button to player! help

    hi! I have posted my codes for Client and ClientChoice.
    in the actionlistener event of the ClientChoice(gui) have i have called the Client class where the player is found and where connection is made to the server. the error i get is that the .class of the Client is:
    mainCl(java.lang.String[]) in Client cannot be applied to (java.lang.String,java.lang.String)          cl.mainCl(a,b);
    can anyone help me ! am i doing the right thing or someway else plz help me......i have a week on that and i'm being late. here are the code:
    //Client.java
    //package ana;
    import java.io.*;
    import java.awt.*;
    import java.net.*;
    import java.awt.event.*;
    import java.util.Vector;
    import javax.media.*;
    import javax.media.rtp.*;
    import javax.media.rtp.event.*;
    import javax.media.rtp.rtcp.*;
    import javax.media.protocol.*;
    import javax.media.protocol.DataSource;
    import javax.media.format.AudioFormat;
    import javax.media.format.VideoFormat;
    import javax.media.Format;
    import javax.media.format.FormatChangeEvent;
    import javax.media.control.BufferControl;
    * Client to receive RTP transmission using the RTPConnector.
    public class Client implements ReceiveStreamListener, SessionListener,
         ControllerListener
    String sessions[] = null;
    RTPManager mgrs[] = null;
    Vector playerWindows = null;
    boolean dataReceived = false;
    Object dataSync = new Object();
    public Client(String sessions[]) {
         this.sessions = sessions;
    public Client(String a, String b)
         }//constructor
    protected boolean initialize() {
    try {
         mgrs = new RTPManager[sessions.length];
         playerWindows = new Vector();
         SessionLabel session;
         // Open the RTP sessions.
         for (int i = 0; i < sessions.length; i++) {
              // Parse the session addresses.
              try {
              session = new SessionLabel(sessions);
              } catch (IllegalArgumentException e) {
              System.err.println("Failed to parse the session address given: " + sessions[i]);
              return false;
              System.err.println(" - Open RTP session for: addr: " + session.addr + " port: " + session.port + " ttl: " + session.ttl);
              mgrs[i] = (RTPManager) RTPManager.newInstance();
              mgrs[i].addSessionListener(this);
              mgrs[i].addReceiveStreamListener(this);
              // Initialize the RTPManager with the RTPSocketAdapter
              mgrs[i].initialize(new RTPSocketAdapter(
                             InetAddress.getByName(session.addr),
                             session.port, session.ttl));
              // You can try out some other buffer size to see
              // if you can get better smoothness.
              BufferControl bc = (BufferControl)mgrs[i].getControl("javax.media.control.BufferControl");
              if (bc != null)
              bc.setBufferLength(350);
    } catch (Exception e){
    System.err.println("Cannot create the RTP Session: " + e.getMessage());
    return false;
         // Wait for data to arrive before moving on.
         long then = System.currentTimeMillis();
         long waitingPeriod = 30000; // wait for a maximum of 30 secs.
         try{
         synchronized (dataSync) {
              while (!dataReceived &&
                   System.currentTimeMillis() - then < waitingPeriod) {
              if (!dataReceived)
                   System.err.println(" - Waiting for RTP data to arrive...");
              dataSync.wait(1000);
         } catch (Exception e) {}
         if (!dataReceived) {
         System.err.println("No RTP data was received.");
         close();
         return false;
    return true;
    public boolean isDone() {
         return playerWindows.size() == 0;
    * Close the players and the session managers.
    protected void close() {
         for (int i = 0; i < playerWindows.size(); i++) {
         try {
              ((PlayerWindow)playerWindows.elementAt(i)).close();
         } catch (Exception e) {}
         playerWindows.removeAllElements();
         // close the RTP session.
         for (int i = 0; i < mgrs.length; i++) {
         if (mgrs[i] != null) {
    mgrs[i].removeTargets( "Closing session from AVReceive3");
    mgrs[i].dispose();
              mgrs[i] = null;
    PlayerWindow find(Player p) {
         for (int i = 0; i < playerWindows.size(); i++) {
         PlayerWindow pw = (PlayerWindow)playerWindows.elementAt(i);
         if (pw.player == p)
              return pw;
         return null;
    PlayerWindow find(ReceiveStream strm) {
         for (int i = 0; i < playerWindows.size(); i++) {
         PlayerWindow pw = (PlayerWindow)playerWindows.elementAt(i);
         if (pw.stream == strm)
              return pw;
         return null;
    * SessionListener.
    public synchronized void update(SessionEvent evt) {
         if (evt instanceof NewParticipantEvent) {
         Participant p = ((NewParticipantEvent)evt).getParticipant();
         System.err.println(" - A new participant had just joined: " + p.getCNAME());
    * ReceiveStreamListener
    public synchronized void update( ReceiveStreamEvent evt) {
         RTPManager mgr = (RTPManager)evt.getSource();
         Participant participant = evt.getParticipant();     // could be null.
         ReceiveStream stream = evt.getReceiveStream(); // could be null.
         if (evt instanceof RemotePayloadChangeEvent) {
         System.err.println(" - Received an RTP PayloadChangeEvent.");
         System.err.println("Sorry, cannot handle payload change.");
         System.exit(0);
         else if (evt instanceof NewReceiveStreamEvent) {
         try {
              stream = ((NewReceiveStreamEvent)evt).getReceiveStream();
              DataSource ds = stream.getDataSource();
              // Find out the formats.
              RTPControl ctl = (RTPControl)ds.getControl("javax.media.rtp.RTPControl");
              if (ctl != null){
              System.err.println(" - Recevied new RTP stream: " + ctl.getFormat());
              } else
              System.err.println(" - Recevied new RTP stream");
              if (participant == null)
              System.err.println(" The sender of this stream had yet to be identified.");
              else {
              System.err.println(" The stream comes from: " + participant.getCNAME());
              // create a player by passing datasource to the Media Manager
              Player p = javax.media.Manager.createPlayer(ds);
              if (p == null)
              return;
              p.addControllerListener(this);
              p.realize();
              PlayerWindow pw = new PlayerWindow(p, stream);
              playerWindows.addElement(pw);
              // Notify intialize() that a new stream had arrived.
              synchronized (dataSync) {
              dataReceived = true;
              dataSync.notifyAll();
         } catch (Exception e) {
              System.err.println("NewReceiveStreamEvent exception " + e.getMessage());
              return;
         else if (evt instanceof StreamMappedEvent) {
         if (stream != null && stream.getDataSource() != null) {
              DataSource ds = stream.getDataSource();
              // Find out the formats.
              RTPControl ctl = (RTPControl)ds.getControl("javax.media.rtp.RTPControl");
              System.err.println(" - The previously unidentified stream ");
              if (ctl != null)
              System.err.println(" " + ctl.getFormat());
              System.err.println(" had now been identified as sent by: " + participant.getCNAME());
         else if (evt instanceof ByeEvent) {
         System.err.println(" - Got \"bye\" from: " + participant.getCNAME());
         PlayerWindow pw = find(stream);
         if (pw != null) {
              pw.close();
              playerWindows.removeElement(pw);
    * ControllerListener for the Players.
    public synchronized void controllerUpdate(ControllerEvent ce) {
         Player p = (Player)ce.getSourceController();
         if (p == null)
         return;
         // Get this when the internal players are realized.
         if (ce instanceof RealizeCompleteEvent) {
         PlayerWindow pw = find(p);
         if (pw == null) {
              // Some strange happened.
              System.err.println("Internal error!");
              System.exit(-1);
         pw.initialize();
         pw.setVisible(true);
         p.start();
         if (ce instanceof ControllerErrorEvent) {
         p.removeControllerListener(this);
         PlayerWindow pw = find(p);
         if (pw != null) {
              pw.close();
              playerWindows.removeElement(pw);
              //p.close(); //i added to know if player close when click
         System.err.println("Client internal error: " + ce);
    * A utility class to parse the session addresses.
    class SessionLabel {
         public String addr = null;
         public int port;
         public int ttl = 1;
         SessionLabel(String session) throws IllegalArgumentException {
         int off;
         String portStr = null, ttlStr = null;
         if (session != null && session.length() > 0) {
              while (session.length() > 1 && session.charAt(0) == '/')
              session = session.substring(1);
              // Now see if there's a addr specified.
              off = session.indexOf('/');
              if (off == -1) {
              if (!session.equals(""))
                   addr = session;
              } else {
              addr = session.substring(0, off);
              session = session.substring(off + 1);
              // Now see if there's a port specified
              off = session.indexOf('/');
              if (off == -1) {
                   if (!session.equals(""))
                   portStr = session;
              } else {
                   portStr = session.substring(0, off);
                   session = session.substring(off + 1);
                   // Now see if there's a ttl specified
                   off = session.indexOf('/');
                   if (off == -1) {
                   if (!session.equals(""))
                        ttlStr = session;
                   } else {
                   ttlStr = session.substring(0, off);
         if (addr == null)
              throw new IllegalArgumentException();
         if (portStr != null) {
              try {
              Integer integer = Integer.valueOf(portStr);
              if (integer != null)
                   port = integer.intValue();
              } catch (Throwable t) {
              throw new IllegalArgumentException();
         } else
              throw new IllegalArgumentException();
         if (ttlStr != null) {
              try {
              Integer integer = Integer.valueOf(ttlStr);
              if (integer != null)
                   ttl = integer.intValue();
              } catch (Throwable t) {
              throw new IllegalArgumentException();
    * GUI classes for the Player.
    class PlayerWindow extends Frame {
         Player player;
         ReceiveStream stream;
         PlayerWindow(Player p, ReceiveStream strm) {
         player = p;
         stream = strm;
         public void initialize() {
         add(new PlayerPanel(player));
         public void close() {
         player.close();
         setVisible(false);
         dispose();
         public void addNotify() {
         super.addNotify();
         pack();
    * GUI classes for the Player.
    class PlayerPanel extends Panel {
         Component vc, cc;
         PlayerPanel(Player p) {
         setLayout(new BorderLayout());
         if ((vc = p.getVisualComponent()) != null)
              add("Center", vc);
         if ((cc = p.getControlPanelComponent()) != null)
              add("South", cc);
         public Dimension getPreferredSize() {
         int w = 0, h = 0;
         if (vc != null) {
              Dimension size = vc.getPreferredSize();
              w = size.width;
              h = size.height;
         if (cc != null) {
              Dimension size = cc.getPreferredSize();
              if (w == 0)
              w = size.width;
              h += size.height;
         if (w < 160)
              w = 160;
         return new Dimension(w, h);
    public static void mainCl(String argv[])
         if (argv.length == 0)
         prUsage();
         Client avReceive = new Client(argv);
         if (!avReceive.initialize()) {
         System.err.println("Failed to initialize the sessions.");
         System.exit(-1);
         // Check to see if Client is done.
         try {
         while (!avReceive.isDone())
              Thread.sleep(1000);
         } catch (Exception e) {}
         System.err.println("Exiting Client");
    static void prUsage() {
         System.err.println("Usage: Client <session> <session> ...");
         System.err.println(" <session>: <address>/<port>/<ttl>");
         System.exit(0);
    }// end of Client
    //package ana;
    import javax.swing.*;
    import javax.swing.UIManager;
    import java.awt.*;
    import java.awt.event.*;
    public class ClientChoice
         public static void main(String args[])
              try
                             UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
                        catch(Exception e)
         }//main
         JFrame frame=new JFrame("--- New Line Movie ---");
         //Create the menu bar
         JMenuBar menuBar;
         JMenu menu;
         menuBar = new JMenuBar();
         //Build the file menu in the menu bar
         menu = new JMenu("File");
         menu.setMnemonic(KeyEvent.VK_F);
         menuBar.add(menu);
         JMenuItem menuItem= new JMenuItem("Exit",KeyEvent.VK_X);
         menuItem.addActionListener(new ActionListener()
              public void actionPerformed(ActionEvent e)
                        System.exit(0);
         menu.add(menuItem);
         //Build help menu in the menu bar.
         menu = new JMenu("Help");
         menu.setMnemonic(KeyEvent.VK_H);
         menuBar.add(menu);
         JMenuItem help_item=new JMenuItem("Help Topics",KeyEvent.VK_T);
         menu.add(help_item);
         JMenuItem about_item=new JMenuItem("About Us");
         menu.add(about_item);
         frame.setJMenuBar(menuBar);
              ImageIcon icon=new ImageIcon("images/potter.jpg","");
              JButton clickmovie=new JButton(icon);
              //final JLabel latest=new JLabel("<html><caption>Harry Potter</caption></html>");
              //clickmovie.add(latest);
              final JLabel welcome1=new JLabel("<html><font color=blue face=arial size=3><strong>New Line Movie</strong> gives you the possibility to view your favorite movies.<br>You can choose your category of movies below and click on any movie to get more information about it. <br>Latest News about new movies are also available. ENJOY!!!</font></html>");
              frame.getContentPane().add(welcome1,BorderLayout.EAST);
              final JLabel copyright=new JLabel("<html><font color=blue face=arial size=3><p align=center>&copy Copyright 2004</p></font></html>");
              //frame.getContentPane().add(copyright,BorderLayout.EAST);
              JPanel actionPanel=new JPanel();
              JPanel cartoonPanel=new JPanel();
              JPanel comedyPanel=new JPanel();
              JPanel fictionPanel=new JPanel();
              JPanel mainPanel=new JPanel();
              mainPanel.setLayout(new GridLayout(2,1,5,5));
              mainPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
              mainPanel.add(actionPanel);
              mainPanel.add(cartoonPanel);
              mainPanel.add(comedyPanel);
              mainPanel.add(fictionPanel);
              //mainPanel.add(copyright);
              actionPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Action"),BorderFactory.createEmptyBorder(5,5,5,5)));
              cartoonPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Cartoon"),BorderFactory.createEmptyBorder(5,5,5,5)));
              comedyPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Comedy"),BorderFactory.createEmptyBorder(5,5,5,5)));
              fictionPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Science Fiction"),BorderFactory.createEmptyBorder(5,5,5,5)));
              frame.getContentPane().add(mainPanel,BorderLayout.SOUTH);
              frame.getContentPane().add(clickmovie,BorderLayout.WEST);
              // Create combo box with action movies choices
              final JComboBox actionChoices;
              String[] actionmovie={"-Select a movie-","X-Men","Spiderman"};
              actionChoices=new JComboBox(actionmovie);
              actionChoices.setSelectedIndex(0);
              actionPanel.add(actionChoices);
              actionChoices.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        JComboBox cb = (JComboBox)e.getSource();
                        String act = (String)cb.getSelectedItem();
                        if(act=="X-Men")
                             JFrame action_xmen= new JFrame("--- New Line Movie: X-Men --- ");
                   action_xmen.setSize(400,350);
                   JPanel main=new JPanel();
                   main.setLayout(new GridLayout(2,1,5,5));
                             main.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
                             ImageIcon icon_men=new ImageIcon("images/x-men.jpg","");
                   JButton clickmovie_men=new JButton(icon_men);
                   final JLabel xmen_overview=new JLabel("<html><font color=blue face=arial size=3><b>Title:</b></font> <font color=black><strong>X-Men 2 </strong></font> <br><br><font color=blue face=arial size=3><b>Starring:</b> Hugh JACKMAN and Halle BARRY<br><br><b>Story:</b> The time has come for those who are different to stand united. <br><br>A military officer with a link to Wolverine's mysterious past conspires <br><br>to eradicate the mutant population for once and all. In order to defeat <br><br>this new menace, the X-men will be forced to join forces with Magneto. <br><br><b>Duration:</b> 1hr45min </font></html>");
                   final JLabel copyright=new JLabel("<html><font color=blue face=arial size=3><p align=center>&copy Copyright 2004</p></font></html>");
                             action_xmen.getContentPane().add(copyright,BorderLayout.SOUTH);
                   JButton view=new JButton("View");
                   view.setLayout(new BoxLayout(view,BoxLayout.X_AXIS));
                                            view.add(Box.createHorizontalGlue());
                             view.add(Box.createRigidArea(new Dimension(30,0)));
                   view.setMinimumSize(new Dimension(20,100));
                   view.setPreferredSize(new Dimension(20,100));
                   view.setMaximumSize(new Dimension(Short.MAX_VALUE,Short.MAX_VALUE));
                   view.setMnemonic('v');
                   view.addActionListener(new ActionListener()
                                  public void actionPerformed(ActionEvent e)
                                            String a="172.22.45.44/42050";
                                            String b="172.22.45.44/42052";
                                            String argv=a+b;
                                            Client cl= new Client(a,b);
                                            cl.mainCl(a,b);
                                            //this is the code i added so that on clicking the view button
                                            //the client is automatically connected to the server and the player
                                            //plays on the current machine
                   main.add(clickmovie_men);
                             main.add(view);
                             //action_xmen.getContentPane().add(view,BorderLayout.SOUTH);
                   action_xmen.getContentPane().add(main,BorderLayout.WEST);
                   action_xmen.getContentPane().add(xmen_overview,BorderLayout.EAST);
                   action_xmen.show();
                        else if(act=="Spiderman")
                             JFrame action_spider= new JFrame("--- New Line Movie: Spiderman --- ");
                             action_spider.setSize(400,350);
                   action_spider.show();
              //Create combo box with cartoon movies choices
              JComboBox cartoonChoices=null;
              String[] cartoonmovie={"-Select a movie-","Le Roi Lion"};
              cartoonChoices=new JComboBox(cartoonmovie);
              cartoonChoices.setSelectedIndex(0);
              cartoonPanel.add(cartoonChoices);
              //cartoonChoices.addActionListener();
              //Create combo box with comedy movies choices
              JComboBox comedyChoices=null;
              String[] comedymovie={"-Select a movie-"};
              comedyChoices=new JComboBox(comedymovie);
              comedyChoices.setSelectedIndex(0);
              comedyPanel.add(comedyChoices);
              //comedyChoices.addActionListener();
              //Create combo box with fiction movies choices
              JComboBox fictionChoices=null;
              String[] fictionmovie={"-Select a movie-","ET"};
              fictionChoices=new JComboBox(fictionmovie);
              fictionChoices.setSelectedIndex(0);
              fictionPanel.add(fictionChoices);
              //fictionChoices.addActionListener();
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.pack();
              frame.setVisible(true);
    //Implement player function here
    }//end of ClientChoice

    You are passing two String objects to a method that accepts an String array.
    try this to get rid of one error.
    Client cl = new Client(a, b);
    String[] c = {a,b};
    Client.mainCl(c);

  • Stopping the player at the client machine independent of the server playing

    can anyone help me i need to allow the client to stop a player independent of the server transmitting the movie. can anyone help me plz!!
    here are rhe codes for the client and the client gui
    import javax.swing.*;
    import javax.swing.UIManager;
    import java.awt.*;
    import java.awt.event.*;
    public class ClientChoice
         public static void main(String args[])
              try
                             UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
                        catch(Exception e)
         }//main
         JFrame frame=new JFrame("--- New Line Movie ---");
         //Create the menu bar
         JMenuBar menuBar;
         JMenu menu;
         menuBar = new JMenuBar();
         //Build the file menu in the menu bar
         menu = new JMenu("File");
         menu.setMnemonic(KeyEvent.VK_F);
         menuBar.add(menu);
         JMenuItem menuItem= new JMenuItem("Exit",KeyEvent.VK_X);
         menuItem.addActionListener(new ActionListener()
              public void actionPerformed(ActionEvent e)
                        System.exit(0);
         menu.add(menuItem);
         //Build help menu in the menu bar.
         menu = new JMenu("Help");
         menu.setMnemonic(KeyEvent.VK_H);
         menuBar.add(menu);
         JMenuItem help_item=new JMenuItem("Help Topics",KeyEvent.VK_T);
         menu.add(help_item);
         JMenuItem about_item=new JMenuItem("About Us");
         menu.add(about_item);
         frame.setJMenuBar(menuBar);
              ImageIcon icon=new ImageIcon("images/potter.jpg","");
              JButton clickmovie=new JButton(icon);
              //final JLabel latest=new JLabel("<html><caption>Harry Potter</caption></html>");
              //clickmovie.add(latest);
              final JLabel welcome1=new JLabel("<html><font color=blue face=arial size=3><strong>New Line Movie</strong> gives you the possibility to view your favorite movies.<br>You can choose your category of movies below and click on any movie to get more information about it. <br>Latest News about new movies are also available. ENJOY!!!</font></html>");
              frame.getContentPane().add(welcome1,BorderLayout.EAST);
              final JLabel copyright=new JLabel("<html><font color=blue face=arial size=3><p align=center>&copy Copyright 2004</p></font></html>");
              //frame.getContentPane().add(copyright,BorderLayout.EAST);
              JPanel actionPanel=new JPanel();
              JPanel cartoonPanel=new JPanel();
              JPanel comedyPanel=new JPanel();
              JPanel fictionPanel=new JPanel();
              JPanel mainPanel=new JPanel();
              mainPanel.setLayout(new GridLayout(2,1,5,5));
              mainPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
              mainPanel.add(actionPanel);
              mainPanel.add(cartoonPanel);
              mainPanel.add(comedyPanel);
              mainPanel.add(fictionPanel);
              //mainPanel.add(copyright);
              actionPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Action"),BorderFactory.createEmptyBorder(5,5,5,5)));
              cartoonPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Cartoon"),BorderFactory.createEmptyBorder(5,5,5,5)));
              comedyPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Comedy"),BorderFactory.createEmptyBorder(5,5,5,5)));
              fictionPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Science Fiction"),BorderFactory.createEmptyBorder(5,5,5,5)));
              frame.getContentPane().add(mainPanel,BorderLayout.SOUTH);
              frame.getContentPane().add(clickmovie,BorderLayout.WEST);
              // Create combo box with action movies choices
              final JComboBox actionChoices;
              String[] actionmovie={"-Select a movie-","X-Men","Spiderman"};
              actionChoices=new JComboBox(actionmovie);
              actionChoices.setSelectedIndex(0);
              actionPanel.add(actionChoices);
              actionChoices.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        JComboBox cb = (JComboBox)e.getSource();
                        String act = (String)cb.getSelectedItem();
                        if(act=="X-Men")
                             JFrame action_xmen= new JFrame("--- New Line Movie: X-Men --- ");
                   action_xmen.setSize(400,350);
                   JPanel main=new JPanel();
                   main.setLayout(new GridLayout(2,1,5,5));
                             main.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
                             ImageIcon icon_men=new ImageIcon("images/x-men.jpg","");
                   JButton clickmovie_men=new JButton(icon_men);
                   final JLabel xmen_overview=new JLabel("<html><font color=blue face=arial size=3><b>Title:</b></font> <font color=black><strong>X-Men 2 </strong></font> <br><br><font color=blue face=arial size=3><b>Starring:</b> Hugh JACKMAN and Halle BARRY<br><br><b>Story:</b> The time has come for those who are different to stand united. <br><br>A military officer with a link to Wolverine's mysterious past conspires <br><br>to eradicate the mutant population for once and all. In order to defeat <br><br>this new menace, the X-men will be forced to join forces with Magneto. <br><br><b>Duration:</b> 1hr45min </font></html>");
                   final JLabel copyright=new JLabel("<html><font color=blue face=arial size=3><p align=center>&copy Copyright 2004</p></font></html>");
                             action_xmen.getContentPane().add(copyright,BorderLayout.SOUTH);
                   JButton view=new JButton("View");
                   view.setLayout(new BoxLayout(view,BoxLayout.X_AXIS));
                                            view.add(Box.createHorizontalGlue());
                             view.add(Box.createRigidArea(new Dimension(30,0)));
                   view.setMinimumSize(new Dimension(20,100));
                   view.setPreferredSize(new Dimension(20,100));
                   view.setMaximumSize(new Dimension(Short.MAX_VALUE,Short.MAX_VALUE));
                   view.setMnemonic('v');
                   view.addActionListener(new ActionListener()
                                  public void actionPerformed(ActionEvent e)
                                            String a="172.22.45.44/42050";
                                            String b="172.22.45.44/42052";
                                            String argv=a+b;
                                            Client cl= new Client(a,b);
                                            String[] c={a,b};
                                            cl.mainCl(c);
                                            //this is the code i added so that on clicking the view button
                                            //the client is automatically connected to the server and the player
                                            //plays on the current machine
                   main.add(clickmovie_men);
                             main.add(view);
                             //action_xmen.getContentPane().add(view,BorderLayout.SOUTH);
                   action_xmen.getContentPane().add(main,BorderLayout.WEST);
                   action_xmen.getContentPane().add(xmen_overview,BorderLayout.EAST);
                   action_xmen.show();
                        else if(act=="Spiderman")
                             JFrame action_spider= new JFrame("--- New Line Movie: Spiderman --- ");
                             action_spider.setSize(400,350);
                   action_spider.show();
              //Create combo box with cartoon movies choices
              JComboBox cartoonChoices=null;
              String[] cartoonmovie={"-Select a movie-","Le Roi Lion"};
              cartoonChoices=new JComboBox(cartoonmovie);
              cartoonChoices.setSelectedIndex(0);
              cartoonPanel.add(cartoonChoices);
              //cartoonChoices.addActionListener();
              //Create combo box with comedy movies choices
              JComboBox comedyChoices=null;
              String[] comedymovie={"-Select a movie-"};
              comedyChoices=new JComboBox(comedymovie);
              comedyChoices.setSelectedIndex(0);
              comedyPanel.add(comedyChoices);
              //comedyChoices.addActionListener();
              //Create combo box with fiction movies choices
              JComboBox fictionChoices=null;
              String[] fictionmovie={"-Select a movie-","ET"};
              fictionChoices=new JComboBox(fictionmovie);
              fictionChoices.setSelectedIndex(0);
              fictionPanel.add(fictionChoices);
              //fictionChoices.addActionListener();
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.pack();
              frame.setVisible(true);
    //Implement player function here
    import java.io.*;
    import java.awt.*;
    import java.net.*;
    import java.awt.event.*;
    import java.util.Vector;
    import javax.media.*;
    import javax.media.rtp.*;
    import javax.media.rtp.event.*;
    import javax.media.rtp.rtcp.*;
    import javax.media.protocol.*;
    import javax.media.protocol.DataSource;
    import javax.media.format.AudioFormat;
    import javax.media.format.VideoFormat;
    import javax.media.Format;
    import javax.media.format.FormatChangeEvent;
    import javax.media.control.BufferControl;
    * Client to receive RTP transmission using the RTPConnector.
    public class Client implements ReceiveStreamListener, SessionListener,
         ControllerListener
    String sessions[] = null;
    RTPManager mgrs[] = null;
    Vector playerWindows = null;
    boolean dataReceived = false;
    Object dataSync = new Object();
    public Client(String sessions[]) {
         this.sessions = sessions;
    public Client(String a, String b)
         }//constructor
    protected boolean initialize() {
    try {
         mgrs = new RTPManager[sessions.length];
         playerWindows = new Vector();
         SessionLabel session;
         // Open the RTP sessions.
         for (int i = 0; i < sessions.length; i++) {
              // Parse the session addresses.
              try {
              session = new SessionLabel(sessions);
              } catch (IllegalArgumentException e) {
              System.err.println("Failed to parse the session address given: " + sessions[i]);
              return false;
              System.err.println(" - Open RTP session for: addr: " + session.addr + " port: " + session.port + " ttl: " + session.ttl);
              mgrs[i] = (RTPManager) RTPManager.newInstance();
              mgrs[i].addSessionListener(this);
              mgrs[i].addReceiveStreamListener(this);
              // Initialize the RTPManager with the RTPSocketAdapter
              mgrs[i].initialize(new RTPSocketAdapter(
                             InetAddress.getByName(session.addr),
                             session.port, session.ttl));
              // You can try out some other buffer size to see
              // if you can get better smoothness.
              BufferControl bc = (BufferControl)mgrs[i].getControl("javax.media.control.BufferControl");
              if (bc != null)
              bc.setBufferLength(350);
    } catch (Exception e){
    System.err.println("Cannot create the RTP Session: " + e.getMessage());
    return false;
         // Wait for data to arrive before moving on.
         long then = System.currentTimeMillis();
         long waitingPeriod = 30000; // wait for a maximum of 30 secs.
         try{
         synchronized (dataSync) {
              while (!dataReceived &&
                   System.currentTimeMillis() - then < waitingPeriod) {
              if (!dataReceived)
                   System.err.println(" - Waiting for RTP data to arrive...");
              dataSync.wait(1000);
         } catch (Exception e) {}
         if (!dataReceived) {
         System.err.println("No RTP data was received.");
         close();
         return false;
    return true;
    public boolean isDone() {
         return playerWindows.size() == 0;
    * Close the players and the session managers.
    protected void close() {
         for (int i = 0; i < playerWindows.size(); i++) {
         try {
              ((PlayerWindow)playerWindows.elementAt(i)).close();
         } catch (Exception e) {}
         playerWindows.removeAllElements();
         // close the RTP session.
         for (int i = 0; i < mgrs.length; i++) {
         if (mgrs[i] != null) {
    mgrs[i].removeTargets( "Closing session from AVReceive3");
    mgrs[i].dispose();
              mgrs[i] = null;
    PlayerWindow find(Player p) {
         for (int i = 0; i < playerWindows.size(); i++) {
         PlayerWindow pw = (PlayerWindow)playerWindows.elementAt(i);
         if (pw.player == p)
              return pw;
         return null;
    PlayerWindow find(ReceiveStream strm) {
         for (int i = 0; i < playerWindows.size(); i++) {
         PlayerWindow pw = (PlayerWindow)playerWindows.elementAt(i);
         if (pw.stream == strm)
              return pw;
         return null;
    * SessionListener.
    public synchronized void update(SessionEvent evt) {
         if (evt instanceof NewParticipantEvent) {
         Participant p = ((NewParticipantEvent)evt).getParticipant();
         System.err.println(" - A new participant had just joined: " + p.getCNAME());
    * ReceiveStreamListener
    public synchronized void update( ReceiveStreamEvent evt) {
         RTPManager mgr = (RTPManager)evt.getSource();
         Participant participant = evt.getParticipant();     // could be null.
         ReceiveStream stream = evt.getReceiveStream(); // could be null.
         if (evt instanceof RemotePayloadChangeEvent) {
         System.err.println(" - Received an RTP PayloadChangeEvent.");
         System.err.println("Sorry, cannot handle payload change.");
         System.exit(0);
         else if (evt instanceof NewReceiveStreamEvent) {
         try {
              stream = ((NewReceiveStreamEvent)evt).getReceiveStream();
              DataSource ds = stream.getDataSource();
              // Find out the formats.
              RTPControl ctl = (RTPControl)ds.getControl("javax.media.rtp.RTPControl");
              if (ctl != null){
              System.err.println(" - Recevied new RTP stream: " + ctl.getFormat());
              } else
              System.err.println(" - Recevied new RTP stream");
              if (participant == null)
              System.err.println(" The sender of this stream had yet to be identified.");
              else {
              System.err.println(" The stream comes from: " + participant.getCNAME());
              // create a player by passing datasource to the Media Manager
              Player p = javax.media.Manager.createPlayer(ds);
              if (p == null)
              return;
              p.addControllerListener(this);
              p.realize();
              PlayerWindow pw = new PlayerWindow(p, stream);
              playerWindows.addElement(pw);
              // Notify intialize() that a new stream had arrived.
              synchronized (dataSync) {
              dataReceived = true;
              dataSync.notifyAll();
         } catch (Exception e) {
              System.err.println("NewReceiveStreamEvent exception " + e.getMessage());
              return;
         else if (evt instanceof StreamMappedEvent) {
         if (stream != null && stream.getDataSource() != null) {
              DataSource ds = stream.getDataSource();
              // Find out the formats.
              RTPControl ctl = (RTPControl)ds.getControl("javax.media.rtp.RTPControl");
              System.err.println(" - The previously unidentified stream ");
              if (ctl != null)
              System.err.println(" " + ctl.getFormat());
              System.err.println(" had now been identified as sent by: " + participant.getCNAME());
         else if (evt instanceof ByeEvent) {
         System.err.println(" - Got \"bye\" from: " + participant.getCNAME());
         PlayerWindow pw = find(stream);
         if (pw != null) {
              pw.close();
              playerWindows.removeElement(pw);
    * ControllerListener for the Players.
    public synchronized void controllerUpdate(ControllerEvent ce) {
         Player p = (Player)ce.getSourceController();
         if (p == null)
         return;
         // Get this when the internal players are realized.
         if (ce instanceof RealizeCompleteEvent) {
         PlayerWindow pw = find(p);
         if (pw == null) {
              // Some strange happened.
              System.err.println("Internal error!");
              System.exit(-1);
         pw.initialize();
         pw.setVisible(true);
         p.start();
         if (ce instanceof ControllerErrorEvent) {
         p.removeControllerListener(this);
         PlayerWindow pw = find(p);
         if (pw != null) {
              pw.close();
              playerWindows.removeElement(pw);
              //p.close(); //i added to know if player close when click
         System.err.println("Client internal error: " + ce);
    * A utility class to parse the session addresses.
    class SessionLabel {
         public String addr = null;
         public int port;
         public int ttl = 1;
         SessionLabel(String session) throws IllegalArgumentException {
         int off;
         String portStr = null, ttlStr = null;
         if (session != null && session.length() > 0) {
              while (session.length() > 1 && session.charAt(0) == '/')
              session = session.substring(1);
              // Now see if there's a addr specified.
              off = session.indexOf('/');
              if (off == -1) {
              if (!session.equals(""))
                   addr = session;
              } else {
              addr = session.substring(0, off);
              session = session.substring(off + 1);
              // Now see if there's a port specified
              off = session.indexOf('/');
              if (off == -1) {
                   if (!session.equals(""))
                   portStr = session;
              } else {
                   portStr = session.substring(0, off);
                   session = session.substring(off + 1);
                   // Now see if there's a ttl specified
                   off = session.indexOf('/');
                   if (off == -1) {
                   if (!session.equals(""))
                        ttlStr = session;
                   } else {
                   ttlStr = session.substring(0, off);
         if (addr == null)
              throw new IllegalArgumentException();
         if (portStr != null) {
              try {
              Integer integer = Integer.valueOf(portStr);
              if (integer != null)
                   port = integer.intValue();
              } catch (Throwable t) {
              throw new IllegalArgumentException();
         } else
              throw new IllegalArgumentException();
         if (ttlStr != null) {
              try {
              Integer integer = Integer.valueOf(ttlStr);
              if (integer != null)
                   ttl = integer.intValue();
              } catch (Throwable t) {
              throw new IllegalArgumentException();
    * GUI classes for the Player.
    class PlayerWindow extends Frame {
         Player player;
         ReceiveStream stream;
         PlayerWindow(Player p, ReceiveStream strm) {
         player = p;
         stream = strm;
         public void initialize() {
         add(new PlayerPanel(player));
         public void close() {
         player.close();
         setVisible(false);
         dispose();
         public void addNotify() {
         super.addNotify();
         pack();
    * GUI classes for the Player.
    class PlayerPanel extends Panel {
         Component vc, cc;
         PlayerPanel(Player p) {
         setLayout(new BorderLayout());
         if ((vc = p.getVisualComponent()) != null)
              add("Center", vc);
         if ((cc = p.getControlPanelComponent()) != null)
              add("South", cc);
         public Dimension getPreferredSize() {
         int w = 0, h = 0;
         if (vc != null) {
              Dimension size = vc.getPreferredSize();
              w = size.width;
              h = size.height;
         if (cc != null) {
              Dimension size = cc.getPreferredSize();
              if (w == 0)
              w = size.width;
              h += size.height;
         if (w < 160)
              w = 160;
         return new Dimension(w, h);
    public static void mainCl(String argv[])
         if (argv.length == 0)
         prUsage();
         Client avReceive = new Client(argv);
         if (!avReceive.initialize()) {
         System.err.println("Failed to initialize the sessions.");
         System.exit(-1);
         // Check to see if Client is done.
         try {
         while (!avReceive.isDone())
              Thread.sleep(1000);
         } catch (Exception e) {}
         System.err.println("Exiting Client");
    static void prUsage() {
         System.err.println("Usage: Client <session> <session> ...");
         System.err.println(" <session>: <address>/<port>/<ttl>");
         System.exit(0);
    }// end of Client

    hi,
    i have try compile your source code...anyway, there is 28 errors..I m not sure where is the errors come from. Currently , i m working on the same project as you. Trying to play the media at client machine, but stil can't manage to do so. Can i have your email address? I want to consult you a bit about my project .Is it ok? Thanks =).

  • Problem with HTML in a JLabel

    Is it possible to use styles when using HTML in a JLabel?
    Example:
    <html><hr style="height: 1px; color: black;"></html>Doesn't work correctly as this should give a solid 1px high hr, but doesn't. Instead it gives a black hr with a white shade...
    The JLabel it is used in is not customized in any way.

    I too am interested in getting color on an HR to work. Can you summarize what you have done to date? Sample code?
    Note: An easy way to correct it in a Nonframe instance of html is to subclass HTMLEditor to implement your own ViewFactory and own HRuleView which checks the attribute tag color for the color. I've got this to work, but frames don't work since you can call FrameView (not public) and thus have to use the super class - which then by-passes the ViewFactory from then on.
    So a NON-FRAME Solution to give HR color is... Anybody have a better global solution?
    Here is the one line fix to HRuleView .setProperties. So if you subclass HRuleView specifically to do
    public class MyHTMLEditorKit extends HTMLEditorKit { // StyledEditorKit
        private static final ViewFactory defaultFactory = new MyHTMLFactory();
        public static class MyHTMLFactory extends HTMLFactory {//implements ViewFactory {
             public View create(Element elem) {
             Object o = elem.getAttributes().getAttribute(StyleConstants.NameAttribute);
             if (o instanceof HTML.Tag) {
              HTML.Tag kind = (HTML.Tag) o;
              if (kind == HTML.Tag.HR) {
                  return new MyHRuleView(elem);
           return super.create(elem);
    class MyHRuleView extends View  {
         private Color color = null;
         public void setPropertiesFromAttributes() {
              super.setPropertiesFromAttributes();
              try {color = new Color(Integer.decode((String)attr.getAttribute("color")).intValue());} catch (Exception e) {}
         public void paint(Graphics g, Shape a) {
              if (color != null) g.setColor(color);
              super.paint(g, a);
    }

Maybe you are looking for

  • Ipod Nano - USB Device Not Recognized

    I have read all the help sections. I have tried connecting on two different PCs after I have installed the software that came with my Nano. For the life of me, I cannot get this **** thing recognized. Ive seen numerous posts from people with similar

  • PI 7.1 XSLT mapping without SAP XMLToolkit

    Anyone successfully run an XSL map that uses a Java enhancement method in am Operation Mapping in PI 7.1 without the using the "SAP XML Toolkit" as the processor? I have created an XSL mapping that is calling a Java enhancement.  Both the xsl and cla

  • J1IEX Vendor invoice status

    Dear Experts In j1iex vendor invoice  status is showing as in process even after posting has done. becuase it is showing under ParI and Part II posted items in J1I7 but status is not updated as posted what could be the reasons can any one tell me the

  • Serial numbers in delivery

    Hi Gurus, When i am performing goods issue for an outbound delivery the system gives an error message"Movement type 647 does not currently support serial number management" and the process is terminated there after. With the help of * under the busin

  • Struts with Netbean 4.1

    can any one suggest me how to dev strts in Netbean 4.1