JScrollpane + JTextArea

hi to all,
i have 3 classes communicating (among others) to create a gui and pass info to the textarea in my scrollpane, its the first time ive used scrollpanes but according to the tutorial - it seems to be wired up right, however i cant get any text to display. the text area appears inside the scroller ok but i cant update it.
<code> => tester.java
InfoScroller info;
this.getContentPane().add(info.getInfoScroller(), new XYConstraints(18, 55, 150, 153));
</code>
<code> => parser.java -- parses a graph file
tester test = new tester();
test.info.setInfoText(" line: " + i + " .. " + expression);
</code>
<code> => InfoScroller.java --> holds the scrollpane and the textarea
infoText = new JTextArea();
// text area inside the scroller
infoText.setWrapStyleWord(true);
infoText.setLineWrap(true);
infoText.setText("");
infoText.setEditable(false);
infoText.setDisabledTextColor(Color.black);
infoText.setToolTipText("Graph Information");
infoText.setDoubleBuffered(false);
// create the scroller for the text area
infoScroller = new JScrollPane(infoText);
infoScroller.setBorder(BorderFactory.createEtchedBorder());
infoScroller.setViewportBorder(BorderFactory.createEtchedBorder());
infoScroller.setVerticalScrollBarPolicy(JScrollPane.
VERTICAL_SCROLLBAR_ALWAYS);
infoScroller.setHorizontalScrollBarPolicy(JScrollPane.
HORIZONTAL_SCROLLBAR_NEVER);
infoScroller.setWheelScrollingEnabled(true);
public JScrollPane getInfoScroller() {
return this.infoScroller;
public void setInfoText(String text) {
this.infoText.append(text);
</code>
regards,
g00fy

After appending the text, try:
textArea.setCaretPosition( 0 );

Similar Messages

  • Console behavior for JScrollPane - - JTextArea

    I'm searching how to make a JScrollPane (containing a JTextArea) work like a console. By console, I mean the application user is FORCED to see the last message ( single line ) displayed in the text area at the moment it gets displayed.
    thanks for help,
    Pierre

    It's not necessary to answer, I found the solution :
    let's suppose :
    JTextArea view = new JTextArea();
    JScrollPane scrollPane = new JScrollPane( view );
    //THIS SINGLE LINE BRINGS THE TEXT AREA TO ITS LAST ROW
    scrollPane.getViewPort().setViewPosition(new Point(0, view.getHeigh()));
    et voil�, to whom it may help!
    Pierre

  • Setting JTextArea text within a JScrollPane

    Hey all. I'm attempting to use the setText() method of JTextArea to set the text of various areas located in various scroll panes. The general procedure I'm following is to initialize a new JTextArea and JScrollPane within an initializeGui function, set the properties of the JTextArea, then add it to the scroll pane using .getViewport().add(). After that, a separate function goes through all my form fields loading them with whatever data type is appropriate, in the case of the text areas I'm trying to use setText() to set a string. However, after using setText() the text area is displaying nothing. Here's some code for example (workerPane is using a layout manager exclusive to the environment I'm working in, but I don't believe it's the problem).
    workerLabel = new JLabel("Customer Address:");
              JScrollPane sp = new JScrollPane();          
              JTextArea ta = new JTextArea();          
              //set ta's properties to whatever is needed
              ta.addKeyListener(new java.awt.event.KeyAdapter(){
                   public void keyTyped(KeyEvent e){
                        JTextArea text = (JTextArea)e.getSource();                    
                        String txt = text.getText();                    
                        int nameLength = 240;
                        if ( txt.length() >= nameLength ){
                             text.setText ( txt.substring( 0, nameLength-1 ) );                         
                             Toolkit.getDefaultToolkit().beep();                    
              sp.getViewport().add(ta);          
              workerPane.add("3.1.right.top",workerLabel);
              workerPane.add("3.2.left.center",custAddScrollPane);After each area has been initialized, another function is called to load the data into it. Here are some methods I've tried that haven't worked.
    //basic, but leaves an empty field.
    ta.setText(formProperties[2].getStringValue());
    //this results in two NullPointerException warning windows popping
    ta=(JTextArea)sp.getViewport().getView();
    if(formProperties[2].getStringValue() != null)         ta.setText(formProperties[2].getStringValue());
    sp.getViewport().removeAll();
    sp.getViewport().add(ta);Can anyone point me in the right direction as to how to set my textarea's text?

    I usually use the approach given above. The other option is:
    scrollPane.setViewportView( textArea );

  • JTabbedPane and JScrollPane

    I am trying to add a JScrollPane inside a tab in a JTabbedPane.. unsuccessfully
    the JScrollPane has a JTextArea added to it...
         // tp previously declared as a JTabbedPane....
        JScrollPane jpC = new JScrollPane();
        JTextArea jtC = new JTextArea(--text source--);
        jpC.add(jtC);
        tp.addTab("Constructors",
                  null,
                  jpC,
                  "View all Constructors");on switching to the tab, it is blank.....
    the tab works fine when I simply have a simple JTextArea inside it, but it is not an option
        JTextArea jtC = new JTextArea(--text source--);
        tp.addTab("Constructors",
                  null,
                  jtC,
                  "View all Constructors");essentially what I need is to have a scrollable peice of text in all of my panes.... any idea what might be going wrong?
    I even tried declaring a new container, adding the scrollpane (with the textarea inside) to it and then creating the tab.. same result.. i understand that a tabbedpane can only contain exactly one component, so i thought this might be a work-around...
    thanks in advance,
    K

    Thanks for the quick reply.....
    actually the solution was quite illogical (IMHO!)
    all i had to do was type cast the freaking thing to (Component)!!!!!!!
        JTextArea jtC = new JTextArea(-- text source --);
        JScrollPane jpC = new JScrollPane(jtC);
        tp.addTab("Constructors",
                  null,
                  (Component)jpC,
                  "View all Constructors");again, thanks for the prompt reply!
    Kunal

  • How can i put text/chars inside a text area inside a JScrollPane?

    ive tried:
    receipt.setText("blah blah") // but it does not work. all i get is still a blank text area inside a JScrollPane
    JTextArea receipt;
    JScrollPane sp;
    receipt = new JTextArea();
    sp = new JScrollPane(receipt,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

    mstrnew = new JButton //this should clear receipt
    if(evnt.getSource()==mstrnew)
                  order.setText("");
                  price.setText("");
                  total.setText("0.0");
                  cash.setText("");
                  change.setText("");
                  mstrtotal = 0;
                  JOptionPane.showMessageDialog(null,"              Starting New Transaction...","",JOptionPane.PLAIN_MESSAGE);    receipt.setText("");}
    else if(evnt.getSource()==vm1)
                  generate("           2pc. Chicken Strips Meal\n");
                  order.setText("2pc. Chicken Strips");
                  price.setText("61.0");
                  mstrtotal = Double.parseDouble(price.getText()) + Double.parseDouble(total.getText());
                  total.setText(String.valueOf(mstrtotal));
    // scrollpane part
                 receipt = new JTextArea();
                 receipt.setEditable(true);
                 //receipt.setLineWrap(true);
             up = "\n          YUM! Brands Corporation, Kentucky Fried Chicken ?\n                       KFC LaSalle Branch, Taft Ave., Manila\n\n           88788   TIN-209-670-390-002   REG VAT   POS#113\n           SN:41-HK170 All prices were subjected of 12% VAT.";
             mid = "\n\n";
             down = "\n";
             complete = up+mid+down;
             receipt.setText(complete);
             sp = new JScrollPane(receipt,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    public void generate(String z)
             mid += z;
             complete = up+mid+down;
        }Message was edited by:
    ice3d

  • Scroll position and JTextArea

    I hava a JFrame with a JScrollPane/JTextArea in it.
    I frequently update the textarea with a setText(string), but for every update the scrollbar jumps to the bottom. The things is that I want the scrollbar to remember its position and not change its position after an update.
    The string in setText varies in length.
    Any ideas, please.
    Thanks!!

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class ScrollingTest {
      static JTextArea textArea;
      static int updateCount = 0;
      static int i;
      public static void main(String[] args) {
        JButton button = new JButton("add data");
        button.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            updateDisplay();
        JPanel panel = new JPanel();
        panel.add(button);
        textArea = new JTextArea();
        textArea.setMargin(new Insets(10,10,10,10));
        textArea.setLineWrap(true);
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().add(panel, "North");
        f.getContentPane().add(new JScrollPane(textArea));
        f.setSize(400,300);
        f.setLocation(400,300);
        f.setVisible(true);
      private static void updateDisplay() {
        String text = "";
        for(i = updateCount; i < 40 + updateCount; i++)
          text += String.valueOf(i) + "\n";
        int caretPosition = textArea.getDocument().getLength();
        textArea.setText(textArea.getText() + text);
        updateCount = i;
        textArea.setCaretPosition(caretPosition);
    }

  • How could i place scroll bars for my JTextArea!

    hi,
    I am using JTextArea. Now i want to place scroll bars to scroll when the text is more than the textarea..............
    Help me...........
    Regards........

    Just to give you some more detail here is a simple example application:
    import javax.swing.*;
    public class Example extends JFrame{
         public Example(){
              build();
        public void build(){
              // The code that should be of interest to you.
               JScrollPane scroll = new JScrollPane();
              JTextArea t = new JTextArea();
              scroll.getViewport().add(t);
              this.getContentPane().add(scroll);
              this.setSize(200,200);
              this.setVisible(true);
        public static void main(String[] args) {
              new Example();
    }good luck :)

  • How can we add elements to component at run time  through java

    Hi,
    In my project ,I am using JArrayList to collect urls and I need to add those to JScrollPane(JTextArea) and this to frame. This works fine but I need the process of how the elements added to ArrayList simultaneusly added to JTextArea.
    pls suggest the way

    arrayList.add( someObject );
    textArea.append( someObject.toString() );

  • Isolating the viewable text in a scrollpane

    Hi,
    I have a JScrollPane, JTextArea, and DefaultStyledDocument.
    My problem is that JTextArea.getText() is too much. I would like to read only the viewable text.
    I have been messing with getViewport, AccessibleContent, getText(int, int), loads of very hopeful guesses, and I'm just not succeeding!
    If it is solved, the viewable text will be edited, so knowing its start and end position in the document might be important.
    Thanks very much for reading!

    maybe???
    http://forum.java.sun.com/thread.jspa?threadID=5163597&messageID=9625138

  • Java Text Editor

    I have created an applet editor that will enable a user to break a text file down into a series of smaller html files. This does serve a purpose that is not really important at the moment and I don't want to bore you all.
    The problem I am having is that upon clicking the open button and the 2 save buttons, the applet opens file chooser where you can select a file. The problem is that once the file is open, the applet, for some reason starts the openfile() method again. The same happens when using the the 2 saveFile() methods. Can anyone help?
    package tagger;
    import java.awt.*;
    import java.applet.*;
    import javax.swing.JComboBox;
    import javax.swing.JPanel;
    import javax.swing.JButton;
    import javax.swing.text.Document;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    import javax.swing.JScrollPane;
    import javax.swing.SwingConstants;
    import javax.swing.JLabel;
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.net.*;
    import java.net.URL;
    import java.io.IOException;
    import java.io.DataInputStream;
    import javax.swing.filechooser.FileFilter;
    * <p>Title: Cheshire Parish Register Database Note Tagging System</p>
    * <p>Description: An online Text Editor and Note Creation Tool for use with
    * CPRDB</p>
    * <p>Copyright: </p>
    * <p>Company: The University Of Liverpool</p>
    * @author Mike Melling
    * @version 1.0
    public class NoteTagger extends Applet {
        public String fileName = null;
        boolean isStandalone = false;
        BorderLayout borderLayout1 = new BorderLayout();
        JPanel jPanel1 = new JPanel();
        BorderLayout borderLayout2 = new BorderLayout();
        JPanel jPanel2 = new JPanel();
        JPanel jPanel3 = new JPanel();
        JPanel jPanel4 = new JPanel();
        JPanel jPanel5 = new JPanel();
        JPanel jPanel6 = new JPanel();
        BorderLayout borderLayout3 = new BorderLayout();
        BorderLayout borderLayout4 = new BorderLayout();
        BorderLayout borderLayout6 = new BorderLayout();
        BorderLayout borderLayout7 = new BorderLayout();
        JScrollPane jScrollPane1 = new JScrollPane();
        JTextArea jTextArea1 = new JTextArea();
        JScrollPane jScrollPane2 = new JScrollPane();
        JTextArea jTextArea4 = new JTextArea();
        BorderLayout borderLayout8 = new BorderLayout();
        JPanel jPanel7 = new JPanel();
        JPanel jPanel8 = new JPanel();
        JPanel jPanel9 = new JPanel();
        JPanel jPanel10 = new JPanel();
        JPanel jPanel11 = new JPanel();
        JPanel jPanel13 = new JPanel();
        JPanel jPanel14 = new JPanel();
        BorderLayout borderLayout9 = new BorderLayout();
        JPanel jPanel15 = new JPanel();
        JPanel jPanel16 = new JPanel();
        JPanel jPanel17 = new JPanel();
        JPanel jPanel18 = new JPanel();
        JPanel jPanel19 = new JPanel();
        BorderLayout borderLayout10 = new BorderLayout();
        JButton jButton2 = new JButton();
        JButton jButton1 = new JButton();
        JPanel jPanel22 = new JPanel();
        BorderLayout borderLayout12 = new BorderLayout();
        JScrollPane jScrollPane5 = new JScrollPane();
        JTextArea jTextArea3 = new JTextArea();
        JLabel jLabel1 = new JLabel();
        BorderLayout borderLayout13 = new BorderLayout();
        BorderLayout borderLayout14 = new BorderLayout();
        FlowLayout flowLayout1 = new FlowLayout();
        BorderLayout borderLayout15 = new BorderLayout();
        JPanel jPanel27 = new JPanel();
        Document document1 = jTextArea1.getDocument();
        Document document2 = jTextArea3.getDocument();
        JFileChooser jFileChooser1 = new JFileChooser();
        String currFileName = null; // Full path and filename. null means new/untitled.
        JPanel jPanel20 = new JPanel();
        java.awt.BorderLayout borderLayout16 = new BorderLayout();
        JPanel jPanel24 = new JPanel();
        JTextField jTextField1 = new JTextField();
        JPanel jPanel25 = new JPanel();
        java.awt.BorderLayout borderLayout18 = new BorderLayout();
        JTextField jTextField2 = new JTextField();
        JPanel jPanel26 = new JPanel();
        JPanel jPanel12 = new JPanel();
        JPanel jPanel21 = new JPanel();
        JPanel jPanel23 = new JPanel();
        JPanel jPanel28 = new JPanel();
        java.awt.BorderLayout borderLayout5 = new BorderLayout();
        JButton jButton6 = new JButton();
        JButton jButton7 = new JButton();
        JFileChooser jFileChooser2 = new JFileChooser();
        String currFileName2 = null; //Full path and filename. null means new/untitled
        JButton jButton3 = new JButton();
        public String getParameter(String key, String def) {
            return isStandalone ? System.getProperty(key, def) :
                    (getParameter(key) != null ? getParameter(key) : def);
        //Construct the applet
        public NoteTagger() {
            try {
                jbInit();
            } catch (Exception ex) {
                ex.printStackTrace();
        //Initialize the applet
        public void init() {
            try {
                jbInit();
            } catch (Exception e) {
                e.printStackTrace();
        //Component initialization
        private void jbInit() throws Exception {
            jPanel1.setLayout(borderLayout2);
            jPanel5.setLayout(borderLayout3);
            jPanel2.setLayout(borderLayout13);
            jPanel6.setLayout(borderLayout14);
            jPanel3.setLayout(borderLayout6);
            jPanel4.setLayout(borderLayout7);
            jTextArea1.setLineWrap(true);
            jPanel3.setPreferredSize(new Dimension(700, 100));
            jPanel4.setBackground(Color.lightGray);
            jPanel4.setPreferredSize(new Dimension(700, 50));
            jTextArea4.setPreferredSize(new Dimension(700, 100));
            jTextArea4.setEditable(false);
            jTextArea4.setText("");
            jScrollPane2.setVerticalScrollBarPolicy(JScrollPane.
                                                    VERTICAL_SCROLLBAR_ALWAYS);
            jScrollPane2.setPreferredSize(new Dimension(700, 100));
            this.setLayout(borderLayout8);
            jPanel2.setBackground(Color.lightGray);
            jPanel2.setPreferredSize(new Dimension(700, 850));
            jPanel7.setBackground(Color.lightGray);
            jPanel8.setBackground(Color.lightGray);
            jPanel9.setBackground(Color.lightGray);
            jPanel10.setBackground(Color.lightGray);
            jPanel11.setBackground(Color.lightGray);
            jScrollPane1.setVerticalScrollBarPolicy(JScrollPane.
                                                    VERTICAL_SCROLLBAR_ALWAYS);
            jScrollPane1.setMinimumSize(new Dimension(300, 470));
            jScrollPane1.setPreferredSize(new Dimension(470, 470));
            jPanel13.setBackground(Color.lightGray);
            jPanel14.setBackground(Color.lightGray);
            jPanel14.setLayout(borderLayout9);
            jPanel15.setBackground(Color.lightGray);
            jPanel15.setLayout(borderLayout10);
            jPanel16.setBackground(Color.lightGray);
            jPanel16.setPreferredSize(new Dimension(10, 7));
            jPanel19.setBackground(Color.lightGray);
            jPanel18.setBackground(Color.lightGray);
            jPanel18.setPreferredSize(new Dimension(280, 33));
            jPanel18.setLayout(flowLayout1);
            jPanel17.setBackground(Color.lightGray);
            jButton2.setBackground(Color.lightGray);
            jButton2.setPreferredSize(new Dimension(83, 23));
            jButton2.setHorizontalAlignment(SwingConstants.CENTER);
            jButton2.setHorizontalTextPosition(SwingConstants.CENTER);
            jButton2.setText("Open");
            jButton2.addActionListener(new NoteTagger_jButton2_actionAdapter(this));
            jPanel5.setPreferredSize(new Dimension(500, 560));
            jPanel6.setBackground(Color.lightGray);
            jPanel6.setMinimumSize(new Dimension(217, 550));
            jPanel6.setPreferredSize(new Dimension(500, 560));
            jPanel22.setBackground(Color.lightGray);
            jPanel22.setLayout(borderLayout15);
            jScrollPane5.setHorizontalScrollBarPolicy(JScrollPane.
                                                      HORIZONTAL_SCROLLBAR_AS_NEEDED);
            jScrollPane5.setVerticalScrollBarPolicy(JScrollPane.
                                                    VERTICAL_SCROLLBAR_ALWAYS);
            jScrollPane5.setMaximumSize(new Dimension(32767, 245));
            jScrollPane5.setMinimumSize(new Dimension(300, 470));
            jScrollPane5.setPreferredSize(new Dimension(300, 470));
            jLabel1.setFont(new java.awt.Font("Dialog", Font.PLAIN, 20));
            jLabel1.setToolTipText("");
            jLabel1.setHorizontalAlignment(SwingConstants.CENTER);
            jLabel1.setHorizontalTextPosition(SwingConstants.CENTER);
            jLabel1.setText("Cheshire Parish Register Database Note Tagging System");
            jPanel27.setBackground(Color.lightGray);
            jTextArea3.setMaximumSize(new Dimension(2147483647, 2147483647));
            jTextArea1.setDocument(document1);
            jTextArea3.setMaximumSize(new Dimension(2147483647, 2147483647));
            jTextArea3.setDocument(document2);
            jButton1.setBackground(Color.lightGray);
            jButton1.setPreferredSize(new Dimension(83, 23));
            jButton1.setHorizontalAlignment(SwingConstants.CENTER);
            jButton1.setHorizontalTextPosition(SwingConstants.CENTER);
            jButton1.setText("Save");
            jButton1.addActionListener(new NoteTagger_jButton1_actionAdapter(this));
            jButton1.setEnabled(false);
            this.setBackground(Color.lightGray);
            jPanel1.setBorder(BorderFactory.createRaisedBevelBorder());
            jPanel1.setPreferredSize(new Dimension(1000, 750));
            jPanel20.setLayout(borderLayout16);
            jTextField1.setPreferredSize(new Dimension(62, 25));
            jTextField1.setText("");
            jPanel24.setBackground(Color.lightGray);
            jPanel24.setMaximumSize(new Dimension(10, 10));
            jPanel25.setLayout(borderLayout18);
            jTextField2.setMaximumSize(new Dimension(62, 25));
            jTextField2.setPreferredSize(new Dimension(62, 25));
            jTextField2.setText("");
            jPanel26.setBackground(Color.lightGray);
            jPanel26.setMaximumSize(new Dimension(10, 10));
            jPanel25.setPreferredSize(new Dimension(470, 505));
            jPanel12.setPreferredSize(new Dimension(300, 40));
            jPanel12.setLayout(borderLayout5);
            jPanel28.setBackground(Color.lightGray);
            jPanel21.setBackground(Color.lightGray);
            jPanel23.setBackground(Color.lightGray);
            jButton6.setBackground(Color.lightGray);
            jButton6.setPreferredSize(new Dimension(83, 23));
            jButton6.setText("Save");
            jButton6.setEnabled(false);
            jButton6.addActionListener(new NoteTagger_jButton6_actionAdapter(this));
            jButton7.setBackground(Color.lightGray);
            jButton7.setPreferredSize(new Dimension(83, 23));
            jButton7.setText("Query");
            jButton7.addActionListener(new NoteTagger_jButton7_actionAdapter(this));
            jFileChooser1.addChoosableFileFilter( new FileFilter1() );
            jFileChooser1.setAcceptAllFileFilterUsed( false );
            jFileChooser1.setMultiSelectionEnabled( false );
            jFileChooser1.setSelectedFile( null );
            jFileChooser2.addChoosableFileFilter( new FileFilter2() );
            jFileChooser2.setAcceptAllFileFilterUsed( false );
            jFileChooser2.setMultiSelectionEnabled( false );
            jFileChooser2.setSelectedFile( null );
            jButton3.setMaximumSize(new Dimension(83, 23));
            jButton3.setMinimumSize(new Dimension(83, 23));
            jButton3.setPreferredSize(new Dimension(83, 23));
            jButton3.setText("New");
            jButton3.addActionListener(new NoteTagger_jButton3_actionAdapter(this));
            jPanel1.add(jPanel2, java.awt.BorderLayout.CENTER);
            jPanel1.add(jPanel3, java.awt.BorderLayout.SOUTH);
            jScrollPane2.getViewport().add(jTextArea4);
            this.add(jPanel1, java.awt.BorderLayout.CENTER);
            jPanel3.add(jScrollPane2, java.awt.BorderLayout.CENTER);
            jPanel3.add(jPanel8, java.awt.BorderLayout.SOUTH);
            jPanel3.add(jPanel9, java.awt.BorderLayout.WEST);
            jPanel3.add(jPanel10, java.awt.BorderLayout.EAST);
            jPanel3.add(jPanel11, java.awt.BorderLayout.NORTH);
            jPanel5.add(jPanel7, java.awt.BorderLayout.WEST);
            jPanel5.add(jPanel13, java.awt.BorderLayout.EAST);
            jPanel5.add(jPanel20, java.awt.BorderLayout.CENTER);
            jPanel14.add(jPanel16, java.awt.BorderLayout.SOUTH);
            jPanel14.add(jPanel15, java.awt.BorderLayout.NORTH);
            jPanel15.add(jPanel19, java.awt.BorderLayout.WEST);
            jPanel15.add(jPanel17, java.awt.BorderLayout.EAST);
            jPanel15.add(jPanel18, java.awt.BorderLayout.CENTER);
            jPanel4.add(jLabel1, java.awt.BorderLayout.CENTER);
            jPanel18.add(jButton2);
            jPanel18.add(jButton1);
            jPanel20.add(jTextField1, java.awt.BorderLayout.NORTH);
            jPanel5.add(jPanel14, java.awt.BorderLayout.NORTH);
            jScrollPane1.getViewport().add(jTextArea1);
            jPanel25.add(jScrollPane5, java.awt.BorderLayout.SOUTH);
            jPanel25.add(jTextField2, java.awt.BorderLayout.NORTH);
            jPanel25.add(jPanel26, java.awt.BorderLayout.CENTER);
            jPanel6.add(jPanel12, java.awt.BorderLayout.NORTH);
            jScrollPane5.getViewport().add(jTextArea3);
            jPanel6.add(jPanel27, java.awt.BorderLayout.EAST);
            jPanel1.add(jPanel4, java.awt.BorderLayout.NORTH);
            jPanel1.add(jPanel5, java.awt.BorderLayout.WEST);
            jPanel1.add(jPanel6, java.awt.BorderLayout.EAST);
            jPanel6.add(jPanel22, java.awt.BorderLayout.WEST);
            jPanel6.add(jPanel25, java.awt.BorderLayout.CENTER);
            jPanel12.add(jPanel28, java.awt.BorderLayout.WEST);
            jPanel21.add(jButton7);
            jPanel21.add(jButton6);
            jPanel21.add(jButton3);
            jPanel12.add(jPanel23, java.awt.BorderLayout.EAST);
            jPanel12.add(jPanel21, null);
            jPanel20.add(jPanel24, java.awt.BorderLayout.CENTER);
            jPanel20.add(jScrollPane1, java.awt.BorderLayout.SOUTH);
        //Start the applet
        public void start() {
        //Stop the applet
        public void stop() {
        //Destroy the applet
        public void destroy() {
        //Get Applet information
        public String getAppletInfo() {
            return "Applet Information";
        //Get parameter info
        public String[][] getParameterInfo() {
            return null;
        // Open named file; read text from file into jTextArea1; report to statusBar.
         void openFile(String fileName) {
             try {
                 // Open a file of the given name.
                 File file = new File(fileName);
                 // Get the size of the opened file.
                 int size = (int) file.length();
                 // Set to zero a counter for counting the number of
                 // characters that have been read from the file.
                 int chars_read = 0;
                 // Create an input reader based on the file, so we can read its data.
                 // FileReader handles international character encoding conversions.
                 FileReader in = new FileReader(file);
                 // Create a character array of the size of the file,
                 // to use as a data buffer, into which we will read
                 // the text data.
                 char[] data = new char[size];
                 // Read all available characters into the buffer.
                 while (in.ready()) {
                     // Increment the count for each character read,
                     // and accumulate them in the data buffer.
                     chars_read += in.read(data, chars_read, size - chars_read);
                 in.close();
                 // Create a temporary string containing the data,
                 // and set the string into the JTextArea.
                 jTextArea1.setText(new String(data, 0, chars_read));
                 // Cache the currently opened filename for use at save time...
                 this.currFileName = fileName;
                 jButton1.setEnabled(true);
            jTextArea4.append('\n'+"Opnened "+ currFileName);
      catch (IOException e) {
        jTextArea4.append('\n'+"Error opening "+fileName);
        // Save current file; handle not yet having a filename; report to statusBar.
    boolean saveFile() {
        // Handle the case where we don't have a file name yet.
        if (currFileName == null) {
            return saveAsFile();
        try {
        // Open a file of the current name.
        File file = new File (currFileName);
        // Create an output writer that will write to that file.
        // FileWriter handles international characters encoding conversions.
        FileWriter out = new FileWriter(file);
        String text = jTextArea1.getText();
        out.write(text);
        out.close();
        jButton1.setEnabled(false);
                return true;
      catch (IOException e) {
        jTextArea4.append('\n'+"Error saving "+ currFileName);
      return false;
        // Save current file; handle not yet having a filename; report to statusBar.
        boolean saveFile2() {
            // Handle the case where we don't have a file name yet.
        if (currFileName2 == null) {
            return saveAsFile2();
        try {
        // Open a file of the current name.
        File file = new File (currFileName2);
        // Create an output writer that will write to that file.
        // FileWriter handles international characters encoding conversions.
        FileWriter out = new FileWriter(file);
        String text = jTextArea3.getText();
        out.write(text);
        out.close();
        jButton7.setEnabled(false);
                return true;
      catch (IOException e) {
        jTextArea4.append('\n'+"Error saving "+ currFileName2);
      return false;
        // Save current file, asking user for new destination name.
    // Report to statusBar.
        boolean saveAsFile() {
          // Use the SAVE version of the dialog, test return for Approve/Cancel
          if (JFileChooser.APPROVE_OPTION == jFileChooser1.showSaveDialog(this)) {
            // Set the current file name to the user's selection,
            // then do a regular saveFile
            currFileName = jFileChooser1.getSelectedFile().getPath();
            //repaints menu after item is selected
            this.repaint();
            return saveFile();
          else {
            this.repaint();
            return false;
        // Save current file, asking user for new destination name.
    // Report to statusBar.
        boolean saveAsFile2() {
          // Use the SAVE version of the dialog, test return for Approve/Cancel
          if (JFileChooser.APPROVE_OPTION == jFileChooser2.showSaveDialog(this)) {
            // Set the current file name to the user's selection,
            // then do a regular saveFile
            currFileName2 = jFileChooser2.getSelectedFile().getPath();
            //repaints menu after item is selected
            this.repaint();
            return saveFile();
          else {
            this.repaint();
            return false;
        public void jButton1_actionPerformed(ActionEvent e) {
            saveFile();
            // Display the name of the saved directory+file in the statusBar.
            jTextArea4.append('\n'+"Saved to " + currFileName);
        public void jButton7_actionPerformed(ActionEvent e) {
            try{
                getAppletContext().showDocument(new URL("http://www.csc.liv.ac.uk/~cprdb/Live/v3.3/database.html"), "_blank" );
            catch (MalformedURLException ex)
                ex.printStackTrace();
            jButton6.setEnabled(true);
        public void jButton6_actionPerformed(ActionEvent e) {
            saveFile2();
            // Display the name of the saved directory+file in the statusBar.
            jTextArea4.append('\n'+"Saved to " + currFileName2);
        public void jButton3_actionPerformed(ActionEvent e) {
         // Handle the File|New menu item.
         // Clears the text of the text area.
         jTextArea3.setText("");
         currFileName2 = null;
         jButton6.setEnabled(true);
         jButton7.setEnabled(false);
        public void jButton2_actionPerformed(ActionEvent e) {
                // Use the OPEN version of the dialog, test return for Approve/Cancel
            if (JFileChooser.APPROVE_OPTION == jFileChooser1.showOpenDialog(this)) {
        // Call openFile to attempt to load the text from file into TextArea
                openFile(jFileChooser1.getSelectedFile().getPath());
                  this.repaint();
    class NoteTagger_jButton3_actionAdapter implements ActionListener {
        private NoteTagger adaptee;
        NoteTagger_jButton3_actionAdapter(NoteTagger adaptee) {
            this.adaptee = adaptee;
        public void actionPerformed(ActionEvent e) {
            adaptee.jButton3_actionPerformed(e);
    class NoteTagger_jButton6_actionAdapter implements ActionListener {
            private NoteTagger adaptee;
            NoteTagger_jButton6_actionAdapter(NoteTagger adaptee) {
                this.adaptee = adaptee;
            public void actionPerformed(ActionEvent e) {
                adaptee.jButton6_actionPerformed(e);
        class NoteTagger_jButton7_actionAdapter implements ActionListener {
            private NoteTagger adaptee;
            NoteTagger_jButton7_actionAdapter(NoteTagger adaptee) {
                this.adaptee = adaptee;
            public void actionPerformed(ActionEvent e) {
                adaptee.jButton7_actionPerformed(e);
    class NoteTagger_jButton2_actionAdapter implements ActionListener {
        private NoteTagger adaptee;
        NoteTagger_jButton2_actionAdapter(NoteTagger adaptee) {
            this.adaptee = adaptee;
        public void actionPerformed(ActionEvent e) {
            adaptee.jButton2_actionPerformed(e);
    class NoteTagger_jButton1_actionAdapter implements ActionListener {
        private NoteTagger adaptee;
        NoteTagger_jButton1_actionAdapter(NoteTagger adaptee) {
            this.adaptee = adaptee;
        public void actionPerformed(ActionEvent e) {
            adaptee.jButton1_actionPerformed(e);
    class FileSelectorUtils {
              public static String getExtension( File file ) {
              return getExtension( file.getName() );
                    private static String getExtension( String str ) {
              String ext = null;
              int i = str.lastIndexOf( '.' );
                  if( i > 0 && i < str.length() - 1) {
                     ext = str.substring( i + 1 ).toLowerCase();
              return ext;
              public static File ensureExtension( File file, String ext ) {
                  if( getExtension( file ) == null ) {
                      file = new File( file.getAbsolutePath() + "." + ext );
                  return file;
          class FileFilter1 extends FileFilter {
             // Valid File Extension
             public final static String txt = "txt";
                  public boolean accept( File f ) {
             // Display Directory
             if( f.isDirectory() ) { return true; }
             // Get File's Extension
             String extension = FileSelectorUtils.getExtension( f );
             // Accept Select File Extensions
             if( extension != null ) {
    if( extension.equals( FileFilter1.txt ) ) { return true; } // Accept *.ann
            // Else Deny File
            return false;
            public String getDescription() {
            return "Text Doument (*.txt)";
            class FileFilter2 extends FileFilter {
             // Valid File Extension
             public final static String html = "html";
                  public boolean accept( File f ) {
             // Display Directory
             if( f.isDirectory() ) { return true; }
             // Get File's Extension
             String extension = FileSelectorUtils.getExtension( f );
             // Accept Select File Extensions
             if( extension != null ) {
    if( extension.equals( FileFilter2.html ) ) { return true; } // Accept *.ann
            // Else Deny File
            return false;
            public String getDescription() {
            return "HTML Document (*.html)";
            }Any ideas? I could do with help ASAP if anybody has any ideas... Thanks
    Mike

    The apps listed at java-tips.org are just some of those that happen to be written in Java. If you want an editor that does syntax highlighting and other programming-specific tasks, you have dozens more options. A few Windows editors that spring to mind are EditPad, Crimson Editor, Scite, UltraEdit and Notetab. Then there are the old Unix standys, Emacs and vi, which have Windows versions as well. I use EditPad Pro, which isn't free like many of the others, but is worth the money anyway, IMO.

  • Geting a SCROLL BAR to scroll

    hi i have create this application using JBuilder6 and it has a JTextArea within a JPanel, but i cannot get the text to scroll.
    Any comments welcomed.
    d code:
    package com.borland.samples.gary;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    * <p>Author: </p>
    * <p>Description: </p>
    * <p>Copyright: Copyright (c) 2003</p>
    * <p>Company: </p>
    * @author unascribed
    * @version 1.0
    public class Frame1 extends JFrame {
      JPanel contentPane;
      JButton jButton1 = new JButton();
      FlowLayout flowLayout1 = new FlowLayout();
      JButton jButton2 = new JButton();
      JButton jButton3 = new JButton();
      JButton jButton4 = new JButton();
      JScrollPane jScrollPane1 = new JScrollPane();
      JTextArea jTextArea2 = new JTextArea();
      Border border1;
      //Construct the frame
      public Frame1() {
        enableEvents(AWTEvent.WINDOW_EVENT_MASK);
        try {
          jbInit();
        catch(Exception e) {
          e.printStackTrace();
      //Component initialization
      private void jbInit() throws Exception  {
        //setIconImage(Toolkit.getDefaultToolkit().createImage(Frame1.class.getResource("[Your Icon]")));
        contentPane = (JPanel) this.getContentPane();
        border1 = BorderFactory.createEmptyBorder();
        jButton1.setText("jButton1");
        contentPane.setLayout(flowLayout1);
        this.setSize(new Dimension(400, 300));
        this.setTitle("Frame Title");
        jButton2.setText("jButton2");
        jButton3.setText("jButton3");
        jButton4.setText("jButton4");
        jTextArea2.setPreferredSize(new Dimension(250, 170));
        jTextArea2.setMargin(new Insets(3, 3, 3, 3));
        jTextArea2.setLineWrap(true);
        jTextArea2.setWrapStyleWord(true);
        jScrollPane1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        jScrollPane1.setViewportBorder(border1);
        jScrollPane1.setNextFocusableComponent(jTextArea2);
        jScrollPane1.addMouseListener(new java.awt.event.MouseAdapter() {
          public void mousePressed(MouseEvent e) {
            jScrollPane1_mousePressed(e);
        contentPane.add(jButton1, null);
        contentPane.add(jButton2, null);
        contentPane.add(jButton3, null);
        contentPane.add(jButton4, null);
        contentPane.add(jScrollPane1, null);
        jScrollPane1.getViewport().add(jTextArea2, null);
      //Overridden so we can exit when window is closed
      protected void processWindowEvent(WindowEvent e) {
        super.processWindowEvent(e);
        if (e.getID() == WindowEvent.WINDOW_CLOSING) {
          System.exit(0);
      void jScrollPane1_mousePressed(MouseEvent e) {
        jTextArea2.append("mouussee pressed");
    }cheers Brendan2003

    Change jTextArea2.setPreferredSize() to jScrollPane1.setPreferredSize(). As it stands now, you are telling the text area that you don't want it to change size, if at all possible, so it doesn't.

  • Dropdown Menu bar being hidden by the Textarea

    My problem is that the menu bar does show up, but the text area is over the dropdown menu. You can see the drop down menu start but then is hidden under the textarea. I hope that a good enough discription.
    The frame is a typical JFrame that contains a BorderLayout. My class TheFrame is an extention of JFrame. In the CenterPanel I have a Text area. In the south panel I have another BorderLayout with a text area as the center and a button for the east panel. The menu is going under the text area in the center panel. This might be a bug with the borderlayout?
    public TheFrame(){
    super("Com");
    getContentPane().setLayout(new BorderLayout());
    JMenuBar menuBar = new JMenuBar();
    setJMenuBar(menuBar);
    menuBar.add(getMyMenuBar());
    getContentPane().add(getCenterPanel(), BorderLayout.CENTER);
    getContentPane().add(getSouthPanel(), BorderLayout.SOUTH);
    pack();
    private JMenu getMyMenuBar(){
    JMenu menu = new JMenu("File");
    menu.add(createConnectItem());
    menu.add(new JMenuItem("test"));
    return menu;
    private JMenuItem createConnectItem(){
    JMenuItem connect = new JMenuItem("New");
    ActionListener listener = new ConnectMenuItemActionListener(com);
    connect.addActionListener(listener);
    return connect;
    }

    I don't see the textarea in the code you posted.
    But I know that the described problem comes up when
    you use "TextArea" unstead of "JTextArea".
    "TextArea" is an awt component and "JTextArea" is
    the corresponding swing component. You should not
    mix awt and swing components in the same GUI.
    However, "TextArea" has the scrolling facility already included.
    With "JTextArea" you must use JScrollPane if you need
    scrolling.
            JScrollPane scrollpane = new JScrollPane();
            JTextArea textarea = new JTextArea();
            scrollpane.setViewportView(textarea);

  • Networking system

    Dear all,
    I'm doing my homework and it is very closed to the deadline, pls. help!
    The question is:
    Develop a chat system which allows at most 5 clients to chat online. The client window should have the following entities:
    ?     a text area (called text1) which allows the client to type in a message;
    ?     a button (called submit button) which allows the client to submit the typed message;
    ?     a text area (called text2) which is used to show all the messages typed by all the served clients;
    ?     a button (called quit button) which allows the user to quite at any time;
    ?     a label (called message label) which is used to show messages from the server.
    The operation of the system is:
    When a client start, it will try to connect to the server. When it is connected, a welcome message will be displayed on message label. Then, if there are less than 5 clients being served, the new client will be served immediately. Otherwise, it has to joint a queue waiting for a served client to quit. If a client has to wait, a message would be displayed on message label telling him/her to wait. If a client is ready to be served, a message will be displayed on message label telling him/her that it is being served.
    When a client is connected to a server, it will be assigned a client number sequentially. This means that the first client will be client 1, the second will be client 2 etc.
    Originally, both text1 and text2 are non-editable. When the client is served, text1 would become editable and allow user to type in anytime. When submit button is pressed, the message in text1 would be appended to all served clients' text2 including the one who sends the message. Then, text1 of the sender would be cleared. The following is an example of what is displayed in text2:
    client 2: Hello!
    client 1: Long time no see!
    client 3: Have you done TMA3?
    client 2: I have done it. It is very easy.
    A user can disconnect from the server by pressing the quit button at anytime. The client window would disappear. Then, the first client waiting at the queue would be served.
    I havd write some java programme and not completed:
    package Q1;
    import java.awt.*;
    import javax.swing.*;
    import java.net.*;
    import java.io.*;
    import java.awt.event.*;
    public class ClientFrame extends JFrame implements Runnable{
      GridLayout gridLayout1 = new GridLayout();
      JPanel jPanel1 = new JPanel();
      JPanel jPanel2 = new JPanel();
      JPanel jPanel3 = new JPanel();
      JScrollPane jScrollPane1 = new JScrollPane();
      BorderLayout borderLayout1 = new BorderLayout();
      DefaultComboBoxModel model=new  DefaultComboBoxModel();
      JList jList1 = new JList(model);
      JPanel jPanel4 = new JPanel();
      JLabel jLabel1 = new JLabel();
      BorderLayout borderLayout2 = new BorderLayout();
      JPanel jPanel5 = new JPanel();
      BorderLayout borderLayout3 = new BorderLayout();
      JPanel jPanel6 = new JPanel();
      JScrollPane jScrollPane2 = new JScrollPane();
      JScrollPane jScrollPane3 = new JScrollPane();
      JTextArea jTextArea1 = new JTextArea();
      JTextArea jTextArea2 = new JTextArea();
      JLabel jLabel2 = new JLabel("Chat List");
      JLabel jLabel4 = new JLabel("Chating");
      JTextField jTextField1 = new JTextField();
      JButton jButton1 = new JButton();
      JPanel jPanel7 = new JPanel();
      JButton jButton2 = new JButton();
      DataInputStream in;
      DataOutputStream out;
      Reader reader;
      Writer writer;
      JLabel jLabel3 = new JLabel();
        GridLayout gridLayout2 = new GridLayout();
      /** Creates a new instance of ClientFrame */
      public ClientFrame() throws HeadlessException {
        try {
          jbInit();
          setSize(400,600);
        catch(Exception e) {
          e.printStackTrace();
      public void start(){
            printMessage("Get ready");
        public void result(boolean result){
            try{
                out.writeInt(ClientThread.END);
            catch (Exception e){
                e.printStackTrace();
        public void printMessage(String message){
            jLabel1.setText(message);
            this.validate();
            repaint();
      private void jbInit() throws Exception {
        gridLayout1.setColumns(1);
        gridLayout1.setRows(0);
        this.getContentPane().setLayout(gridLayout1);
        jPanel1.setLayout(borderLayout1);
        jPanel3.setLayout(borderLayout2);
        jPanel2.setLayout(borderLayout3);
        jButton1.setText("Quit");
        jButton1.addActionListener(new ClientFrame_jButton1_actionAdapter(this));
        jLabel1.setText("");
        jTextArea1.setEditable(false);
        jTextArea1.setText("");
        jTextArea2.setEditable(false);
        jTextArea2.setText("");
        jButton2.setEnabled(false);
        jButton2.setText("Submit");
        jButton2.addActionListener(new ClientFrame_jButton2_actionAdapter(this));
        jPanel4.setLayout(gridLayout2);
        gridLayout2.setColumns(1);
        gridLayout2.setRows(2);
        this.getContentPane().add(jPanel1, null);
        jPanel1.add(jScrollPane1,  BorderLayout.CENTER);
        jPanel1.add(jPanel4, BorderLayout.NORTH);
        jPanel4.add(jLabel3, null);
        jPanel4.add(jLabel1, null);
        jScrollPane1.getViewport().add(jList1, null);
        this.getContentPane().add(jPanel3, null);
        jPanel3.add(jPanel5, BorderLayout.NORTH);
        jPanel5.add(jLabel2, null);
        jPanel3.add(jScrollPane3, BorderLayout.CENTER);
        jScrollPane3.getViewport().add(jTextArea1, null);
        this.getContentPane().add(jPanel2, null);
        jPanel2.add(jPanel6, BorderLayout.SOUTH);   
        jPanel6.add(jButton2, null);
        jPanel6.add(jButton1, null);
        jPanel2.add(jScrollPane2, BorderLayout.CENTER);
        jPanel2.add(jPanel7, BorderLayout.NORTH);
        jPanel7.add(jLabel4, null);
        jScrollPane2.getViewport().add(jTextArea2, null);
        printMessage("Welcome to the chat, We are waiting for some more players");
      private void addClient(int id) {
        String idString="Client "+id;
        model.addElement(idString);
      private void removeClient(int id) {
        String idString="Client "+id;
        for (int i=0;i<model.getSize();i++) {
          String temp=(String)model.getElementAt(i);
          if (idString.equals(temp)) {
            model.removeElementAt(i);
            break;
    public void run(){
         try{
             while (true){
                 int mode = in.readInt();
                 switch (mode) {
                     case ClientThread.START:
                     start();
                     break;
                     case ClientThread.END:
                     boolean result = in.readBoolean();
                     result(result);
                     break;
         catch (Exception e){
             e.printStackTrace();
      public static void main(String st[]) {
        try {
          ClientFrame client=new ClientFrame();
          client.addWindowListener(
              new java.awt.event.WindowAdapter() {
                public void windowClosing(java.awt.event.WindowEvent ee) {
                  System.exit(0);
          client.setVisible(true);
          client.out.flush();
          int id=client.in.readInt();
          client.jLabel1.setText("You are client "+id);
          boolean cont=true;
          while (cont) {
            int command=client.in.readInt();
            switch (command) {
              case ClientThread.ADDCLIENT: int cid=client.in.readInt();
                client.addClient(cid);
                break;
              case ClientThread.REMOVECLIENT: cid=client.in.readInt();
                client.removeClient(cid);
                break;
              case ClientThread.START: cid=client.in.readInt();
                int result=JOptionPane.showConfirmDialog(null,"Client "+cid+" has invited you for a chating");
                client.out.writeInt(ClientThread.START);
                client.out.writeInt(cid);
                client.out.writeBoolean(result==JOptionPane.YES_OPTION);
                client.out.flush();
                if (result==JOptionPane.YES_OPTION) {
                  cont=false;
                  client.out.writeInt(ClientThread.END);
                 Thread thread=new Thread(client);
                  thread.start();
                  client.jLabel3.setText("You are connected with client "+cid);
                break;
          char buffer[]=new char[1000];
          client.jButton1.setEnabled(false);
          client.model.removeAllElements();
          client.jTextArea2.setEditable(true);
          client.jButton2.setEnabled(true);
          while (true) {
            int no=client.reader.read(buffer);
            String text=new String(buffer,0,no);
            client.jTextArea1.append(text+"\n");
        catch (Exception e) {
          e.printStackTrace();
      void jButton1_actionPerformed(ActionEvent e) {
        try {
          int cid=Integer.parseInt(this.jTextField1.getText());
          out.writeInt(ClientThread.END);
          out.writeInt(cid);
          out.flush();
        catch (Exception ee) {
          ee.printStackTrace();
      void jButton2_actionPerformed(ActionEvent e) {
        try {
          String text = jTextArea2.getText();
          writer.write(text);
          writer.flush();
          jTextArea2.setText("");
        catch (Exception ee) {
          ee.printStackTrace();
    class ClientFrame_jButton1_actionAdapter implements java.awt.event.ActionListener {
      ClientFrame adaptee;
      ClientFrame_jButton1_actionAdapter(ClientFrame adaptee) {
        this.adaptee = adaptee;
      public void actionPerformed(ActionEvent e) {
        adaptee.jButton1_actionPerformed(e);
    class ClientFrame_jButton2_actionAdapter implements java.awt.event.ActionListener {
      ClientFrame adaptee;
      ClientFrame_jButton2_actionAdapter(ClientFrame adaptee) {
        this.adaptee = adaptee;
      public void actionPerformed(ActionEvent e) {
        adaptee.jButton2_actionPerformed(e);
    package Q1;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    public class ClientThread extends Thread{
        final public static int END = 1,
                START = 0,
                ADDCLIENT = 2,
                REMOVECLIENT = 3,
                ACCEPTED = 4;
        private Integer id;
        private static int noClients = 0;
        private Socket socket;
        private DataInputStream in;
        private DataOutputStream out;
        //private java.net.InetAddress address;
        //int port;
        Server server;
        /** Creates a new instance of Class */
        public ClientThread(Server _server, Socket _socket) {
            try{
                socket = _socket;
                in = new DataInputStream(socket.getInputStream());
                out = new DataOutputStream(socket.getOutputStream());
                server = _server;
                id = new Integer(++noClients);
               catch (Exception e){
                   e.printStackTrace();
            server.putClient(this);
        public Integer getId(){
            return id;
        synchronized public void addClient(Integer id){
            try{
                out.writeInt(ADDCLIENT);
                out.writeInt(id.intValue());
                out.flush();
            catch (Exception e){
                e.printStackTrace();
        synchronized public void removeClient(Integer id){
            try{
                out.writeInt(REMOVECLIENT);
                out.writeInt(id.intValue());
                out.flush();
            catch (Exception e){
                e.printStackTrace();
        public void begin(ClientThread from){
            try{
                out.writeInt(START);
                out.writeInt(from.getId().intValue());
                out.flush();
            catch (Exception e){
                e.printStackTrace();
        public void run(){
            try{
                while(true){
                    int mode = in.readInt();
                    switch(mode){
                        case END:
                            break;                   
                catch (Exception e){
                    e.printStackTrace();
    package Q1;
    import java.util.*;
    import java.net.*;
    * @author  Administrator
    public class Server extends Thread{
        final static int MIN = 2, MAX = 5;
        Vector clients = new Vector();
        ClientThread[] players;
        Hashtable hashtableClients = new Hashtable();
        synchronized void putClient(ClientThread client){
            Iterator iter = hashtableClients.values().iterator();
            while (iter.hasNext()){
                ClientThread temp = (ClientThread) iter.next();
                temp.addClient(client.getId());
                client.addClient(temp.getId());
           hashtableClients.put(client.getId(), client);
        synchronized public void register(ClientThread thread){
            clients.addElement(thread);
            if(clients.size() >= MIN){
                notify();
        synchronized ClientThread getClient(int id){
            Integer idString = new Integer(id);
            return (ClientThread)hashtableClients.get(idString);
        synchronized public ClientThread[] getPlayers(){
            try {
              if(clients.size() < MIN){
                  wait();
              int no = clients.size() < MAX ? clients.size() : MAX;
              ClientThread[] result = new ClientThread[no];         
              for (int i = 0; i < no; i++){
                  result[i] = getClient(no);
              return result;
            catch (Exception e){
                e.printStackTrace();
                return null;
        /** Creates a new instance of Server */
        public Server() {       
        public void run(){
            try{
             while (true){
                 players = getPlayers();
                 for(int i = 0; i < players.length; i++){
                     players.begin(players[i]);
    catch (Exception e){
    e.printStackTrace();
    * @param args the command line arguments
    public static void main(String[] st) {
    try{
    Server server = new Server();
    server.start();
    ServerSocket sSocket = new ServerSocket(11111);
    while(true){
    Socket socket = sSocket.accept();
    ClientThread client = new ClientThread(server, socket);
    client.start();
    server.register(client);
    catch (Exception e){
    e.printStackTrace();

    I had modify my programme and I still cannot connect the two client and chat. Pls help!!!
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.io.*;
    import java.net.*;
    public class Client extends JFrame {
      GridLayout gridLayout1 = new GridLayout();
      JPanel jPanel1 = new JPanel();
      JPanel jPanel2 = new JPanel();
      JPanel jPanel3 = new JPanel();
      JScrollPane jScrollPane1 = new JScrollPane();
      BorderLayout borderLayout1 = new BorderLayout();
      DefaultComboBoxModel model=new  DefaultComboBoxModel();
      JList jList1 = new JList(model);
      JPanel jPanel4 = new JPanel();
      JLabel jLabel1 = new JLabel();
      BorderLayout borderLayout2 = new BorderLayout();
      JPanel jPanel5 = new JPanel();
      BorderLayout borderLayout3 = new BorderLayout();
      JPanel jPanel6 = new JPanel();
      JScrollPane jScrollPane2 = new JScrollPane();
      JScrollPane jScrollPane3 = new JScrollPane();
      JTextArea jTextArea1 = new JTextArea();
      JTextArea jTextArea2 = new JTextArea();
      JLabel jLabel2 = new JLabel("text2");
      JLabel jLabel4 = new JLabel("text1");
      JLabel jLabel5 = new JLabel("");
      JTextField jTextField1 = new JTextField();
      JButton jButton1 = new JButton();
      JPanel jPanel7 = new JPanel();
      JButton jButton2 = new JButton();
      public Client() throws HeadlessException {
        try {
          jbInit();
          setSize(400,600);
        catch(Exception e) {
          e.printStackTrace();
       private void jbInit() throws Exception {
        gridLayout1.setColumns(1);
        gridLayout1.setRows(0);
        this.getContentPane().setLayout(gridLayout1);
        jPanel1.setLayout(borderLayout1);
        jPanel3.setLayout(borderLayout2);
        jPanel2.setLayout(borderLayout3);
        jButton1.setText("Quit");
        jButton1.addActionListener(new Client_jButton1_actionAdapter(this));
        jLabel1.setText("");
        jTextArea1.setEditable(false);
        jTextArea1.setText("");
        jTextArea2.setEditable(false);
        jTextArea2.setText("");
        jButton2.setEnabled(false);
        jButton2.setText("Submit");
        jButton2.addActionListener(new Client_jButton2_actionAdapter(this));
        jPanel4.setLayout(gridLayout2);
        gridLayout2.setColumns(1);
        gridLayout2.setRows(2);
        this.getContentPane().add(jPanel1, null);
        jPanel1.add(jScrollPane1,  BorderLayout.CENTER);
        jPanel1.add(jPanel4, BorderLayout.NORTH);
        jPanel4.add(jLabel5, null);
        jPanel4.add(jLabel3, null);
        jPanel4.add(jLabel1, null);
        jScrollPane1.getViewport().add(jList1, null);
        this.getContentPane().add(jPanel3, null);
        jPanel3.add(jPanel5, BorderLayout.NORTH);
        jPanel5.add(jLabel2, null);
        jPanel3.add(jScrollPane3, BorderLayout.CENTER);
        jScrollPane3.getViewport().add(jTextArea1, null);
        this.getContentPane().add(jPanel2, null);
        jPanel2.add(jPanel6, BorderLayout.SOUTH);   
        jPanel6.add(jButton2, null);
        jPanel6.add(jButton1, null);
        jPanel2.add(jScrollPane2, BorderLayout.CENTER);
        jPanel2.add(jPanel7, BorderLayout.NORTH);
        jPanel7.add(jLabel4, null);
        jScrollPane2.getViewport().add(jTextArea2, null);
        printMessage("Welcome to the chat");
    public void printMessage(String message){
            jLabel5.setText(message);
            this.validate();
            repaint();
      private void addClient(int id) {
        String idString="Client "+id;
        model.addElement(idString);
      private void removeClient(int id) {
        String idString="Client "+id;
        for (int i=0;i<model.getSize();i++) {
          String temp=(String)model.getElementAt(i);
          if (idString.equals(temp)) {
            model.removeElementAt(i);
            break;
      DataInputStream in;
      DataOutputStream out;
      Reader reader;
      Writer writer;
      JLabel jLabel3 = new JLabel();
        GridLayout gridLayout2 = new GridLayout();
      public static void main(String st[]) {
        int noOfClient = 0;
          try {
          Client client=new Client();
          client.addWindowListener(
              new java.awt.event.WindowAdapter() {
                public void windowClosing(java.awt.event.WindowEvent ee) {
                  System.exit(0);
          client.setVisible(true);
          Socket socket=new Socket("127.0.0.1",12345);
          int port=socket.getLocalPort();
          client.in=new DataInputStream(socket.getInputStream());
          client.out=new DataOutputStream(socket.getOutputStream());
          client.out.writeInt(port);
          client.out.flush();
          int id=client.in.readInt();
          client.jLabel1.setText("You are client "+id);
          boolean cont=true;
          while (cont) {
            int command=client.in.readInt();
            switch (command) {
              case ServerThread.ADDCLIENT: int cid=client.in.readInt();
                client.addClient(cid);
                break;
              case ServerThread.REMOVECLIENT: cid=client.in.readInt();
                client.removeClient(cid);
                break;
              case ServerThread.ACCEPTED:
                cid=client.in.readInt();
                boolean answer=client.in.readBoolean();
                if (answer) {
                  cont = false;
                               client.reader = new InputStreamReader(socket.getInputStream());
                  client.writer = new OutputStreamWriter(socket.getOutputStream());
                  client.jLabel3.setText("You are connected with client "+cid);
                else {
                  JOptionPane.showMessageDialog(null,"Client "+cid+" has denied your invitation");
                break;
              case ServerThread.INVITE: cid=client.in.readInt();
                int result=JOptionPane.showConfirmDialog(null,"Client "+cid+" has invited you for a private conversation");
                client.out.writeInt(ServerThread.ACCEPTED);
                client.out.writeInt(cid);
                client.out.writeBoolean(result==JOptionPane.YES_OPTION);
                client.out.flush();
                if (result==JOptionPane.YES_OPTION) {
                  cont=false;
                  client.out.writeInt(ServerThread.QUIT);
                  socket.close();
                  ServerSocket sSocket=new ServerSocket(port);
                  System.out.println("listen at port "+port);
                  Socket sock=sSocket.accept();
                  client.reader=new InputStreamReader(sock.getInputStream());
                  client.writer=new OutputStreamWriter(sock.getOutputStream());
                  client.jLabel3.setText("You are connected with client "+cid);
                break;
          char buffer[]=new char[1000];
          client.jButton1.setEnabled(false);
          client.model.removeAllElements();
          client.jTextArea2.setEditable(true);
          client.jButton2.setEnabled(true);
          while (true) {
            int no=client.reader.read(buffer);
            String text=new String(buffer,0,no);
            client.jTextArea1.append(text+"\n");
        catch (Exception e) {
          e.printStackTrace();
      void jButton1_actionPerformed(ActionEvent e) {
        try {
         //int cid=Integer.parseInt(this.jTextField1.getText());
          out.writeInt(ServerThread.INVITE);
          //out.writeInt(cid);
          out.flush();
        catch (Exception ee) {
          ee.printStackTrace();
      void jButton2_actionPerformed(ActionEvent e) {
        try {
            String text = jTextArea2.getText();
          writer.write(text);
          writer.flush();
          jTextArea2.setText("");
        catch (Exception ee) {
          ee.printStackTrace();
    class Client_jButton1_actionAdapter implements java.awt.event.ActionListener {
      Client adaptee;
      Client_jButton1_actionAdapter(Client adaptee) {
        this.adaptee = adaptee;
      public void actionPerformed(ActionEvent e) {
        adaptee.jButton1_actionPerformed(e);
    class Client_jButton2_actionAdapter implements java.awt.event.ActionListener {
      Client adaptee;
      Client_jButton2_actionAdapter(Client adaptee) {
        this.adaptee = adaptee;
      public void actionPerformed(ActionEvent e) {
        adaptee.jButton2_actionPerformed(e);
    package online;
    import java.util.*;
    import java.io.*;
    import java.net.*;
    public class Server {
      Hashtable clients = new Hashtable();
      synchronized void putClient(ServerThread client) {
        Iterator iter = clients.values().iterator();
        while (iter.hasNext()) {
          ServerThread temp = (ServerThread) iter.next();
          temp.addClient(client.getId());
          client.addClient(temp.getId());
        clients.put(client.getId(), client);
      synchronized void removeClient(ServerThread client) {
        clients.remove(client.getId());
        Iterator iter = clients.values().iterator();
        while (iter.hasNext()) {
          ServerThread temp = (ServerThread) iter.next();
          temp.removeClient(client.getId());
      notifyAll();
      synchronized ServerThread getClient(int id) {
        Integer idString=new Integer(id);
        return (ServerThread)clients.get(idString);
      public Server() {
      synchronized void invite(ServerThread from, int to) {
        ServerThread toThread=this.getClient(to);
        toThread.invite(from);
      synchronized void accepted(ServerThread to, int from,boolean answer) {
        ServerThread fromThread=this.getClient(from);
        fromThread.accept(to,answer);
      public static void main(String st[]) {
        Server server = new Server();
        try {
          ServerSocket sSocket = new ServerSocket(12345);
          while (true ) {
            Socket socket=sSocket.accept();
            DataInputStream in=new DataInputStream(socket.getInputStream());
            DataOutputStream out=new DataOutputStream(socket.getOutputStream());
            int port=in.readInt();
            (new ServerThread(server,socket.getInetAddress(),port,in,out)).start();
        catch (Exception e) {
          e.printStackTrace();
    package online;
    import java.io.*;
    import java.net.*;
    public class ServerThread
        extends Thread {
      public static final int QUIT = 0,
          INVITE = 1,
          ADDCLIENT = 2,
          REMOVECLIENT = 3,
          ACCEPTED = 4;
      private Integer id;
      private static int noClients = 0;
      private DataInputStream in;
      private DataOutputStream out;
      private java.net.InetAddress address;
      int port;
      Server server;
      public ServerThread(Server server, java.net.InetAddress address, int port,
                          DataInputStream in, DataOutputStream out) {
        this.address = address;
        this.in = in;
        this.out = out;
        this.port = port;
        id = new Integer(++noClients);
        this.server = server;
        try {
          out.writeInt(id.intValue());
        catch (Exception e) {
          e.printStackTrace();
        server.putClient(this);
      public Integer getId() {
        return id;
      synchronized public void addClient(Integer id) {
        try {
          out.writeInt(ADDCLIENT);
          out.writeInt(id.intValue());
          out.flush();
        catch (Exception e) {
          e.printStackTrace();
      synchronized public void removeClient(Integer id) {
        try {
          out.writeInt(REMOVECLIENT);
          out.writeInt(id.intValue());
          out.flush();
        catch (Exception e) {
          e.printStackTrace();
      synchronized public void invite(ServerThread from) {
        try {
          out.writeInt(INVITE);
          out.writeInt(from.getId().intValue());
          out.flush();
        catch (Exception e) {
          e.printStackTrace();
      synchronized public void accept(ServerThread to, boolean answer) {
        try {
          out.writeInt(ACCEPTED);
          out.writeInt(to.id.intValue());
          out.writeBoolean(answer);
          if (answer) {
            String address = to.address.toString().split("/")[1];
            out.writeInt(address.length());
            out.writeChars(address);
            out.writeInt(to.port);
          out.flush();
        catch (Exception e) {
          e.printStackTrace();
      public void run() {
        try {
          boolean cont = true;
          while (cont) {
            int command = in.readInt();
            switch (command) {
              case QUIT:
                cont = false;
                break;
              case INVITE:
                int inviteId = in.readInt();
                server.invite(this,inviteId);
                break;
              case ACCEPTED:
                int acceptId = in.readInt();
                boolean answer = in.readBoolean();
                server.accepted(this, acceptId, answer);
                break;
        catch (Exception e) {
          e.printStackTrace();
        finally {
          server.removeClient(this);
    }

  • Making a seperate frame non resizable

    Is it possible to make a seperate frame non-resizable and if so how? If I set the resizable property of the window then this simply makes the browser non-resizable rather than the seperate frame. Is there some PL/SQL code that can do this for me or is it possible to set this in the forms web config? Thanks for any help
    Dan

    I have tried this method, it looks like it should run, but when i compile it the browser displays................
    "Untitled1.java": Error #: 750 : initialization error: com.borland.compiler.symtab.LoadError: neither class nor source found for java.lang.Object
    public class Untitled1 extends Component {
    public void createPanel()
    JFrame frame = new JFrame();
    frame.setUndecorated(true);
    frame.setLayout(new BorderLayout());
    MyDisplay test = new MyDisplay(frame);
    test.setLayout(new BorderLayout());
    frame.add(test, BorderLayout.CENTER);
    JLabel label = new JLabel("This is just a test");
    test.add(label, BorderLayout.CENTER);
    frame.pack();
    frame.setSize(500, 500);
    // make sure you pack and/or set size first...
    Dimension dS = Toolkit.getDefaultToolkit().getScreenSize();
    Dimension dF = frame.getSize();
    // make sure it's not off screen
    int x = (dS.width/2)-(dF.width/2);
    int y = (dS.height/2)-(dF.height/2);
    if(x < 0) x = 0;
    if(y < 0) y = 0;
    frame.setLocation(x, y);
    frame.setVisible(true);
    contentpane.add(sc);
    jscrollpane sc = new jscrollpane();
    jtextarea ta = new jtextarea();
    /**Main method*/
    public static void main(String[] args) {
    try {
    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    catch(Exception e) {
    e.printStackTrace();
    new untitled1();
    Do you know how i can correct this erreor!

  • Help -- vectors

    i am writing an editor and i have run into a problem.
    I am using vectors to keep track of the documents that
    opened. the documents are displayed in a JTabbedPane
    and i am using a JTextArea for editing them. When i
    try to do go to Select All of i get a bunch of errors.
    here is code that i am using to: add elements to the
    Vector, trying to Select All. And the runtime error
    that occurs when i try the select All on anything but
    the first element in the Vector.
    adding elements to the Vector:
    vector = new Vector();
    vector.addElement(new JTextArea());
    ((JTextArea)vector.lastElement()).setTabSize(2);
    ((JTextArea)vector.lastElement()).setText(text);
    JScrollPane scrollPane = new
    JScrollPane((JTextArea)vector.lastElement());trying to selectAll:
    ((JTextArea)vector.elementAt(tabbedPane.getSelect
    dIndex())).selectAll();error:
    Exception occurred during event dispatching:
    java.lang.ArrayIndexOutOfBoundsException: 1 >= 1
    at java.util.Vector.elementAt(Vector.java:417)
    at
    VisualChange$ItemHandler.actionPerformed(VisualChange.
    ava:589)
    at
    javax.swing.AbstractButton.fireActionPerformed(Abstrac
    Button.java:1450)
    at
    javax.swing.AbstractButton$ForwardActionEvents.actionP
    rformed(AbstractButton.java:1504)
    at
    javax.swing.DefaultButtonModel.fireActionPerformed(Def
    ultButtonModel.java:378)
    at
    javax.swing.DefaultButtonModel.setPressed(DefaultButto
    Model.java:250)
    at
    javax.swing.AbstractButton.doClick(AbstractButton.java
    279)
    at
    javax.swing.plaf.basic.BasicMenuItemUI$MouseInputHandl
    r.mouseReleased(BasicMenuItemUI.java:886)
    at
    java.awt.AWTEventMulticaster.mouseReleased(AWTEventMul
    icaster.java:230)
    at
    java.awt.Component.processMouseEvent(Component.java:37
    7)
    at
    java.awt.Component.processEvent(Component.java:3546)
    at
    java.awt.Container.processEvent(Container.java:1164)
    at
    java.awt.Component.dispatchEventImpl(Component.java:25
    5)
    at
    java.awt.Container.dispatchEventImpl(Container.java:12
    3)
    at
    java.awt.Component.dispatchEvent(Component.java:2499)
    at
    java.awt.LightweightDispatcher.retargetMouseEvent(Cont
    iner.java:2451)
    at
    java.awt.LightweightDispatcher.processMouseEvent(Conta
    ner.java:2216)
    at
    java.awt.LightweightDispatcher.dispatchEvent(Container
    java:2125)
    at
    java.awt.Container.dispatchEventImpl(Container.java:12
    0)
    at
    java.awt.Window.dispatchEventImpl(Window.java:912)
    at
    java.awt.Component.dispatchEvent(Component.java:2499)
    at
    java.awt.EventQueue.dispatchEvent(EventQueue.java:319)
    at
    java.awt.EventDispatchThread.pumpOneEvent(EventDispatc
    Thread.java:103)
    at
    java.awt.EventDispatchThread.pumpEvents(EventDispatchT
    read.java:93)
    at
    java.awt.EventDispatchThread.run(EventDispatchThread.j
    va:84)
    sample code would help a lot. thanks in
    advance: TravenE.

    i hope this is as simple as i think it is.. is this the EXACT code youre using to add new elements: ???
    vector = new Vector();
    vector.addElement(new TextArea());
    ((JTextArea)vector.lastElement()).setTabSize(2);
    ((JTextArea)vector.lastElement()).setText(text);
    JScrollPane scrollPane = new> JScrollPane((JTextArea)vector.lastElement());"""
    cause, what i think is happening, is that youre just creating the new vector each time youre attempting to add elements to it..youre basically deleting the elements in the vector every time you add a new element, so the most elements you can have is one... try this: move the following line:
    " vector = new Vector();"
    move it somewhere else...like in the form constructor or somewhere where it will only execute ONCE.. because right now, you have the vector redefining itself every time a new element is being added.
    anyway, hope it works... sorry if i misread your code. talk to ya later,
    Steven Berardi

Maybe you are looking for

  • What is main diff b/w imported Archives and External Defination in IR

    What is main diff b/w imported Archives and External Defination in IR

  • Com.sap.engine.services.jndi.persistent.exceptions.NamingException

    Hi, We have just finish apply/update our SAP Netweaver WebAS 6.40 (Java) with the support package (SP25). When we test our application, we encountered the following exception com.sap.engine.services.jndi.persistent.exceptions.NamingException: Error g

  • Javax.naming.NamingException

    When I run the following deployment. . . java -jar ../../admin.jar ormi://localhost admin 123456 -deploy -file csldc.ear I get this . . . Error: javax.naming.NamingException: Lookup error: java.net.ConnectException: Co nnection refused: connect; nest

  • My face time camera won't work

    When I click on my camera and I try to switch to my face time camera it shows like it's going to switch but then the camera just goes back and I can't switch it to the other camera for a while. It's been like this for a while and I don't know what to

  • Equium A60 - need drivers for Window2003

    Hi all. I am a student installing a dual boot with linux and windows2003. I could not find in this web site any ATI driver, display driver, infrared driver for windows2003 in order to display movies (DVD) etc in my Laptop. I would really appreciate s