JScrollPane, what is wrong with my code?

Hi, I appreciated if you helped me(perhaps by trying it out yourself?)
I wanted my JScrollPane to display what is drawn on my canvas (which may be large)by scrolling, but it says it doesn't need any vertical and horizontal scroll bars. Here is the code that has this effect
import javax.swing.*;
import java.awt.*;
public class WhatsWrong extends JApplet{
public void init(){
Container appletCont = getContentPane();
appletCont.setLayout(new BorderLayout());
JPanel p = new JPanel();
p.setLayout(new BorderLayout());
p.add(new LargeCanvas(),BorderLayout.CENTER);
int ver = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int hor = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane jsp = new JScrollPane(p,ver,hor);
appletCont.add(jsp,BorderLayout.CENTER);
class LargeCanvas extends Canvas{
public LargeCanvas(){
super();
setBackground(Color.white);
public void paint(Graphics g){
g.drawRect(50,50,700,700);
and the html code:
<html>
<body>
<applet code="WhatsWrong" width = 300 height = 250>
</applet>
</body>
</html>
What shall I do?
Thanks in advance.

What is wrong with your code is that your class, LargeCanvas must implement the Scrollable interface in order to be scrolled by a JScrollPane.
A comment regarding your use of Canvas and Swing components: The Java Tutorial recommends that you extend JPanel to do custom painting. Canvas is what they call a "heavyweight" component and they recommend not to mix lightweight (Swing) components and heavyweight components.
There is a lot more information on custom painting on the Java Tutorial in the Lesson "Creating a GUI with Swing.

Similar Messages

  • What's wrong with my code? compliation error

    There is a compilation error in my program
    but i follow others sample prog. to do, but i can't do it
    Please help me, thanks!!!
    private int selectedRow, selectedCol;
    final JTable table = new JTable(new MyTableModel());
    public temp() {     
    super(new GridLayout(1, 0));                         
    table.setPreferredScrollableViewportSize(new Dimension(600, 200));     
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);     
    ListSelectionModel rowSM = table.getSelectionModel();
    rowSM.addListSelectionListener(new ListSelectionListener() {
    public void valueChanged(ListSelectionEvent e) {
         //Ignore extra messages.
    if (e.getValueIsAdjusting()) return;
    ListSelectionModel lsm = (ListSelectionModel)e.getSource();
    if (lsm.isSelectionEmpty()) {
         System.out.println("No rows are selected.");
    else {
         selectedRow = lsm.getMinSelectionIndex();
    System.out.println("Row " + selectedRow+ " is now selected.");
    JScrollPane scrollPane = new JScrollPane(table);
    add(scrollPane);
    createPopupMenu();
    public void createPopupMenu() {       
    //Create the popup menu.
    JPopupMenu popup = new JPopupMenu();
    // display item
    JMenuItem menuItem = new JMenuItem("Delete selected");
    popup.add(menuItem);
    menuItem.addActionListener(new ActionListener(){
         public void actionPerformed(ActionEvent e){
              System.out.println("Display selected.");
              System.out.println("ClientID: "+table.getValueAt(selectedRow,0));
              int index = table.getSelectedColumn();
              table.removeRow(index);     <-------------------------------compliation error     
         }}); //what's wrong with my code? can anyone tell
    //me what careless mistake i made?
    MouseListener popupListener = new PopupListener(popup);
    table.addMouseListener(popupListener);
    public class MyTableModel extends AbstractTableModel {
    private String[] columnNames = { "ClientID", "Name", "Administrator" };
    private Vector data = new Vector();
    class Row{
         public Row(String c, String n, String a){
              clientid = c;
              name = n;
              admin = a;
         private String clientid;
         private String name;
         private String admin;
    public MyTableModel(){}
    public void removeRow(int r) {    
         data.removeElementAt(r);
         fireTableChanged(null);
    public int getColumnCount() {
    return columnNames.length;
    public int getRowCount() {
    return data.size();
    public String getColumnName(int col) {
    return columnNames[col];
    public Object getValueAt(int row, int col) {
         return "";
    public boolean isCellEditable(int row, int col) {   
    return false;
    public void setValueAt(Object value, int row, int col) {}
    }

    Inside your table model you use a Vector to hold your data. Create a method on your table model
    public void removeRow(int rowIndex)
        data.remove(rowIndex); // Remove the row from the vector
        fireTableRowDeleted(rowIndex, rowIndex); // Inform the table that the rwo has gone
    [/data]
    In the class that from which you wish to call the above you will need to add a reference to your table model.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • What is wrong with this code? on(release) gotoAndPlay("2")'{'

    Please could someone tell me what is wrong with this code - on(release)
    gotoAndPlay("2")'{'
    this is the error that comes up and i have tried changing it but it is not working
    **Error** Scene=Scene 1, layer=Layer 2, frame=1:Line 2: '{' expected
         gotoAndPlay("2")'{'
    Total ActionScript Errors: 1 Reported Errors: 1
    Thanks

    If you have a frame labelled "2" then it should be:
    on (release) {
        this._parent.gotoAndPlay("2");
    or other wise just the following to go to frame 2:
    on (release) {
         this._parent.gotoAndPlay(2);
    You just had a missing curly bracket...

  • I can't figure out what's wrong with this code

    First i want this program to allow me to enter a number with the EasyReader class and depending on the number entered it will show that specific line of this peom:
    One two buckle your shoe
    Three four shut the door
    Five six pick up sticks
    Seven eight lay them straight
    Nine ten this is the end.
    The error message i got was an illegal start of expression. I can't figure out why it is giving me this error because i have if (n = 1) || (n = 2) statements. My code is:
    public class PoemSeventeen
    public static void main(String[] args)
    EasyReader console = new EasyReader();
    System.out.println("Enter a number for the poem (0 to quit): ");
    int n = console.readInt();
    if (n = 1) || (n = 2)
    System.out.println("One, two, buckle your shoe");
    else if (n = 3) || (n = 4)
    System.out.println("Three, four, shut the door");
    else if (n = 5) || (n = 6)
    System.out.println("Five, six, pick up sticks");
    else if (n = 7) || (n = 8)
    System.out.println("Seven, eight, lay them straight");
    else if (n = 9) || (n = 10)
    System.out.println("Nine, ten, this is the end");
    else if (n = 0)
    System.out.println("You may exit now");
    else
    System.out.println("Put in a number between 0 and 10");
    I messed around with a few other thing because i had some weird errors before but now i have narrowed it down to just this 1 error.
    The EasyReader class code:
    // package com.skylit.io;
    import java.io.*;
    * @author Gary Litvin
    * @version 1.2, 5/30/02
    * Written as part of
    * <i>Java Methods: An Introduction to Object-Oriented Programming</i>
    * (Skylight Publishing 2001, ISBN 0-9654853-7-4)
    * and
    * <i>Java Methods AB: Data Structures</i>
    * (Skylight Publishing 2003, ISBN 0-9654853-1-5)
    * EasyReader provides simple methods for reading the console and
    * for opening and reading text files. All exceptions are handled
    * inside the class and are hidden from the user.
    * <xmp>
    * Example:
    * =======
    * EasyReader console = new EasyReader();
    * System.out.print("Enter input file name: ");
    * String fileName = console.readLine();
    * EasyReader inFile = new EasyReader(fileName);
    * if (inFile.bad())
    * System.err.println("Can't open " + fileName);
    * System.exit(1);
    * String firstLine = inFile.readLine();
    * if (!inFile.eof()) // or: if (firstLine != null)
    * System.out.println("The first line is : " + firstLine);
    * System.out.print("Enter the maximum number of integers to read: ");
    * int maxCount = console.readInt();
    * int k, count = 0;
    * while (count < maxCount && !inFile.eof())
    * k = inFile.readInt();
    * if (!inFile.eof())
    * // process or store this number
    * count++;
    * inFile.close(); // optional
    * System.out.println(count + " numbers read");
    * </xmp>
    public class EasyReader
    protected String myFileName;
    protected BufferedReader myInFile;
    protected int myErrorFlags = 0;
    protected static final int OPENERROR = 0x0001;
    protected static final int CLOSEERROR = 0x0002;
    protected static final int READERROR = 0x0004;
    protected static final int EOF = 0x0100;
    * Constructor. Prepares console (System.in) for reading
    public EasyReader()
    myFileName = null;
    myErrorFlags = 0;
    myInFile = new BufferedReader(
    new InputStreamReader(System.in), 128);
    * Constructor. opens a file for reading
    * @param fileName the name or pathname of the file
    public EasyReader(String fileName)
    myFileName = fileName;
    myErrorFlags = 0;
    try
    myInFile = new BufferedReader(new FileReader(fileName), 1024);
    catch (FileNotFoundException e)
    myErrorFlags |= OPENERROR;
    myFileName = null;
    * Closes the file
    public void close()
    if (myFileName == null)
    return;
    try
    myInFile.close();
    catch (IOException e)
    System.err.println("Error closing " + myFileName + "\n");
    myErrorFlags |= CLOSEERROR;
    * Checks the status of the file
    * @return true if en error occurred opening or reading the file,
    * false otherwise
    public boolean bad()
    return myErrorFlags != 0;
    * Checks the EOF status of the file
    * @return true if EOF was encountered in the previous read
    * operation, false otherwise
    public boolean eof()
    return (myErrorFlags & EOF) != 0;
    private boolean ready() throws IOException
    return myFileName == null || myInFile.ready();
    * Reads the next character from a file (any character including
    * a space or a newline character).
    * @return character read or <code>null</code> character
    * (Unicode 0) if trying to read beyond the EOF
    public char readChar()
    char ch = '\u0000';
    try
    if (ready())
    ch = (char)myInFile.read();
    catch (IOException e)
    if (myFileName != null)
    System.err.println("Error reading " + myFileName + "\n");
    myErrorFlags |= READERROR;
    if (ch == '\u0000')
    myErrorFlags |= EOF;
    return ch;
    * Reads from the current position in the file up to and including
    * the next newline character. The newline character is thrown away
    * @return the read string (excluding the newline character) or
    * null if trying to read beyond the EOF
    public String readLine()
    String s = null;
    try
    s = myInFile.readLine();
    catch (IOException e)
    if (myFileName != null)
    System.err.println("Error reading " + myFileName + "\n");
    myErrorFlags |= READERROR;
    if (s == null)
    myErrorFlags |= EOF;
    return s;
    * Skips whitespace and reads the next word (a string of consecutive
    * non-whitespace characters (up to but excluding the next space,
    * newline, etc.)
    * @return the read string or null if trying to read beyond the EOF
    public String readWord()
    StringBuffer buffer = new StringBuffer(128);
    char ch = ' ';
    int count = 0;
    String s = null;
    try
    while (ready() && Character.isWhitespace(ch))
    ch = (char)myInFile.read();
    while (ready() && !Character.isWhitespace(ch))
    count++;
    buffer.append(ch);
    myInFile.mark(1);
    ch = (char)myInFile.read();
    if (count > 0)
    myInFile.reset();
    s = buffer.toString();
    else
    myErrorFlags |= EOF;
    catch (IOException e)
    if (myFileName != null)
    System.err.println("Error reading " + myFileName + "\n");
    myErrorFlags |= READERROR;
    return s;
    * Reads the next integer (without validating its format)
    * @return the integer read or 0 if trying to read beyond the EOF
    public int readInt()
    String s = readWord();
    if (s != null)
    return Integer.parseInt(s);
    else
    return 0;
    * Reads the next double (without validating its format)
    * @return the number read or 0 if trying to read beyond the EOF
    public double readDouble()
    String s = readWord();
    if (s != null)
    return Double.parseDouble(s);
    // in Java 1, use: return Double.valueOf(s).doubleValue();
    else
    return 0.0;
    Can anybody please tell me what's wrong with this code? Thanks

    String[] message = {
        "One, two, buckle your shoe",
        "One, two, buckle your shoe",
        "Three, four, shut the door",
        "Three, four, shut the door",
        "Five, six, pick up sticks",
        "Five, six, pick up sticks",
        "Seven, eight, lay them straight",
        "Seven, eight, lay them straight",
        "Nine, ten, this is the end",
        "Nine, ten, this is the end"
    if(n>0)
        System.out.println(message[n]);
    else
        System.exit(0);

  • [b]Does anybody know what is wrong with my code[/b]

    I cannot see what is wrong with this code but i can't get it to compile. when i try to compile it i get the
    "Exception in thread "main" java.lang.NoClassDefFoundError:
    Is this a problem with compiling or is it a code error?
    Here is my code
    public class IntCalc{
         int value;
         public IntCalc(){
              value = 0;
         public void add(int number)     {
              value = value + number;
         public void subtract(int number){
              value = value - number;
         public int getValue()     {
              return value;
    Message was edited by:
    SHIFTER

    Youd don't have a class file. Compile it first then run it. If your compiler isnt making the .class file tell me and ill give you a link to a realy good java compiler.

  • What's wrong with my code for comparing date retreived from db and sysdate?

    Hi all,
    I need to retrive date from the DB and compare it to system date.i have posted the code below.i get java.sql.SQL Exception:Io exception:Socket closed.
    What's wrong with the code?please help me.Thanks in advance.
    public boolean date() throws IOException, SQLException {
    Connection con1;
    long millis = System.currentTimeMillis();
    Timestamp timestamp = new java.sql.Timestamp(millis);
    ResultSet rs4 = null;
    try
    Class.forName("oracle.jdbc.driver.OracleDriver");
    con = DriverManager.getConnection(
    "jdbc:oracle:thin:@abc:1605:xyz",
    "cdf", "cdf");
    Statement stmt_exp = con.createStatement();
    rs4 = stmt_exp.executeQuery("SELECT DATE FROM TABLE_NAME")
    while (rs4.next()) {
    Timestamp timestamp2 = rs4.getTimestamp("expire_date");
    con1.close();
    catch (Exception e)
    e.printStackTrace();
    finally
    //ResultSet rs4 = null;
    //Timestamp timestamp2;
    Timestamp timestamp2 = rs4.getTimestamp("expire_date");
    if (timestamp2.compareTo(timestamp) < 0)  //sysdate < exp date
    return true;
    } else {
    return false;
    }

    Didn't you understand what BalusC said? You're closing the connection and then trying to use the ResultSet. The ResultSet will be closed when you close the connection so you can't use it anymore.
    You should close the connection last thing in your code, probably in a finally. And after you close your ResultSet and Statement.
    People on the forum help others voluntarily, it's not their job.
    Help them help you.
    Learn how to ask questions first: http://faq.javaranch.com/java/HowToAskQuestionsOnJavaRanch
    ----------------------------------------------------------------

  • What's wrong with the code?

    public void run()
    try
    {     for(;;)
         mgr = (RTPManager)RTPManager.newInstance();
         mgr.addSessionListener(this);
         mgr.addReceiveStreamListener(this);
         try{  /*****port1 = port2 = 29261, which port is only used in here
         localAddr = new SessionAddress(InetAddress.getLocalHost(), port1);
         destAddr = new SessionAddress(ipAddr, port2);
         }catch(Exception e)
              System.out.println(e + " 4");
         try{
         mgr.initialize(localAddr);
         }catch(Exception e)
         System.out.println(e + " 5");
         //set buffer
         bc = (BufferControl)mgr.getControl("javax.media.control.BufferControl");
         if (bc != null)
         bc.setBufferLength(20);
         try{
              mgr.addTarget(destAddr);
         }catch(Exception e)
         System.out.println(e + " 2");
    catch(Exception e)
         System.out.println(e+ " 3");
    the error when i run the code is like that:
    javax.media.rtp.InvalidSessionAddressException: Can't open local data port: 29261
    5
    java.io.IOException: Address already in use: Cannot bind 2
    which means there is error in :
    mgr.initialize(localAddr);
    mgr.addTarget(destAddr);
    But i don't know what's wrong with the code,
    can any one help me?

    I do not find any problem using the same ports for local and destination address with several unicasts. My problems are others.
    But note that the error is even at constructing the localAddress, I mean before trying the destinationAddress. Thus the reason cannot be the former is already in use. In fact I think the later belongs to a remote hosts. Likely, it is trying to access the destinationAddress through the localAddress, but this has not been constructed properly.

  • What's wrong with my code? please help....

    when display button is clicked it must diplay the remarks but it didn't happen...
    what's wrong with my code? please help
    here is my code.....
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.*;
    public class Area extends Applet implements ItemListener,ActionListener
         {Label arlbl = new Label("AREA");
          Choice archc = new Choice();
          Label extlbl = new Label("EXPENDITURE TYPE");
          CheckboxGroup extchk = new CheckboxGroup();
              Checkbox fchk = new Checkbox("FOOD",extchk,true);
              Checkbox schk = new Checkbox("SHELTER",extchk,false);
              Checkbox echk = new Checkbox("EDUCATION",extchk,false);
              Checkbox uchk = new Checkbox("UTILITIES",extchk,false);
          Label exalbl = new Label("EXPENDITURE AMOUNT");
          TextField exatf = new TextField("",20);
          Label remlbl = new Label("REMARKS");
          TextField remtf = new TextField("",30);
          Button disbtn = new Button("DISPLAY");
          Button resbtn = new Button("RESET");
          String display;
          public void init()
              {add(arlbl);
               archc.add("MANILA");
               archc.add("MAKATI");
               archc.add("QUEZON");
               archc.add("PASAY");
               add(archc);
               archc.addItemListener(this);
               add(extlbl);
               add(fchk);
               fchk.addItemListener(this);
               add(schk);
               schk.addItemListener(this);     
               add(echk);
               echk.addItemListener(this);
               add(uchk);
               uchk.addItemListener(this);
               add(exalbl);
               add(exatf);
               add(remlbl);
               add(remtf);
               add(disbtn);
               disbtn.addActionListener(this);
               add(resbtn);
               resbtn.addActionListener(this);
         public void itemStateChanged(ItemEvent ex)
              {int n = archc.getSelectedIndex();
               if(n==0)
                   {if(fchk.getState())
                         {exatf.setText("10000.00");
                         display = archc.getSelectedItem();
                   if(schk.getState())
                        {exatf.setText("15000.00");
                        display = archc.getSelectedItem();
                   if(echk.getState())
                        {exatf.setText("24000.00");
                        display = archc.getSelectedItem();
                   if(uchk.getState())
                        {exatf.setText("8500.00");
                        display = archc.getSelectedItem();
              if(n==1)
                   {if(fchk.getState())
                        {exatf.setText("5000.00");
                        display = archc.getSelectedItem();
                   if(schk.getState())
                        {exatf.setText("11000.00");
                        display = archc.getSelectedItem();
                   if(echk.getState())
                        {exatf.setText("7500.00");
                        display = archc.getSelectedItem();
                   if(uchk.getState())
                        {exatf.setText("24000.00");
                        display = archc.getSelectedItem();
              if(n==2)
                   {if(fchk.getState())
                        {exatf.setText("13000.00");
                        display = archc.getSelectedItem();
                   if(schk.getState())
                        {exatf.setText("7000.00");
                        display = archc.getSelectedItem();
                   if(echk.getState())
                        {exatf.setText("27000.00");
                        display = archc.getSelectedItem();
                   if(uchk.getState())
                        {exatf.setText("6000.00");
                        display = archc.getSelectedItem();
              if(n==3)
                   {if(fchk.getState())
                        {exatf.setText("6000.00");
                        display = archc.getSelectedItem();
                   if(schk.getState())
                        {exatf.setText("9000.00");
                        display = archc.getSelectedItem();
                   if(echk.getState())
                        {exatf.setText("15000.00");
                        display = archc.getSelectedItem();
                   if(uchk.getState())
                        {exatf.setText("19000.00");
                        display = archc.getSelectedItem();
         public void actionPerformed(ActionEvent e)
              {if(e.getSource() == disbtn)
                    {String amtstr = exatf.getText();
                     int amt = Integer.parseInt(amtstr);
                        {if(amt > 8000)
                             {remtf.setText(display + " IS ABOVE BUDGET");
                        else
                             {remtf.setText(display + " IS BELOW BUDGET");
              if(e.getSource() == resbtn)
                   {archc.select(0);
                   fchk.setState(true);
                   schk.setState(false);
                   echk.setState(false);
                   uchk.setState(false);
                   exatf.setText("");
                   remtf.setText("");
    Edited by: lovely23 on Feb 28, 2009 11:24 PM

    Edit: thanks for cross-posting this question on another forum. I now see that I wasted my time trying to study your code in the java-forums to help you with an answer that had already been answered elsewhere (here). Do you realize that we are volunteers, that our time is as valuable as yours? Apparently not. Cross-post again and many here will not help you again. I know that I won't.

  • Red highlight next to code in dreamweaver. What is wrong with the code and is it affecting the websi

    What is wrong with the code and is it affecting the website?

    Line 107 looks dodgy to me and it won't have any effect on your code.  However, it is a good idea to post a complete link to your CSS for us to see it in full and to validate it using external tools.  In fact, you could validate the CSS (and HTML) yourself..
    <http://jigsaw.w3.org/css-validator/>
    Good luck.

  • I'm trying to add the system date with a Label. What is wrong with the code

    import java.util.*;
    import javax.swing.*;
    public class CurrentDateApplet extends JApplet
         Calendar currentCalendar = Calendar.getInstance();
         JLabel dateLabel = new JLabel();
         JPanel mainPanel = new JPanel();
         int dayInteger = currentCalendar.get(Calendar.DATE);
         int monthInteger = currentCalendar.get(Calendar.MONTH)+1;
         int yearInteger = currentCalendar.get(Calendar.YEAR);
         public void init()
              mainPanel.add(dateLabel);
              setContentPane(mainPanel);
              dateLabel.append(currentCalendar.get(Calendar.HOUR) + currentCalendar.get
                        (Calendar.MINUTE);
    }

    As for what's wrong with the code, it would be easier if you said: it doesn't show the date (it does this instead), it doesn't compile (I get this message) etc.
    Anyway I'll assume you want to display the time in a label...
    dateLabel.append(currentCalendar.get(Calendar.HOUR) + currentCalendar.get
    (Calendar.MINUTE);This won't compile: the parentheses are mismatched, and there is simply no such thing as append(). So we could trydateLabel.setText("" + currentCalendar.get(Calendar.HOUR) + currentCalendar.get(Calendar.MINUTE));This wroks, but looks pretty nasty and it's not how you are supposed to format dates and times. Here's the unofficial party line, nicked from one of jverd's posts:
    Calculating Java dates: Take the time to learn how to create and use dates
    Formatting a Date Using a Custom Format
    Parsing a Date Using a Custom Format
    From those links you should be able to find those applicable to times like this: http://www.exampledepot.com/egs/java.text/FormatTime.html
    Using this approach you would end up with something like:import java.text.Format;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import javax.swing.JApplet;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    public class CurrentDateApplet extends JApplet
        private Date date;
        private JLabel timeLabel;
        private JPanel mainPanel;
        public void init()
            mainPanel = new JPanel();
            timeLabel = new JLabel();
            mainPanel.add(timeLabel);
            setContentPane(mainPanel);
            date = new Date();
            Format formatter = new SimpleDateFormat("HH:ss a");
            timeLabel.setText(formatter.format(date));
    }

  • What's wrong with my code?

    I don't have a lot of time for explanation. Somebody please tell me what's wrong with the following code.
    import java.nio.*;
    import java.io.*;
    public class GettingAnInteger {
         public static void main(String args[]) {
              IntBuffer intBuf = new IntBuffer.allocate(10);
              int x;
              x = intBuf.get();
              System.out.print(x);
    }Thanks!!!

    Why wouldn't you include the keyword new?http://java.sun.com/docs/books/tutorial/
    http://java.sun.com/learning/new2java/index.html
    http://javaalmanac.com
    http://www.jguru.com
    http://www.javaranch.com
    Bruce Eckel's Thinking in Java
    Joshua Bloch's Effective Java
    Bert Bates and Kathy Sierra's Head First Java

  • What's wrong with this code (AS3)?

    I want to publish a live stream and, when a button is pressed, publish the same stream for vod.  I haven't been able to get an answer as to whether I can do this...my code is below.  Can someone please tell me if I can do this, or what may be wrong with my code?
    The live stream and playback works fine; but the recording doesn't start.  Also, I want other objects on the client, such as the current camera and audio information, and the aspect ratio being used.  I havent' been able to get these to show up (i.e., the incomingLbl and outgoingLbl do not show up).
    Thank you,
    Phillip A
    My code:
    package {
        import flash.display.MovieClip;
        import flash.net.NetConnection;
        import flash.events.NetStatusEvent; 
        import flash.events.MouseEvent;
        import flash.events.AsyncErrorEvent;
        import flash.net.NetStream;
        import flash.media.Video;
        import flash.media.Camera;
        import flash.media.Microphone;
        import fl.controls.Button;
        import fl.controls.Label;
        import fl.controls.TextArea;
        import fl.controls.CheckBox;
        public class vodcast1 extends MovieClip {
            private var nc:NetConnection;
            private var nc2:NetConnection;
            private var ns:NetStream;
            private var ns2:NetStream;
            private var nsPlayer:NetStream;
            private var vid:Video;
            private var vidPlayer:Video;
            private var cam:Camera;
            private var mic:Microphone;
            private var camr:Camera;
            private var micr:Microphone;
            private var clearBtn:Button;
            private var startRecordBtn:Button;
            private var outgoingLbl:Label;
            private var incomingLbl:Label;
            private var myMetadata:Object;
            private var outputWindow:TextArea;
            private var cb1:CheckBox;
            public function vodcast1(){
                setupUI();
                nc = new NetConnection();
                nc.addEventListener(NetStatusEvent.NET_STATUS, onNetStatus);
                nc.connect("rtmp://localhost/publishLive");
                nc2 = new NetConnection();
                nc2.connect("rtmp://localhost/vod/videos");
                nc2.addEventListener(NetStatusEvent.NET_STATUS, onNetStatus2);
            private function startRecordHandler(event:MouseEvent):void {
                publishRecordStream();
            private function onNetStatus(event:NetStatusEvent):void {
                trace(event.target + ": " + event.info.code);
                switch (event.info.code)
                    case "NetConnection.Connect.Success":
                        trace("Congratulations! you're connected to live");
                        publishCamera();
                        displayPublishingVideo();
                        displayPlaybackVideo();
                        break;
                    case "NetStream.Publish.Start":
            // NetStatus handler for Record stream       
            private function onNetStatus2(event:NetStatusEvent):void {
                trace(event.target + ": " + event.info.code);
                switch (event.info.code)
                    case "NetConnection.Connect.Success":
                        trace("Congratulations! you're connected to vod");                   
                        break;
                    case "NetConnection.Connect.Rejected":
                    case "NetConnection.Connect.Failed":
                    trace ("Oops! the connection was rejected");
                        break;
                    case "NetStream.Publish.Start":
                        sendMetadata();
                        break;
            private function asyncErrorHandler(event:AsyncErrorEvent):void {
                trace(event.text);
            private function sendMetadata():void {
                trace("sendMetaData() called")
                myMetadata = new Object();
                myMetadata.customProp = "Recording in progress";
                ns.send("@setDataFrame", "onMetaData", myMetadata);
            private function publishRecordStream():void {
                camr = Camera.getCamera();
                micr = Microphone.getMicrophone();
                ns2 = new NetStream(nc2);
                ns2.client = new Object();
                ns2.addEventListener(NetStatusEvent.NET_STATUS, onNetStatus2);
                ns2.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler);
                ns2.attachCamera(camr);
                ns2.attachAudio(micr);
                ns2.publish("vodstream", "record");           
            private function publishCamera():void {
                cam = Camera.getCamera();
                mic = Microphone.getMicrophone();
                ns = new NetStream(nc);
                ns.client = this;
                ns.addEventListener(NetStatusEvent.NET_STATUS, onNetStatus);
                ns.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler);
                ns.attachCamera(cam);
                ns.attachAudio(mic);
                ns.publish("livestream", "live");
            private function displayPublishingVideo():void {
                vid = new Video(cam.width, cam.height);
                vid.x = 10;
                vid.y = 30;
                vid.attachCamera(cam);
                addChild(vid); 
            private function displayPlaybackVideo():void {
                nsPlayer = new NetStream(nc);
                nsPlayer.client = this;
                nsPlayer.addEventListener(NetStatusEvent.NET_STATUS, onNetStatus);
                nsPlayer.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler);
                nsPlayer.play("livestream");
                vidPlayer = new Video(cam.width, cam.height);
                vidPlayer.x = cam.width + 100;
                vidPlayer.y = 30;
                vidPlayer.attachNetStream(nsPlayer);
                addChild(vidPlayer);
            private function setupUI():void {
                outputWindow = new TextArea();
                outputWindow.move(250, 175);
                outputWindow.width = 200;
                outputWindow.height = 50;
                outgoingLbl = new Label();
                incomingLbl = new Label();
                outgoingLbl.width = 100;
                incomingLbl.width = 100;
                outgoingLbl.text = "Publishing Stream";
                incomingLbl.text = "Playback Stream";
                outgoingLbl.move(20, 200);
                incomingLbl.move(300, 200);
                outgoingLbl.condenseWhite = true;
                incomingLbl.condenseWhite = true;
                startRecordBtn = new Button();
                startRecordBtn.width = 150;
                startRecordBtn.move(250, 345);
                startRecordBtn.label = "Start Recording";
                startRecordBtn.addEventListener(MouseEvent.CLICK, startRecordHandler);
                //cb1 = new CheckBox();
                //cb1.label = "Record";
                //cb1.move(135,300);
                //cb1.addEventListener(MouseEvent.CLICK,publishRecordStream);
                //clearBtn = new Button();
    //            clearBtn.width = 100;
    //            clearBtn.move(135,345);
    //            clearBtn.label = "Clear Metadata";
    //            clearBtn.addEventListener(MouseEvent.CLICK, clearHandler);
                addChild(outgoingLbl);
                addChild(incomingLbl);
    //            addChild(clearBtn);
                addChild(startRecordBtn);
    //            addChild(cb1);
                addChild(outputWindow);
            public function onMetaData(info:Object):void {
                outputWindow.appendText(info.customProp);

    use event.currentTarget (and you don't need to repeatedly define the same function):
    var c:int;
    var buttonName:String;
    for (c = 1;c < 5;c++) {
         buttonNum = "button"+c;
         this[buttonNum].addEventListener(MouseEvent.MOUSE_DOWN, pressStepButton);
    function pressStepButton(event:MouseEvent) {          trace(event.currentTarget,event.currentTarget.name);     }

  • What's wrong with these code?

    Hi, i made the below snippet of code for retriving data from a table in database. but it doesnt work property when i run the program. Could anyone tell me what's wrong with it? Thanx in advance.
    //rs is object of type ResultSet
    //url is one of the column names in a table
    <% if(rs.getString("url")!= null){%>
       <tr>
          <td>URL </td>
          <td>= { <%= rs.getString("url") %> },</td>   
      </tr>
    <%}%>

    Without seeing the error message, one can only guess. Some JDBC drivers do not allow you to get a column more than once, so that may be your problem. Store the result of rs.getString("url") in a String variable in the first line, and use that variable in the table cell.

  • FileFilter????What's wrong with this code???HELP!!

    I want to limit the JFileChooser to display only txt and java file. But the code I wrote has error and I don't know what's wrong with it. can anyone help me to check it out? Thank you.
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class FileFilterTest extends JPanel
         public static void main(String[] args)
              new FileFilterTest();
         public class fFilter implements FileFilter
              public boolean accept(File file)
                   String name = file.getName();
                   if(name.toLowerCase().endsWith(".java") || name.toLowerCase().endsWith(".txt"))
                        return true;
                   else
                        return false;
         public FileFilterTest()
              JFileChooser fc = new JFileChooser();
              fc.setFileFilter(new fFilter());
              fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
              fc.setCurrentDirectory(new File(System.getProperty("user.dir")));
              //fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
              //fc.setMultiSelectionEnabled(true);
              int returnVal = fc.showDialog(FileFilterTest.this, "Open File");
              if(returnVal == JFileChooser.APPROVE_OPTION)
                   String file = fc.getSelectedFile().getPath();
                   if(file == null)
                        return;
              else if(returnVal == JFileChooser.CANCEL_OPTION)
                   System.exit(0);
              else
                   System.exit(0);
              JFrame f = new JFrame();
              FileFilterTest ff = new FileFilterTest();
              f.setTitle("FileFilterTest");
              f.setBackground(Color.lightGray);
              f.getContentPane().add(ff, BorderLayout.CENTER);
              f.setSize(800, 500);
              f.setVisible(true);
    }

    There are two file filters
    class javax.swing.filechooser.FileFilter
    interface java.io.FileFilter
    In Swing you need to make a class which extends the first one and implements the second. Sometimes you may not need to implement the second, but it is more versitle to do so and requires no extra work.

  • What's wrong with this code (in recursion there may be a problem )

    // ELEMENTS OF TWO VECTORS ARE COMPARED HERE
    // CHECK WHAT IS WRONG WITH THIS PGM
    // there may be a problem in recursion
    import java.util.*;
    class Test
    Vector phy,db;
    public static void main(String adf[])
         Vector pp1=new Vector();
         Vector dp1=new Vector();
         //adding elements to the vector
         pp1.add("1");
         pp1.add("a");
         pp1.add("b");
         pp1.add("h");
         pp1.add("c");
         dp1.add("q");
         dp1.add("c");
         dp1.add("h");
         dp1.add("w");
         dp1.add("t");
         printVector(dp1);
         printVector(pp1);
         check2Vectors(pp1,dp1);
    public static void printVector(Vector v1)
         System.out.println("Vector size "+v1.size());
         for(int i=0;i<v1.size();i++)
              System.out.println(v1.get(i).toString());
    public static void check2Vectors(Vector p,Vector d)
         System.out.println("p.size() "+p.size()+" d.size() "+d.size());
         printVector(p);
         printVector(d);
         for(int i=0;i<p.size();i++)
                   for(int j=0;j<d.size();j++)
                        System.out.println(" i= "+i+" j= "+j);
                        Object s1=p.elementAt(i);
                        Object s2=d.elementAt(j);
              System.out.println("Checking "+s1+" and "+s2);
                        if(s1.equals(s2))
    System.out.println("Equal and Removing "+s1+" and "+s2);
                             p.remove(i);
                             d.remove(j);
                             printVector(p);
                             printVector(d);                    
                        check2Vectors(p,d);
                   }//inner for
              }//outer for     
    if(p.size()==0||d.size()==0)
    System.out.println("Vector checking finished and both match");
    else
    System.out.println("Vector checking finished and both do not match");
    }//method
    }

    hi,
    but the upper limit is changing everytime you call the function recursively
    so there should not be any problem(i suppose)
    my intension is to get the unmatched elements of the two vectors
    suggest me changes and thanks in advancce
    ashok
    The problems comes from the fact that you remove
    elements for a Vector while iterating in a loop where
    the upper limit as been set to the initial size of the
    Vector.
    You should use so while loops with flexible stop
    conditions that would work when the size of the Vector
    changes.
    Finally: why don't you use Vector.equals() ?

Maybe you are looking for

  • Personal view is not available

    Hi All I got a user who is opening a sharepoint 2010 site and getting a blank page (Quick launch is there and Ribbon is there) but no content in middle. He provided one URL and it is http://abc.qintra.com/bu/EBCPE/EBCPEPM/LaughmanAppProjStatu/Lists/A

  • Looking for AIR answers?

    Can't find what you are looking for in the forums? Need an answer to your question immediately? Get proactive and search the AIR cookbook for an answer to your question. Cookbooks are very similar to forums, except that posts contributed to the cookb

  • The new firmw

    When ? Are there anybody who knows when the new firmware with dri've letter support will be released ? *Zen Touch*Message Edited by Chrille on 02-2-2005 02:9 PM

  • How to dynamically refresh system properties when changed

    Hi All, Through weblogic startup class I'm loading the properties from a properties file into system properties, Now my requirement is to refresh those system properties when ever I make changes to the properties. Is there any way to achieve this fun

  • FIN_PCA is activated at Client level or at Company Code level?

    I have two companies already set without FIN_PCA activated. I need to configure a new one and I want FIN_PCA to be active, Could I do this without impacting the other companies?