SetText Problem...

Hello all! Well i'm trying to make a simple Set comparison applet. My problem is when i try and compile my script it gives me this error....
C:\.....\SetApplet.java:212: cannot resolve symbol
symbol : method setText (boolean)
location: class java.awt.TextField
          answerField.setText(set1.equals(set2));
So here is my code for the SetApllet....
import java.io.*;
import java.applet.Applet;
import java.applet.*;
import java.awt.event.*;
import java.awt.*;
import java.util.Enumeration;
import java.util.Vector;
import java.lang.*;
public class SetApplet extends Applet implements ActionListener, ItemListener {
private Set set1;
private Set set2;
private Set resultSet;
private Set activeSet; // reference to the currently selected Set (set1 or set2)
private Checkbox set1Selector;
private Checkbox set2Selector;
private CheckboxGroup selectorGroup;
private List set1List; // list showing elements of set1
private List set2List; // list showing elements of set2
private List resultList; // list showing the elements of a result (of union or intersect) Set
private List activeList; // reference to the currently selected List (set1List or set2List)
private Button addButton;
private TextField value, answerField;
private Button intersectButton, complementButton, unionButton, clearButton, equalsButton;
     private Color background, blue, yellow;
     private Panel row0, row1, row2, row3, row4, row5, row6;
     private     Label headerLabel, label1, label2, label3, label4, label5, label6;
     private String subset1, subset2, subsetadd;
public SetApplet() {
     * makePanel is a method that sets the layout and background color of each panel it is called to create.
     * @param lm Set's Layout
     * @param c Set's Background Color of Panel
     * @return returns new button
     private Panel makePanel(LayoutManager lm, Color c) {
          Panel p = new Panel();
          p.setLayout(lm);
          p.setBackground(c);
          return p;
     * makeButton is a method that sets the label and color of each new button that is created.
     * @param label string label to be used on the new button
     * @param color color of the new button
     * @return returns new button
     private Button makeButton(String label, Color color) {
          Button x = new Button(label);
          x.setBackground(color);
          x.setFont(new Font("Verdana", Font.BOLD, 14));
          return x;
* Initialize the Applet
public void init() {
     //--- create Model
     set1 = new Set();
     set2 = new Set();
     //--- create GUI
     background = new Color(54,140,203);
                    //blue = new Color(129,129,218);
                    blue = new Color(54,140,203);
                    yellow = new Color(255,255,102);
     this.setLayout(new FlowLayout(FlowLayout.CENTER,4,1));
     // Checkboxes
     headerLabel = new Label("Choose the set you want to add or clear: ");
     set1Selector = new Checkbox("Set 1");
     set2Selector = new Checkbox("Set 2");
     row0 = makePanel(new FlowLayout(FlowLayout.LEFT,4,2),background);
     row0.add(headerLabel);
     row0.add(set1Selector);
     row0.add(set2Selector);
     // Lists
     row1 = makePanel(new FlowLayout(FlowLayout.LEFT,4,2),background);
     set1List = new List();
     set2List = new List();
     resultList = new List();
     row1.add(new Label("Set 1"));
     row1.add(set1List);
     row1.add(new Label("Set 2"));
     row1.add(set2List);
     row1.add(new Label("Result"));
     row1.add(resultList);
     row2 = makePanel(new FlowLayout(FlowLayout.LEFT,4,2),background);
     addButton = new Button("Add:");
     value = new TextField(5);
     clearButton = new Button("Clear");
     label1 = new Label("Enter an Integer in the text field and press [Add] to add to indicated set: ");
     row2.add(label1);
     row2.add(addButton);
     row2.add(value);
     row3 = makePanel(new FlowLayout(FlowLayout.LEFT,4,2),background);
     label2 = new Label("Press this button to clear sets: ");
     row3.add(label2);
     row3.add(clearButton);
     // Buttons
     row4 = makePanel(new FlowLayout(FlowLayout.LEFT,4,2),background);
     label3 = new Label("Set 1");
     label4 = new Label(" Set 2");
     unionButton = new Button("Union");
     intersectButton = new Button("Intersect");
     complementButton = new Button("Complement");
     row4.add(label3);
     row4.add(unionButton);
     row4.add(intersectButton);
     row4.add(complementButton);
     row4.add(label4);
     //tests
     row5 = makePanel(new FlowLayout(FlowLayout.LEFT,4,2),background);
     label5 = new Label("Test");
     equalsButton = new Button("Equals");
     answerField = new TextField(5);
     row5.add(label5);
     row5.add(equalsButton);
     row5.add(answerField);
     //--- group Checkboxes
     selectorGroup = new CheckboxGroup();
     set1Selector.setCheckboxGroup(selectorGroup);
     set2Selector.setCheckboxGroup(selectorGroup);
     //--- initialize GUI
     selectorGroup.setSelectedCheckbox(set1Selector);
     setActive();
     //--- register Listeners
     set1Selector.addItemListener(this);
     set2Selector.addItemListener(this);
     addButton.addActionListener(this);
     clearButton.addActionListener(this);
     unionButton.addActionListener(this);
     intersectButton.addActionListener(this);
     complementButton.addActionListener(this);
     equalsButton.addActionListener(this);
add(row0);
add(row1);
add(row2);
add(row3);
add(row4);
add(row5);
public void paint(Graphics g) {
               setSize(row1.getSize().width,200);
               validate();
//--- implement ActionListener
* This method is called when one of the Buttons is pushed
public void actionPerformed(ActionEvent ev) {
     Object eventSource = ev.getSource();
     if (eventSource==addButton) {
     // add
     int i = Integer.parseInt(value.getText());
     activeSet.addElement(new Integer(i));
     updateList(activeList, activeSet);
     } else if (eventSource==clearButton) {
     // clear
     activeSet.removeAllElements();
     updateList(activeList, activeSet);
     } else if (eventSource==unionButton) {
     // union
     resultSet = set1.union(set2);
     updateList(resultList, resultSet);
     } else if (eventSource==intersectButton) {
     // intersect
     resultSet = set1.intersection(set2);
     updateList(resultList, resultSet);
     } else if (eventSource==complementButton) {
          // complement
          resultSet = set1.complementWithRespectTo(set2);
          updateList(resultList, resultSet);
     } else if (eventSource==equalsButton) {
          // equals
          answerField.setText(set1.equals(set2));
//--- implement ItemListener
* This method is called, when one of the Checkboxes is selected
public void itemStateChanged(ItemEvent ev) {
     setActive();
//--- private worker methods
* Set activeList and activeSet depending on the selected Checkbox
private void setActive() {
     List newActiveList;
     if (selectorGroup.getSelectedCheckbox()==set1Selector) {
     activeList = set1List;
     activeSet = set1;
     } else {
     activeList = set2List;
     activeSet = set2;
* Set the contents of the List according to the contents of the Set
private void updateList(List list, Set set) {
     if (list.getItemCount() != 0) {
     list.removeAll();
     //--- enumerate loop pattern
     Enumeration en = set.elements();
     while (en.hasMoreElements()) {
     // get next
     Integer i = (Integer)en.nextElement();
     // process
     list.add(i.toString());
Here is my code for my set.java, the equals method is at the bottom.....
import java.io.*;
import java.util.*;
import java.lang.*;
class Set {
     public Set() {
          vector = new Vector();
     public boolean isEmpty() {
          return vector.isEmpty();
     public int size() {
          return vector.size();
     public boolean contains(Object o) {
          Enumeration enum = vector.elements();
          while (enum.hasMoreElements()) {
               Object elem = enum.nextElement();
               if (elem.equals(o))
                    return true;
          return false;
     public void addElement(Object o) {
          if (!contains(o))
               vector.addElement(o);
     public Object copy() {
          Set destSet = new Set();
          Enumeration enum = vector.elements();
          while (enum.hasMoreElements())
               destSet.addElement(enum.nextElement());
          return destSet;
     public Set union(Set s) {
          Set unionSet = (Set)s.copy();
          Enumeration enum = vector.elements();
          while (enum.hasMoreElements())
               unionSet.addElement(enum.nextElement());
          return unionSet;
     public Set intersection(Set s) {
          Set interSet = new Set();
          Enumeration enum = this.vector.elements();
          while (enum.hasMoreElements()) {
               Object elem = enum.nextElement();
               if (s.contains(elem))
                    interSet.addElement(elem);
          return interSet;
     void removeAllElements() {
     vector.removeAllElements();
     Enumeration elements() {
     return vector.elements();
     public void print(PrintStream ps) {
          Enumeration enum = vector.elements();
          while (enum.hasMoreElements()) {
               ps.print(enum.nextElement().toString());
               ps.print(" ");
     //newstuff
     public Set complementWithRespectTo(Set s) {
     // Returns a set containing all elements in s not in the receiver object
     Set complement = new Set();
          Enumeration enum = this.vector.elements();
          while (enum.hasMoreElements()) {
               Object elem = enum.nextElement();
               if (!s.contains(elem))
               complement.addElement(elem);
          return complement;
     public boolean equals(Object right){
     // Returns true if each of the receiver object and s is a subset of
     // the other, and false otherwise
          Enumeration enum = vector.elements();
          while (enum.hasMoreElements()) {
               Object elem = enum.nextElement();
               if (elem.equals(right))
                    return true;
          return false;
Vector vector;
Any thoughts? THANKS ALOT!
I LOVE THIS FORUM!
Paul

Hi
The argument from method setText must to be a string!
One solution:
answerField.setText( (set1.equals(set2) ? "TRUE" : "FALSE") );
Next time post a snippet and explain error not the full source code since most people hate to read long posts and reject the answer.
Regards.

Similar Messages

  • JEditorPane setText problems

    I'm having problems in setting styles after using setText with JEditorPane.
    For example I enter a line of text in the JEditorPane, highlight this in bold and then save it back to file. I then load this line of text back into the JEditorPane using the setText method and I see my highlighted line of bold text. I then go to unmark the bold highlighting of the line and this appears to have been done correctly but when I go to view the contents of the JEditorPane's document I find that the bold hasn't actually been removed from the content but it appears to have done so looking at the JEditorPane.
    Has anyone else had this problem?
    I have found someone who has described a very similar problem at the following link
    http://groups.google.com/groups?q=jeditorpane+setText&hl=en&selm=3B7BEBD2.24EE2EE8%40home.com&rnum=6

    I've had this Problem when I was building a HTML-Editor-Applet.
    The Problem was, that there was a Style-Attribute like e.g. text-decoration:underlined. If I removed the underlined style the Attribut was text-decoration:none, but the getText() method just cared about the Style with the name text-decoration to handle this Element as underlined. I had to build my own getText() method by examing all the Elemntes from the Document and set the html-Tags for the style-attributes.
    Jörn

  • Problems with MaskFormatter and JFormattedTextfield

    Hi,
    I'm new to the forum and Java programming so if anyone is willing to answer this query with a small degree of patience I would be immensely, humbly grateful!
    I'll say firstly that I wrote the program in jdk1.4.2 then recompiled it in 1.6.0 in the vain hope that the problem would go a way, but no such luck.
    Right, I'm using one Formatted textfield with a MaskFormatter on which I change the mask according to what information I want from the user:
    class myFormatter extends MaskFormatter {
              String key;
              public void setMask(String k){
                   key = k;     
                   if (key.equals("text")) {
                        try{
                             super.setMask("*************"); // for text, eg star names
                             super.setValidCharacters("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\u0020");
                        }catch (java.text.ParseException e) {
                        System.err.println("Problem with formatting: " + e.getMessage());
                        System.exit(-1);
                   else if (key.equals("num")) {
                        try{
                        super.setMask("****#"); // for numbers 1-10000 eg frame num
                                    super.setValidCharacters("0123456789\u0020");
                        }catch (java.text.ParseException e) {
                        System.err.println("Problem with formatting: " + e.getMessage());
                        System.exit(-1);
                   else if (key.equals("epoch")) try{
                        super.setMask("####.#"); // for epoch
                        super.setValueContainsLiteralCharacters(true);
                        }catch (java.text.ParseException e) {
                        System.err.println("Problem with formatting: " + e.getMessage());
                        System.exit(-1);
                   else if (key.equals("yna")) try{
                        super.setMask("L"); // for single lower case characters eg y/n/a
                        }catch (java.text.ParseException e) {
                        System.err.println("Problem with formatting: " + e.getMessage());
                        System.exit(-1);
                   else if (key.equals("coord")) try{
                        super.setMask("*## ## ##"); // for RA/Dec
                        super.setValueContainsLiteralCharacters(true);
                        super.setValidCharacters("0123456789+-\u0020");
                        }catch (java.text.ParseException e) {
                        System.err.println("Problem with formatting: " + e.getMessage());
                        System.exit(-1);
                   else if (key.equals("reset")) try{
                        super.setMask("*********************"); // accept anything
                        }catch (java.text.ParseException e) {
                        System.err.println("Problem with formatting: " + e.getMessage());
                        System.exit(-1);
                   else  try{
                        super.setMask("********************"); // accept anything
                        }catch (java.text.ParseException e) {
                        System.err.println("Problem with formatting: " + e.getMessage());
                        System.exit(-1);
    -----------------------------------------------------------------------------------------------------Ok, now I've only gotten as far as checking the implementation of the "epoch", "text", "yna" and "coord" keys. I've discovered two main problems:
    1. The A, ? and H masks in MaskFormatter just simply did not work; the textfield would not let me enter anything, even when setting the valid the characters, hence having to use * for implementing the "text" key.     
    But most importantly:
    2. The "coord" mask will not let me enter anything (example coordinates -32 44 55) and when I try (in particular press the backspace to start entering at the beginning of the ttextfield instead of the middle, where the cursor is put) I presented with this horrendous complaint from the compiler:
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at javax.swing.text.MaskFormatter.isLiteral(MaskFormatter.java:566)
    at javax.swing.text.MaskFormatter.canReplace(MaskFormatter.java:711)
    at javax.swing.text.DefaultFormatter.replace(DefaultFormatter.java:560)
    at javax.swing.text.DefaultFormatter.replace(DefaultFormatter.java:533)
    at javax.swing.text.DefaultFormatter$DefaultDocumentFilter.remove(DefaultFormatter.java:711)
    at javax.swing.text.AbstractDocument.remove(AbstractDocument.java:573)
    at javax.swing.text.DefaultEditorKit$DeletePrevCharAction.actionPerformed(DefaultEditorKit.java:1045)
    at javax.swing.SwingUtilities.notifyAction(SwingUtilities.java:1636)
    at javax.swing.JComponent.processKeyBinding(JComponent.java:2844)
    at javax.swing.JComponent.processKeyBindings(JComponent.java:2879)
    at javax.swing.JComponent.processKeyEvent(JComponent.java:2807)
    at java.awt.Component.processEvent(Component.java:5815)
    at java.awt.Container.processEvent(Container.java:2058)
    at java.awt.Component.dispatchEventImpl(Component.java:4410)
    at java.awt.Container.dispatchEventImpl(Container.java:2116)
    at java.awt.Component.dispatchEvent(Component.java:4240)
    at java.awt.KeyboardFocusManager.redispatchEvent(KeyboardFocusManager.java:1848)
    at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(DefaultKeyboardFocusManager.java:693)
    at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(DefaultKeyboardFocusManager.java:958)
    at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(DefaultKeyboardFocusManager.java:830)
    at java.awt.DefaultKeyboardFocusManager.dispatchEvent(DefaultKeyboardFocusManager.java:657)
    at java.awt.Component.dispatchEventImpl(Component.java:4282)
    at java.awt.Container.dispatchEventImpl(Container.java:2116)
    at java.awt.Window.dispatchEventImpl(Window.java:2429)
    at java.awt.Component.dispatchEvent(Component.java:4240)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)
    A NullPointerException??? I even tried priming the textfield by setting the value using formatTxt.setValue(format.stringToValue("+00 00 00")).
    Does anyone have any ideas on this error (or how I can get around this without delving to much into other filtering classes)? Has anyone had similar problems with the MaskFormatter masks not accepting what they claim they do (I looked through the posts on the subject).
    Thanking you in advance for you patience........

    Hi,
    Thank you very much for your prompt reply.
    I've done as you said - written a smaller program to test each mask. They don't work quite as I expected but you're right, each mask works fine, its changing the masks that's the problem. I wrote this to test it out:
    public class testMask {
    //Note:      main() won't let u access object/variable methods if declared here
    // GUI items to be globally accsessed:
         JFrame MainWin;
         JPanel panel, panel1;
         JLabel question, answer;
         JButton send, askQues, change;
         JFormattedTextField formatTxt;
         myFormatter format;
    // I/O to be globally accessed:
         String usrinput = null;
         public static void main( String[] args ) {
              testMask GUI = new testMask();
         public testMask(){
              javax.swing.SwingUtilities.invokeLater(new Runnable() {
                   public synchronized void run() {
                              create();
                 });                              //     thread safe code to make sure that UI painting is not interrupted by events, possibly causing the UI to hang
         public synchronized void create(){
              //set look and feel of GUI
              try {
              } catch (Exception e) {
                             System.out.println("Error - Problem displaying window");
              //initialise main window and set layout manager
              MainWin = new JFrame("Test Masks");     
              MainWin.getContentPane().setLayout(new BorderLayout());     
              // initialise containers to go on MainWin
              panel = createPanel();
              MainWin.getContentPane().add(panel, BorderLayout.CENTER);
              MainWin.pack();
              MainWin.setSize(300,150);
              MainWin.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              MainWin.setLocation(150, 150);
              MainWin.setVisible(true);
         public synchronized JPanel createPanel() {
              JPanel panel1 = new JPanel();
              panel1.setLayout(new GridLayout(3,1));
              Border border = BorderFactory.createEtchedBorder();
              panel1.setBorder(BorderFactory.createTitledBorder(border, " Test Panel "));
              question = new JLabel("Please enter drive");
              answer = new JLabel();
              answer.setBorder(border);
              panel1.add(question);
              JPanel pane1 = new JPanel(new FlowLayout());
    //------Set up formatted textfield for user input to be verified--------
              format = createFormatter();
              format.setMask("drive");
              formatTxt = new JFormattedTextField(format);
              formatTxt.setColumns(10);
              send = new JButton(" Send ");
              send.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
              send.addActionListener(new ActionListener(){
                   public synchronized void actionPerformed(ActionEvent e) {
                        try{
                             formatTxt.commitEdit();
                        } catch (java.text.ParseException exc) {
                             answer.setText("Problem with formatting: " + exc.getMessage());
                             return;
                        SwingUtilities.invokeLater(new Runnable() {
                             public synchronized void run() {                         
                                  if (formatTxt.isEditValid()) {
                                       usrinput = formatTxt.getText();
                                       answer.setText(usrinput);
                                  } else { answer.setText("Input not of valid format"); }
              change = new JButton("Change mask");
              change.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
              change.addActionListener(new ActionListener(){
                   public synchronized void actionPerformed(ActionEvent e) {
                        question.setText("Please enter coord in format ## ## ##");
                        format.setMask("coord");
              pane1.add(formatTxt);
              pane1.add(send);
              pane1.add(change);
              panel1.add(pane1);
              panel1.add(answer);
              return panel1;
         protected myFormatter createFormatter() {
              myFormatter formatter = new myFormatter();
              return formatter;
    class myFormatter extends MaskFormatter {
         String key;
         public void setMask(String k){
              key = k;     
              if (key.equals("coord")) {
                   try{
                        super.setMask("*## ## ##"); // for disk drive
                        super.setValueContainsLiteralCharacters(true);
                   }catch (java.text.ParseException e) {
                        answer.setText("Problem with formatting: " + e.getMessage());
                        return;
              } else if (key.equals("drive")) {
                   try{
                        super.setMask("L:"); // for disk drive
                        super.setValueContainsLiteralCharacters(true);
                   }catch (java.text.ParseException e) {
                        answer.setText("Problem with formatting: " + e.getMessage());
                        return;
              } else  {
                   try{
                        super.setMask("********************"); // accept anything
                   }catch (java.text.ParseException e) {
                        answer.setText("Problem with formatting: " + e.getMessage());
                        return;
    }When I click on the "change" button, the textfield won't let me enter anything in, no matter what I change the mask from or to.
    Does anyone have any idea how I can implement the mask change dynamically? The only thing I could think of was to somehow re-initalise the textfield then do a repaint, but I don't know how or if that would even work.
    Thanking you again in anticipation,
    Mellony

  • I grab a null frame.  Can a Java genious help, please?

    Hello. I am a high school student working on a science fair project. Right now I am using JMF to grab a frame from my ATI TV Wonder USB. The code below accesses the TV Wonder but it seems like I get a null frame because I have put a if statement in the code and it says I have a null image there. Can someone please help me. Thank you in advance
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.text.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.media.*;
    import javax.media.format.*;
    import javax.media.util.*;
    import javax.media.control.*;
    import javax.media.protocol.*;
    import javax.media.control.FormatControl;
    public class Cell extends JApplet implements ActionListener{
         JLabel welcomeLabel;
         JTextArea output;
         JButton close;
         String display = "";
         String exit = "The video capture buffer has been terminated.";
         String problem = "";
         String videoDevice = "vfw:Microsoft WDM Image Capture (Win32):0";
         public static Player player = null;
         public Buffer buf = null;
         public Image img = null;
         public VideoFormat vf = null;
         public BufferToImage btoi = null;
         public MediaLocator ml = null;
         public CaptureDeviceInfo di = null;
         public void init()
              Container c = getContentPane();
              c.setLayout( new FlowLayout() );
              welcomeLabel = new JLabel("Welcome to Adam's Cell Analyzer");
              c.add(welcomeLabel);
              output = new JTextArea(6, 60);
              output.setFont( new Font("Courier", Font.PLAIN, 12) );
              c.add(output);
              close = new JButton("End Analyze Program");
              close.addActionListener(this);
              c.add(close);
              display = "Starting...\n\n";
              output.setText(display);
              di = CaptureDeviceManager.getDevice(videoDevice);
              ml = di.getLocator();
              try {
                   player = Manager.createRealizedPlayer(ml);
                   player.start();
                   Component comp;
              catch (Exception e) {
                   problem += "An Exception has occured.";
                   output.setText(problem);
              FrameGrabbingControl fgc = (FrameGrabbingControl)
                   player.getControl("javax.media.control.FrameGrabbingControl");
              buf = fgc.grabFrame();
              btoi = new BufferToImage((VideoFormat)buf.getFormat());
              img = btoi.createImage(buf);
              display += "The video capture card is currently working properly\n";
              display += "and is sending a video feed to the image buffer.\n\n";
              output.setText(display);
              if(img==null){
                   problem += "The frame is null.";
                   output.setText(problem);
              else
                   imageEnhancement(img);
         public void actionPerformed(ActionEvent e)
              output.setText(exit);
              player.close();
              player.deallocate();
         private void imageEnhancement(Image img)
         //Nothing now     
    }

    I decided to post my program on here because I remember how hard it was to get it to work, and I don't want people to go through the same problems... just don't use it to compete against me in the Intel Science and Engineering Fair and/or the Intel Science Talent Search ;-) then I'll be mad. Other than that, have fun!
    ~Adam Georgas
    import java.awt.*;
    import java.awt.Dimension;
    import java.awt.event.*;
    import java.awt.Image.*;
    import java.awt.image.renderable.*;
    import java.io.*;
    import java.text.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.media.*;
    import javax.media.format.*;
    import javax.media.format.VideoFormat;
    import javax.media.util.*;
    import javax.media.util.BufferToImage;
    import javax.media.control.*;
    import javax.media.protocol.*;
    import javax.media.control.FormatControl;
    public class Cell extends JApplet implements ActionListener{
         JLabel welcomeLabel;
         JTextArea output;
         JButton begin;
         JButton end;
         String display = "";
         String problem = "";
         String exit = "The video capture buffer has been terminated.";
         String videoDevice = "vfw:Microsoft WDM Image Capture (Win32):0";
         public static Player player = null;
         public Buffer buf = null;
         public MediaLocator ml = null;
         public CaptureDeviceInfo di = null;
         public BufferToImage btoi = null;
         public Image frameImage = null;
         public VideoFormat vf = null;
         public PlanarImage src = null;
         private ImageEncoder encoder = null;
    private JPEGEncodeParam encodeParam = null;
         int error = 0;
         public void init()
              Container c = getContentPane();
              c.setLayout( new FlowLayout() );
              welcomeLabel = new JLabel("Welcome to Adam's Cell Analyzer");
              c.add(welcomeLabel);
              output = new JTextArea(6, 60);
              output.setFont( new Font("Courier", Font.PLAIN, 12) );
              c.add(output);
              begin = new JButton("Begin Analyze Program");
              begin.addActionListener(this);
              c.add(begin);
              end = new JButton("End Analyze Program");
              end.addActionListener(this);
              c.add(end);
              di = CaptureDeviceManager.getDevice(videoDevice);
              ml = di.getLocator();
              try {
                   player = Manager.createRealizedPlayer(ml);
                   player.start();
              catch (Exception b) {
                   JOptionPane.showMessageDialog(this, b.toString(),
                        "An Exception has occured", JOptionPane.ERROR_MESSAGE);
              display = "Welcome\n\n";
              output.setText(display);
         public void actionPerformed(ActionEvent e)
              JComponent j = (JComponent) e.getSource();
              if (j == end){
                   player.close();
                   player.deallocate();
                   output.setText(exit);     
              if (j == begin){
                   display += "Starting...\n\n";
                   output.setText(display);
                   Control[] controls = player.getControls();
                   FrameGrabbingControl fgc = (FrameGrabbingControl)
                        player.getControl("javax.media.control.FrameGrabbingControl");
                   if (fgc == null) {
                        error = 1;
                        problem(error);
                   buf = fgc.grabFrame();
                   btoi = new BufferToImage((VideoFormat)buf.getFormat());
                   if (btoi == null){
                        error = 2;
                        problem(error);
                   VideoFormat format = (VideoFormat)buf.getFormat();
                   Dimension size = format.getSize();
                   if(format == null) {
                        error = 3;
                        problem(error);
                   frameImage = btoi.createImage(buf);               
                   if(frameImage == null) {
                        error = 4;
                        problem(error);
                   else{
                        display = "";
                        display = "The video system is working correctly and grabbing frames.\n\n";
                        output.setText(display);     
         public void imageEnhancement()
    //Top Secret :-)
         public void problem(int error)
              switch(error) {
              case 1:
                   JOptionPane.showMessageDialog(this, "The frame grabbing control is null.",
                        "A problem has occured", JOptionPane.ERROR_MESSAGE);
                   break;
              case 2:
                   JOptionPane.showMessageDialog(this, "The buffer to image conversion did not occur properly.",
                        "A problem has occured", JOptionPane.ERROR_MESSAGE);
                   break;
              case 3:
                   JOptionPane.showMessageDialog(this, "The image format queries did not occur properly.",
                        "A problem has occured", JOptionPane.ERROR_MESSAGE);
                   break;
              case 4:
                   JOptionPane.showMessageDialog(this, "The buffer to image did not occur properly.",
                        "A problem has occured", JOptionPane.ERROR_MESSAGE);
                   break;
              case 5:
                   JOptionPane.showMessageDialog(this, "Java AWT Image to JAI Image did not occur properly.",
                        "A problem has occured", JOptionPane.ERROR_MESSAGE);
                   break;
              default:
                   JOptionPane.showMessageDialog(this, "An unknown problem has occured.",
                        "A problem has occured", JOptionPane.ERROR_MESSAGE);
    }

  • Actionlistener in swing won't let me play with my variables!

    I am sort of new to java, having done some scripting before, but not much programming experiance. OOP was, until I learned java, something I didn't use that much. All this static and public stuff was hard at first, but I finally think I understand it all.
    I am still learning java, and for one of my projects, I am trying to make a small quiz game to learn swing. I am having problems. My button actionlistener complains about my variables, and I have tried many things, like wrapping them in a container and moving them, but I cannot make it compile. Any help would be appriciated. Thanks in advance!
    //The program is a quiz thingy.
    //the error is down in the GUI section, where I make the button respond to commands
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.net.*;//for later use, download files to read off net
    import java.io.*;
    import java.math.*;
    import java.util.Random;
    public class Main {
    public static void main(String args[]) { 
      File file = new File("problems.txt");
      int probcount=5;
      int answercount=0;
      boolean onproblem = true;
      String[] Problems={"","","","","","","","","","","",""};//I find if I don't init, I get nullpointer errors
      String[] Answers={"","","","","","","","","","","",""};//sorry for the oddness
      String[] thetext=new String[100];
      int i=0;
      int t=0;
      if ( !file.exists(  ) || !file.canRead(  ) ) {
                    System.out.println( "Can't read " + file );
                    return;
                    try {
                        FileReader fr = new FileReader ( file );
                        BufferedReader in = new BufferedReader( fr );
                        String line;
                        while ((line = in.readLine(  )) != null ){
                            thetext=line;
    i++;
    catch ( FileNotFoundException e ) {
    System.out.println( "File Disappeared" );
    catch ( IOException e ) {
    System.out.println( "Error During File Reading" );
    boolean writetoprob = true;
    for(int y=0;y<i;y++)
    System.out.println(thetext[y]);
    for(int y=0;y<i;y++){
    if(thetext[y].equals("-")){
    if(writetoprob==true)
    writetoprob=false;
    else{
    writetoprob=true;
    t++;
    else{
    if(writetoprob==true)
    Problems[t]=Problems[t].concat("\n").concat(thetext[y]);
    else
    Answers[t]=Answers[t].concat("\n").concat(thetext[y]);
    System.out.println(Problems[0]);
    System.out.println(Problems[1]);
    //TODO:Randomize problems and display them, then answers when button clicked
    boolean answerbutton=true;
    int probindex=0;
    Random rnums = new Random();
    probindex=rnums.nextInt()%(t+1);
    if(probindex<0)
    probindex=-probindex;
    System.out.println(probindex);
    System.out.println(Problems[probindex]);
    JButton action = new JButton("Click for Answer!");
    JTextArea tp = new JTextArea(Problems[probindex]);
    JFrame jf = new JFrame();
    boolean onanswer = false;
    action.addActionListener( new ActionListener( ) {
    public void actionPerformed(ActionEvent theaction) {
    System.out.println(answerbutton);
    if(answerbutton==false){
    answerbutton=true;
    probindex=rnums.nextInt()%(t+1);
    if(probindex<0)
    probindex=-probindex;
    tp.setText(Problems[probindex]);
    else{
    answerbutton=false;
    tp.setText(Answers[probindex]);
    Container content = jf.getContentPane( );
    content.setLayout(new FlowLayout( ));
    content.add(tp);
    content.add(action);
    jf.pack();
    jf.setVisible(true);

    init:
    deps-jar:
    Compiling 1 source file to C:\Documents and Settings\Patrick\FirstCup\build\classes
    C:\Documents and Settings\Patrick\FirstCup\src\firstcup\Main.java:91: local variable answerbutton is accessed from within inner class; needs to be declared final
    System.out.println(answerbutton);
    C:\Documents and Settings\Patrick\FirstCup\src\firstcup\Main.java:92: local variable answerbutton is accessed from within inner class; needs to be declared final
    if(answerbutton==false){
    C:\Documents and Settings\Patrick\FirstCup\src\firstcup\Main.java:93: local variable answerbutton is accessed from within inner class; needs to be declared final
    answerbutton=true;
    C:\Documents and Settings\Patrick\FirstCup\src\firstcup\Main.java:94: local variable probindex is accessed from within inner class; needs to be declared final
    probindex=rnums.nextInt()%(t+1);
    C:\Documents and Settings\Patrick\FirstCup\src\firstcup\Main.java:94: local variable rnums is accessed from within inner class; needs to be declared final
    probindex=rnums.nextInt()%(t+1);
    C:\Documents and Settings\Patrick\FirstCup\src\firstcup\Main.java:94: local variable t is accessed from within inner class; needs to be declared final
    probindex=rnums.nextInt()%(t+1);
    C:\Documents and Settings\Patrick\FirstCup\src\firstcup\Main.java:95: local variable probindex is accessed from within inner class; needs to be declared final
    if(probindex<0)
    C:\Documents and Settings\Patrick\FirstCup\src\firstcup\Main.java:96: local variable probindex is accessed from within inner class; needs to be declared final
    probindex=-probindex;
    C:\Documents and Settings\Patrick\FirstCup\src\firstcup\Main.java:96: local variable probindex is accessed from within inner class; needs to be declared final
    probindex=-probindex;
    C:\Documents and Settings\Patrick\FirstCup\src\firstcup\Main.java:97: local variable Problems is accessed from within inner class; needs to be declared final
    tp.setText(Problems[probindex]);
    C:\Documents and Settings\Patrick\FirstCup\src\firstcup\Main.java:97: local variable probindex is accessed from within inner class; needs to be declared final
    tp.setText(Problems[probindex]);
    C:\Documents and Settings\Patrick\FirstCup\src\firstcup\Main.java:97: local variable tp is accessed from within inner class; needs to be declared final
    tp.setText(Problems[probindex]);
    C:\Documents and Settings\Patrick\FirstCup\src\firstcup\Main.java:100: local variable answerbutton is accessed from within inner class; needs to be declared final
    answerbutton=false;
    C:\Documents and Settings\Patrick\FirstCup\src\firstcup\Main.java:101: local variable Answers is accessed from within inner class; needs to be declared final
    tp.setText(Answers[probindex]);
    C:\Documents and Settings\Patrick\FirstCup\src\firstcup\Main.java:101: local variable probindex is accessed from within inner class; needs to be declared final
    tp.setText(Answers[probindex]);
    C:\Documents and Settings\Patrick\FirstCup\src\firstcup\Main.java:101: local variable tp is accessed from within inner class; needs to be declared final
    tp.setText(Answers[probindex]);
    16 errors
    BUILD FAILED (total time: 3 seconds)

  • It seems the basic encryption/decryption functions are unreliable,

    I am having trouble with the following code. I am just using the resources provided in the latest SDK.
    My code compiles and appears to run without generating any errors. The problem is that I have yet to get back the same string as I entered.
    I am following an example in a J2EE security text, but the example seems to be incomplete.
    I suspect the problem is not so much with the encryption and decryption functions per se, but rather a problem, not discussed in any of the references I have read, with managing and storing the cipher text. Can anyone confirm or refute my suspicions, and/or show me how to modify my code so that it invariably results in the decrypted string being identical to the original plain text string?
    It looks like the cipher text I will get will invariably be binary data, and not just sequences of alphanumeric characters. Can anyone tell me where I can find a function that will generate a unique integer for an arbitrary length byte array, or how one might be constructed? Or, if there is one, perhaps someone can tell me if there is a good encryption algorithm that will create cipher text that consists only of a sequence of alphanumeric characters.
    Here are the two relevant functions, along with the relevant declarations of class data members:
        private void encryptBTNMouseClicked(java.awt.event.MouseEvent evt) {
            if ( !OK2run ) return;
            String tmp = PlainTextArea.getText();
            int length = tmp.length();
            if (length < 20) {
                tmp = new String("We need a longer string. we are trying to understand encryption and decryption.");
                PlainTextArea.setText(tmp);
            try {
                myCypher.init(Cipher.ENCRYPT_MODE,sk);
            } catch (java.security.InvalidKeyException ivke) {
                PlainTextArea.setText("Problem with key!");
            byte[] pBytes = tmp.getBytes();
            byte[] cBytes = null;
            try {
                cBytes = myCypher.doFinal(pBytes);
            } catch (javax.crypto.BadPaddingException nspe) {
                CypherTextArea.setText("Problem with padding!");
            } catch (javax.crypto.IllegalBlockSizeException ibse) {
                CypherTextArea.setText("Problem with block size!");
            tmp = new String(cBytes);
            CypherTextArea.setText(tmp);
            tmp = PlainTextArea.getText() + "\n\nWrapped Key = " + wrappedKey;
            PlainTextArea.setText(tmp);
            decryptBTN.enable();
        private void decryptBTNMouseClicked(java.awt.event.MouseEvent evt) {
            String tmp = CypherTextArea.getText();
            byte[] cBytes = tmp.getBytes();
            try {
                myCypher.init(Cipher.DECRYPT_MODE,sk);
            } catch (java.security.InvalidKeyException ivke) {
                DecypheredTextArea.setText("Problem with key!");
            byte[] dBytes = null;
            try {
                dBytes = myCypher.doFinal(cBytes);
            } catch (javax.crypto.BadPaddingException nspe) {
                CypherTextArea.setText("Problem with padding!");
            } catch (javax.crypto.IllegalBlockSizeException ibse) {
                DecypheredTextArea.setText("Problem with block size!");
            tmp = new String(dBytes);
            DecypheredTextArea.setText(tmp);
        private javax.crypto.KeyGenerator kg;
        private boolean OK2run = false;
        private javax.crypto.SecretKey sk = null;
        private javax.crypto.Cipher myCypher = null;
        private byte[] theBytes = null;
        private String wrappedKey = null;Thanks,
    Ted

    One should not try to create a String object from the encrypted bytes using
    tmp = new String(cBytes);
    because it is not guaranteed to be reversible.
    If you need a String then use Base64 or Hex encoding. Google for Jakarta Commons Codec.

  • Inconsistent ArrayIndexOutOfBoundsException using SwingWorker worker thread

    On occasions I will get the following exception thrown whenever I happen to be using SimpleBrowser.this.processor.processTask() method to run a SwingWorker<Void, Void>-based class Task worker thread (within doInBackground()) :
    Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: -1
            at javax.swing.text.BoxView.getOffset(BoxView.java:1076)
            at javax.swing.text.BoxView.childAllocation(BoxView.java:670)
            at javax.swing.text.CompositeView.getChildAllocation(CompositeView.java:215)
            at javax.swing.text.BoxView.getChildAllocation(BoxView.java:428)
            at javax.swing.plaf.basic.BasicTextUI$UpdateHandler.calculateViewPosition(BasicTextUI.java:1978)
            at javax.swing.plaf.basic.BasicTextUI$UpdateHandler.layoutContainer(BasicTextUI.java:1954)
            at java.awt.Container.layout(Container.java:1432)
            at java.awt.Container.doLayout(Container.java:1421)
            at java.awt.Container.validateTree(Container.java:1519)
            at java.awt.Container.validateTree(Container.java:1526)
            at java.awt.Container.validateTree(Container.java:1526)
            at java.awt.Container.validate(Container.java:1491)
            at javax.swing.RepaintManager.validateInvalidComponents(RepaintManager.java:639)
            at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(SystemEventQueueUtilities.java:127)
            at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
            at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
            at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
            at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
            at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
            at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)I haven't found much reliable online information to illustrate this issue any further so I'm a bit in the dark. Following is my code that runs within the aforementioned worker thread which I believe throws the exception:
             * Use {@link #setWebBrowserURL} using a local {@link com.ppowell.tools.ObjectTools.SwingTools.Task}
            protected void processTask() {
                Task task = new Task() {
                    public Void doInBackground() {
                        int progress = 0;
                        while (!SimpleBrowser.this.builder.hasLoadedWebpage && progress < 100) {
                            SimpleBrowser.this.statusBar.setMessage("Attempting to load " + SimpleBrowser.this.getURL().toString());
                            this.setProgress(progress);
                            progress++;
                        SimpleBrowser.this.setWebBrowserURL();
                        try {
                            Thread.sleep(2500);
                        } catch (InterruptedException ignore) {} // DO NOTHING
                        if (SimpleBrowser.this.builder.hasLoadedWebpage) {
                            SimpleBrowser.this.statusBar.setMessage("Done");
                        return null;
                task.addPropertyChangeListener(SimpleBrowser.this);
                task.execute();
            }Is there a way I might at least be able to suppress this error (the GUI application browser functions just fine in spite of it), or, even better, solve this inconsistent problem?
    Thanks
    Phil

    I suspect that you need to "clean" your html priorto
    calling super.setText(). My guess is that you're
    yanking nodes from beaneath Swing while it'strying
    to render.
    In addition to that, you may want to use JTidy to
    clean up your html, and convert it to xhtml --again
    prior to calling super.setText().Problem is that however I clean up the HTML, the
    moment I try to reinsert back into the JEditorPane
    using setText(), I get EmptyStackException or I'll
    get NullPointerException or it just might work - same
    problem, different exception(s).Ok this time I am simply using setText() instead of setPage(), but the results are, while consistent, they are consistently completely wrong. The browser appears blank every time, no HTML can be retrieved (you get a NullPointerException if you try), all the while I can verify that that original HTML from the remote site is correct, it never, ever, inserts into JEditorPane.
    Here is my code:
    * SimpleHTMLRenderableEditorPane.java
    * Created on March 13, 2007, 3:39 PM
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package com.ppowell.tools.ObjectTools.SwingTools;
    import java.io.*;
    import java.net.*;
    import javax.swing.JEditorPane;
    import javax.swing.text.html.HTMLEditorKit;
    * A safer version of {@link javax.swing.JEditorPane}
    * @author Phil Powell
    * @version JDK 1.6.0
    public class SimpleHTMLRenderableEditorPane extends JEditorPane {
        //--------------------------- --* CONSTRUCTORS *--
        // <editor-fold defaultstate="collapsed" desc=" Constructors ">
        /** Creates a new instance of SimpleHTMLRenderableEditorPane */
        public SimpleHTMLRenderableEditorPane() {
            super();
         * Creates a new instance of SimpleHTMLRenderableEditorPane
         * @param url {@link java.lang.String}
         * @throws java.io.IOException Thrown if an I/O exception occurs
        public SimpleHTMLRenderableEditorPane(String url) throws
    IOException {
            super(url);
         * Creates a new instance of SimpleHTMLRenderableEditorPane
         * @param type {@link java.lang.String}
         * @param text {@link java.lang.String}
        public SimpleHTMLRenderableEditorPane(String type, String text) {
            super(type, text);
         * Creates a new instance of SimpleHTMLRenderableEditorPane
         * @param url {@link java.net.URL}
         * @throws java.io.IOException Thrown if an I/O exception occurs
        public SimpleHTMLRenderableEditorPane(URL url) throws IOException
            super(url);
        // </editor-fold>
        //----------------------- --* GETTER/SETTER METHODS *--
        // <editor-fold defaultstate="collapsed" desc=" Getter/Setter
    Methods ">
         * Retrieve HTML content
         * @return html {@link java.lang.String}
        public String getText() {
            try {
                 * I decided to use {@link java.net.HttpURLConnection} to
    retrieve the
                 * HTML code from the remote site instead of using
    super.getText() because
                 * of the HTML code return constantly being stripped to
    primitive HTML
                 * template formatting irregardless of the original HTML
    source code
                HttpURLConnection conn =
    (HttpURLConnection)getPage().openConnection();
                conn.setUseCaches(false);
                conn.setDefaultUseCaches(false);
                conn.setDoOutput(false); // READ-ONLY
                BufferedReader in = new BufferedReader(
                        new InputStreamReader(
                        conn.getInputStream()));
                int data;
                StringBuffer sb = new StringBuffer();
                char[] ch = new char[512];
                while ((data = in.read(ch)) != -1) {
                    sb.append(ch, 0, data);
                in.close();
                conn.disconnect();
                return sb.toString();
            } catch (IOException e) {
                return super.getText(); // DEFAULT TO USING
    super.getText() IF NO I/O CONNECTION
         * Overloaded to fix HTML rendering bug Bug ID: 4695909.
         * @param text {@link java.lang.String}
        public void setText(String text) {
            // Workaround for bug Bug ID: 4695909 in java 1.4
            // JEditorPane does not handle the META tag in the html HEAD
            if (isJava14() && "text/
    html".equalsIgnoreCase(getContentType())) {
                text = stripMetaTag(text);
            super.setText(text);
        // </editor-fold>
        //--------------------------- --* OTHER METHODS *--
        // <editor-fold defaultstate="collapsed" desc=" Methods ">
         * Clean HTML to remove things like <link>, <script>,
         * <style>, <object>, <embed>, and <!-- -->
         * Based upon <a href="http://bugs.sun.com/bugdatabase/view_bug.do?
    bug_id=4695909">bug report</a>
        public void cleanHTML() {
            try {
                setText(cleanHTML(getText()));
            } catch (Exception e) {} // DO NOTHING
         * Clean HTML
         * @param html {@link java.lang.String}
         * @return html {@link java.lang.String}
        public String cleanHTML(String html) {
            String[] tagArray = {"<LINK", "<SCRIPT", "<STYLE", "<OBJECT",
    "<EMBED", "<!--"};
            String upperHTML = html.toUpperCase();
            String endTag;
            int index = -1, endIndex = -1;
            for (int i = 0; i < tagArray.length; i++) {
                index = upperHTML.indexOf(tagArray);
    endTag = "</" + tagArray[i].substring(1,
    tagArray[i].length());
    endIndex = upperHTML.indexOf(endTag, index);
    while (index >= 0) {
    if (endIndex >= 0) {
    html = html.substring(0, index) +
    html.substring(html.indexOf(">", endIndex)
    + 1,
    html.length());
    upperHTML = upperHTML.substring(0, index) +
    upperHTML.substring(upperHTML.indexOf(">",
    endIndex) + 1,
    upperHTML.length());
    } else {
    html = html.substring(0, index) +
    html.substring(html.indexOf(">", index) +
    1,
    html.length());
    upperHTML = upperHTML.substring(0, index) +
    upperHTML.substring(upperHTML.indexOf(">",
    index) + 1,
    upperHTML.length());
    index = upperHTML.indexOf(tagArray[i]);
    endIndex = upperHTML.indexOf(endTag, index);
    // REF: http://forum.java.sun.com/thread.jspa?threadID=213582&messageID=735120
    html = html.substring(0, upperHTML.indexOf(">",
    upperHTML.indexOf("</HTML")) + 1);
    // REF: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5042872
    return html.trim();
    * This actually only obtains the URL; this serves as a retriever
    for cleanHTML(String html)
    * @param url {@link java.net.URL}
    * @return html {@link java.lang.String}
    public String cleanHTML(URL url) {
    try {
    HttpURLConnection conn =
    (HttpURLConnection)url.openConnection();
    conn.setUseCaches(false);
    conn.setDefaultUseCaches(false);
    conn.setDoOutput(false); // READ-ONLY
    BufferedReader in = new BufferedReader(
    new InputStreamReader(
    conn.getInputStream()));
    int data;
    StringBuffer sb = new StringBuffer();
    char[] ch = new char[512];
    while ((data = in.read(ch)) != -1) {
    sb.append(ch, 0, data);
    in.close();
    conn.disconnect();
    return cleanHTML(sb.toString());
    } catch (IOException e) {
    e.printStackTrace();
    return null;
    * Determine if java version is 1.4.
    * @return true if java version is 1.4.x....
    private boolean isJava14() {
    if (System.getProperty("java.version") == null) return false;
    return System.getProperty("java.version").startsWith("1.4");
    * Workaround for Bug ID: 4695909 in java 1.4, fixed in 1.5
    * JEditorPane fails to display HTML BODY when META tag included
    in HEAD section.
    * Code modified by Phil Powell
    * <html>
    * <head>
    * <META http-equiv="Content-Type" content="text/html;
    charset=UTF-8">
    * </head>
    * <body>
    * @param text html to strip.
    * @return same HTML text w/o the META tag.
    private String stripMetaTag(String text) {
    // String used for searching, comparison and indexing
    String textUpperCase = text.toUpperCase();
    int indexHead = textUpperCase.indexOf("<HEAD ");
    int indexMeta = textUpperCase.indexOf("<META ");
    int indexBody = textUpperCase.indexOf("<BODY ");
    // Not found or meta not inside the head nothing to strip...
    if (indexMeta == -1 || indexMeta < indexHead || indexMeta >
    indexBody) {
    return text;
    // Find end of meta tag text.
    int indexHeadEnd = textUpperCase.indexOf(">", indexMeta);
    // Strip meta tag text
    return text.substring(0, indexMeta - 1) +
    text.substring(indexHeadEnd + 1);
    // </editor-fold>
    Instead if you try
    browser.getText()
    You will get a NullPointerException
    If you try
        public void setText(String text) {
            // Workaround for bug Bug ID: 4695909 in java 1.4
            // JEditorPane does not handle the META tag in the html HEAD
            if (isJava14() && "text/
    html".equalsIgnoreCase(getContentType())) {
                text = stripMetaTag(text);
            System.out.println(text); // YOU WILL SEE CNN'S HTML
            super.setText(text);
            System.out.println(super.getText()); // SEE BELOW
        }You see only this:
    <html>
      <head>
      </head>
      <body>
        <p style="margin-top: 0">
        </p>
      </body>
    </html>

  • JTextArea never looses focus

    I have a simple gui that is giving me problems, for some reason when I reset the componments one of my JTextAreas still has focus. If I go and click to write in JTextArea B, theres still another cusor in the A ..... ???? And when I go back to the A, and try to write in A, it appends in the B. Why would the cusor still thinks its in the other JTextArea, Basically now, I have two cusors in my Frame ......... Can any one help me ???
    Thanks

    Heres a sample of my code, cause the whole thing is way too long ....
         JPanel pEdit = new JPanel();
         static Document EDtaProbDoc;
         static Document EDtaInteDoc;
         static JScrollPane EDspProb           = new JScrollPane();
         static JScrollPane EDspInte           = new JScrollPane();
         static JLabel EDlbNoAppel                = new JLabel();
         static JLabel EDlbContact                = new JLabel();
         static JLabel EDlbNoCon                = new JLabel();
         static JLabel EDlbCli                = new JLabel();
         static JLabel EDlbTel                = new JLabel();
         static JLabel EDlbPost                = new JLabel();
         static JLabel EDlbDetEquip                = new JLabel();
         static JLabel EDlbDetProb                = new JLabel();
         static JLabel EDlbDetInte                = new JLabel();
         static JComboBox EDchNoAppel           = new JComboBox();
         static JTextField EDtfContact           = new JTextField();
         static JTextField EDtfTel           = new JTextField();
         static JTextField EDtfPost           = new JTextField();
         static JTextField EDtfAutre           = new JTextField();
         static JTextField EDtfCli                = new JTextField();
         static JTextField EDtfNoCon           = new JTextField();
         static JComboBox EDchDetEquip                = new JComboBox();
         static JTextArea EDtaDetProb                = new JTextArea();
         static JTextArea EDtaDetInte                = new JTextArea();
         static JButton EDbtSau                = new JButton();
    /*********               ADDING TO PANEL ******************/
              pEdit.setLayout(null);
              EDlbNoAppel.setText("Number call");
              EDlbNoAppel.setBounds(new Rectangle(75, 38, 125, 23));
              EDlbContact.setText("Contact");
              EDlbContact.setBounds(new Rectangle(426, 38, 125, 23));
              EDlbNoCon.setText("No Contrat");
              EDlbNoCon.setBounds(new Rectangle(75, 75, 125, 23));
              EDlbCli.setText("Client");
              EDlbCli.setBounds(new Rectangle(75, 57, 125, 23));
              EDlbTel.setText("T�l�phone");
              EDlbTel.setBounds(new Rectangle(426, 58, 125, 23));
              EDlbPost.setText("Post");
              EDlbPost.setBounds(new Rectangle(426, 76, 125, 23));
              EDlbDetEquip.setText("Equipement");
              EDlbDetEquip.setBounds(new Rectangle(75, 110, 125, 23));
              EDlbDetProb.setText("Problem ");
              EDlbDetProb.setBounds(new Rectangle(75, 145, 125, 23));
              EDlbDetInte.setText("Intervention");
              EDlbDetInte.setBounds(new Rectangle(75, 300, 125, 23));
              EDchNoAppel.setBounds(new Rectangle(149, 41, 235, 20));
              EDtfContact.setBounds(new Rectangle(500, 44, 235, 20));
              EDtfNoCon.setBounds(new Rectangle(149, 79, 235, 20));
              EDtfCli.setBounds(new Rectangle(149, 61, 235, 20));
              EDtfTel.setBounds(new Rectangle(500, 62, 235, 20));
              EDtfTel.setToolTipText("Format (###)###-####");
              EDtfPost.setBounds(new Rectangle(500, 80, 235, 20));
              EDchDetEquip.setBounds(new Rectangle(186, 110, 550, 20));
              EDtaDetProb.setBounds(new Rectangle(77, 170, 657, 115));
              EDtaDetProb.setLineWrap(true);
              EDtaDetProb.setWrapStyleWord(true);
              EDspProb.setBounds(new Rectangle(77, 170, 657, 115));
              EDspProb.getViewport().add(EDtaDetProb, null);
              EDtaDetInte.setBounds(new Rectangle(77, 325, 657, 115));
              EDtaDetInte.setLineWrap(true);
              EDtaDetInte.setWrapStyleWord(true);
              EDspInte.setBounds(new Rectangle(77, 325, 657, 115));
              EDspInte.getViewport().add(EDtaDetInte, null);
              EDtaInteDoc = EDtaDetInte.getDocument();
              EDtaProbDoc = EDtaDetProb.getDocument();
              KeyStroke key = KeyStroke.getKeyStroke("ENTER");
              EDtaDetInte.getInputMap().put(key,"none");
              KeyStroke key1 = KeyStroke.getKeyStroke("ENTER");
              EDtaDetProb.getInputMap().put(key1,"none");
              EDbtSau.setText("Sauvegarder");
              EDbtSau.setToolTipText("Mise � jour de cet appel");
              EDbtSau.setBounds(new Rectangle(615, 450, 118, 30));
              EDbtSau.addActionListener(this);
              EDbtSau.setEnabled(false);
              EDtfCli.setEditable(false);
    EDtfNoCon.setEditable(false);
    EDchNoAppel.addItemListener(this);
    EDchDetEquip.addItemListener(this);
              pEdit.add(EDchNoAppel, null);
              pEdit.add(EDtfContact, null);
              pEdit.add(EDtfNoCon, null);
              pEdit.add(EDlbNoCon, null);
              pEdit.add(EDlbContact, null);
              pEdit.add(EDlbNoAppel, null);
              pEdit.add(EDtfCli, null);
              pEdit.add(EDtfPost, null);
              pEdit.add(EDlbPost, null);
              pEdit.add(EDlbTel, null);
              pEdit.add(EDlbCli, null);
              pEdit.add(EDtfTel, null);
              pEdit.add(EDchDetEquip, null);
              pEdit.add(EDlbDetEquip, null);
              pEdit.add(EDlbDetProb, null);
              pEdit.add(EDtaDetProb, null);
              pEdit.add(EDtaDetInte, null);
              pEdit.add(EDbtSau, null);
              pEdit.add(EDlbDetInte, null);
    /***********                ACTIONEVENT          *******************/     
              public void actionPerformed(ActionEvent e)
                   Object obj = e.getSource();
                   if (obj== EDbtSau)
                        setCursor(new Cursor(Cursor.WAIT_CURSOR));
                        if (ASGestAdm.SaveAs() == true)
                             emptyPanel("edit");
                             EDbtSau.setEnabled(false);
                        setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
         public void emptyPanel(String str)
                   if (str.trim().equals("edit") )
                        EDtfCli .setText("");
                        EDtfContact.setText("");
                        EDtfNoCon.setText("");
                        EDchNoAppel.setSelectedIndex(0);
                        EDtfTel.setText("");
                        EDtfPost.setText("");
                        EDchDetEquip.removeItemListener(this);
                        EDchDetEquip.removeAllItems();
                        EDchDetEquip.addItemListener(this);
                        EDtaDetProb.setText("");
                        EDtaDetInte.setText("");
              PLUS I'M ONLY HAVING THIS PROBLEM ON THE SECOND RESET, THEN ON THE THIRD TIME THERE ARE CURSORS
              IN BOTH TEXTAREA ....
              THANKS AGAIN

  • Problem disabling JButton in ActionListener after setText of JLabel

    What i want is when i click View to see the label say "Viewing ..." and in the same time the btnView (View Button) to be disabled.
    I want the same with the other 2 buttons.
    My problem is in ActionListener of the button. It only half works.
    I cannot disable (setEnabled(false)) the button after it is pressed and showing the JLabel.
    The code i cannot run is the 3 buttons setEnabled (2 in comments).
    Any light?
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    class BTester extends JFrame implements ActionListener { 
         JButton btnView, btnBook, btnSearch;
         BTester(){     //Constructor
              JPanel p = new JPanel();
         JButton btnView = new JButton( "View" );
         btnView.setActionCommand( "View" );
         btnView.addActionListener(this);
         JButton btnBook = new JButton( "Book" );
         btnBook.setActionCommand( "Book" );
         btnBook.addActionListener(this);
         JButton btnSearch = new JButton( "Search" );
         btnSearch.setActionCommand( "Search" );
         btnSearch.addActionListener(this);
         p.add(btnView);
         p.add(btnBook);
         p.add(btnSearch);
         getContentPane().add(show, "North"); //put text up
    getContentPane().add(p, "South"); //put panel of buttons down
    setSize(400,200);
    setVisible(true);
    setTitle("INITIAL BUTTON TESTER");
    show.setFont(new Font("Tahoma",Font.BOLD,20));
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);     
         //actionPerformed implemented (overrided)
         public void actionPerformed( ActionEvent ae) {
    String actionName = ae.getActionCommand().trim();
    if( actionName.equals( "View" ) ) {
    show.setText("Viewing ...");
         btnView.setEnabled(false); // The line of problem
    //btnBook.setEnabled(true);
    //btnSearch.setEnabled(true);
    else if( actionName.equals( "Book" ) ) {
    show.setText("Booking ...");
    //btnView.setEnabled(true);
    //btnBook.setEnabled(false);
    //btnSearch.setEnabled(true);
    else if( actionName.equals( "Search" ) ) {
    show.setText("Searching ...");
    //btnView.setEnabled(true);
    //btnBook.setEnabled(true);
    //btnSearch.setEnabled(false);
    } //end actionPerformed
         private JLabel show = new JLabel( "Press a button ... " );
    public static void main(String[] args) { 
         new BTester();
    } // End BTester class

    1. Use code formatting when posting code.
    2. You have a Null Pointer Exception since in your constructor you create the JButtons and assign them to a local variable instead of the class member.
    Change this
    JButton btnView = new JButton( "View" );to:
    btnView = new JButton( "View" );

  • JEditorPane, setText, and redraw problems.

    This code was borrowed from another post on the forum. The aim is to append lines of text onto the bottom of the editor pane.
        JEditorPane messagePane = new JEditorPane("text/html", "");
        String text = messagePane.getText();
        text = text.substring(text.indexOf("<body>") + 6, text.indexOf("</body>"));
        text = text + "<br>" + message;
        messagePane.setText(text);It works, but the whole editor pane flashes when setText is called.
    Is there anything I can do to prevent this? I've tried setDoubleBuffered(true) but that doesn't seem to work.
    There are a whole lot of methods on HTMLDocument like insertBeforeEnd which should allow me to insert content before the end body tag, but they don't work anyway.

    I've encoutered this problem and I use the following to replace the call to setText, actually this call causes the flicker effect you experience (for some obscure reason involving callbacks and property change)
            String myString = "<html><body>Sample text, put yours here</body></html>";
            EditorKit kit = this.messagePane.getEditorKit();
            Document newDocument = kit.createDefaultDocument();
            StringReader reader = new StringReader(myString);
            try
                kit.read(reader, newDocument, 0);
                this.messagePane.setDocument(newDocument);
            catch (Exception e)
                this.messagePane.setText("Error " + e);
            }Et voil�, no more flickering !

  • JTextPane.setText(String) - New line problem

    Hello.
    I'm usin a JTextPane for a small editor I need.
    I'm using it for it's ability to use HTML format codes (<font color = #color>string</font> for a singular line);
    Now, It's loading lines from a text file. Then, I made a function to parse the array data into a singular string, and return it.
    It's along the lines of
    String parseArrayToString(String[] data) {
        String returnString = "";
        for(String s : data)
            returnString += s+"\n";
        return returnString;
    }This worked for JTextArea, but not for this.
    Is there any way to do this using JTextPane?

    More or less straight from from the number 2 google hit...
    package forums;
    // a slighty cleaned up version of:
    // http://www.java2s.com/Code/Java/Swing-JFC/JTextPanedemowithvariousformatandhtmlloadingandrenderering.htm
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.IOException;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextPane;
    import javax.swing.text.Document;
    import javax.swing.text.AttributeSet;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.SimpleAttributeSet;
    import javax.swing.text.StyleConstants;
    public class JTextPaneDemo extends JPanel
      private static final long serialVersionUID = 1L;
      private static final SimpleAttributeSet ITALIC_GRAY = new SimpleAttributeSet();
      private static final SimpleAttributeSet BOLD_BLACK = new SimpleAttributeSet();
      private static final SimpleAttributeSet BLACK = new SimpleAttributeSet();
      static {
        StyleConstants.setForeground(ITALIC_GRAY, Color.gray);
        StyleConstants.setItalic(ITALIC_GRAY, true);
        StyleConstants.setFontFamily(ITALIC_GRAY, "Helvetica");
        StyleConstants.setFontSize(ITALIC_GRAY, 14);
        StyleConstants.setForeground(BOLD_BLACK, Color.black);
        StyleConstants.setBold(BOLD_BLACK, true);
        StyleConstants.setFontFamily(BOLD_BLACK, "Helvetica");
        StyleConstants.setFontSize(BOLD_BLACK, 14);
        StyleConstants.setForeground(BLACK, Color.black);
        StyleConstants.setFontFamily(BLACK, "Helvetica");
        StyleConstants.setFontSize(BLACK, 14);
      private JTextPane textPane = new JTextPane();
      public JTextPaneDemo() {
        textPane.setPreferredSize(new java.awt.Dimension(640, 480));
        JScrollPane scrollPane = new JScrollPane(textPane);
        add(scrollPane, BorderLayout.CENTER);
        appendText("\nHere's", BLACK);
        appendText(" Duke Baby", BOLD_BLACK);
        appendText("!\n\n", BLACK);
        textPane.insertIcon(new ImageIcon("C:/Java/home/src/crap/Java2D/images/duke.gif"));
        appendText("\n\nIsn't he just so cute ;-)\n\n", ITALIC_GRAY);
        JButton btnLoad = new JButton("Load web-page: The Java Tutorials");
        btnLoad.addActionListener(
          new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
              textPane.setEditable(false);
              try {
                textPane.setPage("http://java.sun.com/docs/books/tutorial/");
              } catch (IOException e) {
                e.printStackTrace();
        textPane.insertComponent(btnLoad);
        setVisible(true);
      private void appendText(String text, AttributeSet attributes) {
        try {
          Document doc = textPane.getDocument();
          doc.insertString(doc.getLength(), text, attributes);
        } catch (BadLocationException e) {
          e.printStackTrace();
      private static void createAndShowGUI() {
        JFrame frame = new JFrame("JTextPane Demo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new JTextPaneDemo());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
          public void run() {
            createAndShowGUI();
    }Cheers. Keith.

  • Problem with threads in my swing application

    Hi,
    I have some problem in running my swing app. Thre problem is related to threads.
    What i am developing, is a gui framework where i can add different pluggable components to the framework.
    The framework is working fine, but when i press the close action then the gui should close down the present component which is active. The close action is of the framework and the component has the responsibility of checking if it's work is saved or not and hence to throw a message for saving the work, therefore, what i have done is that i call the close method for the component in a separate thread and from my main thread i call the join method for the component's thread.But after join the whole gui hangs.
    I think after the join method even the GUI thread , which is started for every gui, also waits for the component's thread to finish but the component thread can't finish because the gui thread is also waiting for the component to finish. This creates a deadlock situation.
    I dont know wht's happening it's purely my guess.
    One more thing. Why i am calling the component through a different thread, is because , if the component's work is not saved by the user then it must throw a message to save the work. If i continue this message throwing in my main thread only then the main thread doesnt wait for user press of the yes no or cancel button for saving the work . It immediately progresses to the next statement.
    Can anybody help me get out of this?
    Regards,
    amazing_java

    For my original bad thread version, I have rewritten it mimicking javax.swing.Timer
    implementation, reducing average CPU usage to 2 - 3%.
    Will you try this:
    import javax.swing.*;
    import java.awt.*;
    import java.text.*;
    import java.util.*;
    public class SamurayClockW{
      JFrame frame;
      Container con;
      ClockTextFieldW ctf;
      public SamurayClockW(){
        frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        con = frame.getContentPane();
        ctf = new ClockTextFieldW();
        con.add(ctf, BorderLayout.SOUTH);
        frame.setBounds(100, 100, 300, 300);
        frame.setVisible(true);
        ctf.start();
      public static void main(String[] args){
        new SamurayClockW();
    class ClockTextFieldW extends JTextField implements Runnable{
      String clock;
      boolean running;
      public ClockTextFieldW(){
        setEditable(false);
        setHorizontalAlignment(RIGHT);
      public synchronized void start(){
        running = true;
        Thread t = new Thread(this);
        t.start();
      public synchronized void stop(){
        running = false;
      public synchronized void run(){
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        try{
          while (running){
            clock = sdf.format(new Date());
            SwingUtilities.invokeLater(new Runnable(){
              public void run(){
                setText(clock);
            try{
              wait(1000);
            catch (InterruptedException ie){
              ie.printStackTrace();
        catch (ThreadDeath td){
          running = false;
    }

  • Problem with threads in JFrame

    Hy everyone...i have a small problem when i try to insert clock in my JFrame , because all i get is an empty text field.
    What i do is that i create inner class that extends Thread and implements Runnable , but i dont know ... i saw some examples on the intrnet...but they are all for Applets...
    Does any one know how i can implement this in JFrame (JTextField in JFrame).
    Actually any material on threads in JFrame or JPanel would be great....THNX.

    For my original bad thread version, I have rewritten it mimicking javax.swing.Timer
    implementation, reducing average CPU usage to 2 - 3%.
    Will you try this:
    import javax.swing.*;
    import java.awt.*;
    import java.text.*;
    import java.util.*;
    public class SamurayClockW{
      JFrame frame;
      Container con;
      ClockTextFieldW ctf;
      public SamurayClockW(){
        frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        con = frame.getContentPane();
        ctf = new ClockTextFieldW();
        con.add(ctf, BorderLayout.SOUTH);
        frame.setBounds(100, 100, 300, 300);
        frame.setVisible(true);
        ctf.start();
      public static void main(String[] args){
        new SamurayClockW();
    class ClockTextFieldW extends JTextField implements Runnable{
      String clock;
      boolean running;
      public ClockTextFieldW(){
        setEditable(false);
        setHorizontalAlignment(RIGHT);
      public synchronized void start(){
        running = true;
        Thread t = new Thread(this);
        t.start();
      public synchronized void stop(){
        running = false;
      public synchronized void run(){
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        try{
          while (running){
            clock = sdf.format(new Date());
            SwingUtilities.invokeLater(new Runnable(){
              public void run(){
                setText(clock);
            try{
              wait(1000);
            catch (InterruptedException ie){
              ie.printStackTrace();
        catch (ThreadDeath td){
          running = false;
    }

  • File and FileInputStream problem

    Hi all
    I have downloaded from developpez.com a sample code to zip files. I modified it a bit to suit with my needs, and when I launched it, there was an exception. So I commented all the lines except for the first executable one; and when it succeeds then I uncomment the next executable line; and so on. When I arrived at the FileInputStream line , the exception raised. When I looked at the code, it seemed normal. So I want help how to solve it. Here is the code with the last executable line uncommented, and the exception stack :
    // Copyright (c) 2001
    package pack_zip;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import oracle.jdeveloper.layout.*;
    import java.io.*;
    import java.util.*;
    import java.util.zip.*;
    import java.text.*;
    * A Swing-based top level window class.
    * <P>
    * @author a
    public class fzip extends JFrame implements ActionListener{
    JPanel jPanel1 = new JPanel();
    XYLayout xYLayout1 = new XYLayout();
    JTextField szdir = new JTextField();
    JButton btn = new JButton();
    JButton bzip = new JButton();
         * Taille générique du tampon en lecture et écriture
    static final int BUFFER = 2048;
    * Constructs a new instance.
    public fzip() {
    super("Test zip");
    try {
    jbInit();
    catch (Exception e) {
    e.printStackTrace();
    * Initializes the state of this instance.
    private void jbInit() throws Exception {
    this.getContentPane().setLayout(xYLayout1);
         this.setSize(new Dimension(400, 300));
    btn.setText("btn");
    btn.setActionCommand("browse");
    btn.setLabel("Browse ...");
    btn.setFont(new Font("Dialog", 0, 14));
    bzip.setText("bzip");
    bzip.setActionCommand("zipper");
    bzip.setLabel("Zipper");
    bzip.setFont(new Font("Dialog", 0, 14));
    btn.addActionListener(this);
    bzip.addActionListener(this);
    bzip.setEnabled(false);
         this.getContentPane().add(jPanel1, new XYConstraints(0, 0, -1, -1));
    this.getContentPane().add(szdir, new XYConstraints(23, 28, 252, 35));
    this.getContentPane().add(btn, new XYConstraints(279, 28, 103, 38));
    this.getContentPane().add(bzip, new XYConstraints(128, 71, 103, 38));
    public void actionPerformed(ActionEvent e)
    if(e.getActionCommand() == "browse")
    FileDialog fd = new FileDialog(this);
    fd.setVisible(true);
    szdir.setText(fd.getDirectory());
    bzip.setEnabled(true);
    else
              * Compression
         try {
              // création d'un flux d'écriture sur fichier
         FileOutputStream dest = new FileOutputStream("Test_archive.zip");
              // calcul du checksum : Adler32 (plus rapide) ou CRC32
         CheckedOutputStream checksum = new CheckedOutputStream(dest, new Adler32());
              // création d'un buffer d'écriture
         BufferedOutputStream buff = new BufferedOutputStream(checksum);
              // création d'un flux d'écriture Zip
         ZipOutputStream out = new ZipOutputStream(buff);
         // spécification de la méthode de compression
         out.setMethod(ZipOutputStream.DEFLATED);
              // spécifier la qualité de la compression 0..9
         out.setLevel(Deflater.BEST_COMPRESSION);
         // buffer temporaire des données à écriture dans le flux de sortie
         byte data[] = new byte[BUFFER];
              // extraction de la liste des fichiers du répertoire courant
         File f = new File(szdir.getText());
         String files[] = f.list();
              // pour chacun des fichiers de la liste
         for (int i=0; i<files.length; i++) {
                   // en afficher le nom
              System.out.println("Adding: "+files);
    // création d'un flux de lecture
    FileInputStream fi = new FileInputStream(files[i]);
    /* // création d'un tampon de lecture sur ce flux
    BufferedInputStream buffi = new BufferedInputStream(fi, BUFFER);
    // création d'en entrée Zip pour ce fichier
    ZipEntry entry = new ZipEntry(files[i]);
    // ajout de cette entrée dans le flux d'écriture de l'archive Zip
    out.putNextEntry(entry);
    // écriture du fichier par paquet de BUFFER octets
    // dans le flux d'écriture
    int count;
    while((count = buffi.read(data, 0, BUFFER)) != -1) {
              out.write(data, 0, count);
                   // Close the current entry
    out.closeEntry();
    // fermeture du flux de lecture
              buffi.close();*/
    /*     // fermeture du flux d'écriture
         out.close();
         buff.close();
         checksum.close();
         dest.close();
         System.out.println("checksum: " + checksum.getChecksum().getValue());*/
         // traitement de toute exception
    catch(Exception ex) {
              ex.printStackTrace();
    And here is the error stack :
    "D:\jdev32\java1.2\jre\bin\javaw.exe" -mx50m -classpath "D:\jdev32\myclasses;D:\jdev32\lib\jdev-rt.zip;D:\jdev32\jdbc\lib\oracle8.1.7\classes12.zip;D:\jdev32\lib\connectionmanager.zip;D:\jdev32\lib\jbcl2.0.zip;D:\jdev32\lib\jgl3.1.0.jar;D:\jdev32\java1.2\jre\lib\rt.jar" pack_zip.czip
    Adding: accueil188.cfm
    java.io.FileNotFoundException: accueil188.cfm (Le fichier spécifié est introuvable.
         void java.io.FileInputStream.open(java.lang.String)
         void java.io.FileInputStream.<init>(java.lang.String)
         void pack_zip.fzip.actionPerformed(java.awt.event.ActionEvent)
         void javax.swing.AbstractButton.fireActionPerformed(java.awt.event.ActionEvent)
         void javax.swing.AbstractButton$ForwardActionEvents.actionPerformed(java.awt.event.ActionEvent)
         void javax.swing.DefaultButtonModel.fireActionPerformed(java.awt.event.ActionEvent)
         void javax.swing.DefaultButtonModel.setPressed(boolean)
         void javax.swing.plaf.basic.BasicButtonListener.mouseReleased(java.awt.event.MouseEvent)
         void java.awt.Component.processMouseEvent(java.awt.event.MouseEvent)
         void java.awt.Component.processEvent(java.awt.AWTEvent)
         void java.awt.Container.processEvent(java.awt.AWTEvent)
         void java.awt.Component.dispatchEventImpl(java.awt.AWTEvent)
         void java.awt.Container.dispatchEventImpl(java.awt.AWTEvent)
         void java.awt.Component.dispatchEvent(java.awt.AWTEvent)
         void java.awt.LightweightDispatcher.retargetMouseEvent(java.awt.Component, int, java.awt.event.MouseEvent)
         boolean java.awt.LightweightDispatcher.processMouseEvent(java.awt.event.MouseEvent)
         boolean java.awt.LightweightDispatcher.dispatchEvent(java.awt.AWTEvent)
         void java.awt.Container.dispatchEventImpl(java.awt.AWTEvent)
         void java.awt.Window.dispatchEventImpl(java.awt.AWTEvent)
         void java.awt.Component.dispatchEvent(java.awt.AWTEvent)
         void java.awt.EventQueue.dispatchEvent(java.awt.AWTEvent)
         boolean java.awt.EventDispatchThread.pumpOneEvent()
         void java.awt.EventDispatchThread.pumpEvents(java.awt.Conditional)
         void java.awt.EventDispatchThread.run()
    Thank you very much

    One easy way to send a file through RMI is to read all bytes of a file to a byte array and send this array as a parameter of a remote method. But of course you may have problems with memory when you send large files. The receive is simillary.
    Other way is to split the file and getting slices of the file, sending slices and re-assemble at destination. This assume that the file isn't changed through the full transfering is concluded.
    I hope these could help you.

  • URGENT HELP NEEDED FOR JTABLE PROBLEM!!!!!!!!!!!!!!!!!

    firstly i made a jtable to adds and deletes rows and passes the the data to the table model from some textfields. then i wanted to add a tablemoselistener method in order to change the value in the columns 1,2,3,4 and set the result of them in the column 5. when i added that portion of code the buttons that added and deleted rows had problems to function correctly..they dont work at all..can somebody have a look in my code and see wot is wrong..thanx in advance..
    below follows the code..sorry for the mesh of the code..you can use and run the code and notice the problem when you press the add button..also if you want delete the TableChanged method to see that the add button works perfect.
    * Created on 03-Aug-2005
    * TODO To change the template for this generated file go to
    * Window - Preferences - Java - Code Style - Code Templates
    * @author Administrator
    * TODO To change the template for this generated type comment go to
    * Window - Preferences - Java - Code Style - Code Templates
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.Vector;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.TableModelEvent;
    import javax.swing.event.TableModelListener;
    import java.io.*;
    public class NodesTable extends JFrame implements TableModelListener, ActionListener {
    JTable jt;
    DefaultTableColumnModel dtcm;
    TableColumn column[] = new TableColumn[100];
    DefaultTableModel dtm;
    JLabel Name,m1,w1,m2,w2;
    JTextField NameTF,m1TF,w1TF,m2TF,w2TF;
    String c [] ={ "Name", "Assessment1", "Weight1" , "Assessment2","Weight2 ","TotalMark"};
    float x=0,y=0,tMark=0,z = 0;
    float j=0;
    int i;
         JButton DelButton;
         JButton AddButton;
         JScrollPane scrollPane;
         JPanel mainPanel,buttonPanel;
         JFrame frame;
         Object[][] data =
              {"tami", new Float(1), new Float(1.11), new Float(1.11),new Float(1),new Float(1)},
              {"tami", new Float(1), new Float(2.22), new Float(2.22),new Float(1),new Float(1)},
              {"petros", new Float(1), new Float(3.33), new Float(3.33),new Float(1),new Float(1)},
              {"petros", new Float(1), new Float(4.44), new Float(4.44),new Float(1),new Float(1)}
    public NodesTable() {
    super("Student Marking Spreadsheet");
    this.AddNodesintoTable();
    setSize(400,250);
    setVisible(true);
    public void AddNodesintoTable(){
    // Create a vector object and load them with the data
    // to be placed on each row of the table
    dtm = new DefaultTableModel(data,c);
    dtm.addTableModelListener( this );
    jt = new JTable(dtm){
         // Returning the Class of each column will allow different
              // renderers to be used based on Class
              public Class getColumnClass(int column)
                   return getValueAt(0, column).getClass();
              // The Cost is not editable
              public boolean isCellEditable(int row, int column)
                   int modelColumn = convertColumnIndexToModel( column );
                   return (modelColumn == 5) ? false : true;
    //****************************User Input**************************
    //Add another node
    //Creating and setting the properties
    //of the panel's component (panels and textfields)
    Name = new JLabel("Name");
    Name.setForeground(Color.black);
    m1 = new JLabel("Mark1");
    m1.setForeground(Color.black);
    w1 = new JLabel("Weigth1");
    w1.setForeground(Color.black);
    m2= new JLabel("Mark2");
    m2.setForeground(Color.black);
    w2 = new JLabel("Weight2");
    w2.setForeground(Color.black);
    NameTF = new JTextField(5);
    NameTF.setText("Node");
    m1TF = new JTextField(5);
    w1TF = new JTextField(5);
    m2TF=new JTextField(5);
    w2TF=new JTextField(5);
    //creating the buttons
    JPanel buttonPanel = new JPanel();
    AddButton=new JButton("Add Row");
    DelButton=new JButton("Delete") ;
    buttonPanel.add(AddButton);
    buttonPanel.add(DelButton);
    //adding the components to the panel
    JPanel inputpanel = new JPanel();
    inputpanel.add(Name);
    inputpanel.add(NameTF);
    inputpanel.add(m1);
    inputpanel.add(m1TF);
    inputpanel.add(w1);
    inputpanel.add(w1TF);
    inputpanel.add(m2);
    inputpanel.add(m2TF);
    inputpanel.add(w2TF);
    inputpanel.add(w2);
    inputpanel.add(AddButton);
    inputpanel.add(DelButton);
    //creating the panel and setting its properties
    JPanel tablepanel = new JPanel();
    tablepanel.add(new JScrollPane(jt, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED
    , JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS));
    getContentPane().add(tablepanel, BorderLayout.CENTER);
    getContentPane().add(inputpanel, BorderLayout.SOUTH);
    //Method to add row for each new entry
    public void addRow()
    Vector r=new Vector();
    r=createBlankElement();
    dtm.addRow(r);
    jt.addNotify();
    public Vector createBlankElement()
    Vector t = new Vector();
    t.addElement((String) " ");
    t.addElement((String) " ");
    t.addElement((String) " ");
    t.addElement((String) " ");
    t.addElement((String) " ");
    return t;
    // Method to delete a row from the spreadsheet
    void deleteRow(int index)
    if(index!=-1) //At least one Row in Table
    dtm.removeRow(index);
    jt.addNotify();
    // Method that adds and deletes rows
    // from the table by pressing the
    //corresponding buttons
    public void actionPerformed(ActionEvent ae){
         Float z=new Float (m2TF.getText());
    String Name= NameTF.getText();
    Float x= new Float(m1TF.getText());
    Float y= new Float(w1TF.getText());
    Float j=new Float (w2TF.getText());
    JFileChooser jfc2 = new JFileChooser();
    String newdata[]= {Name,String.valueOf(x),String.valueOf(y),
    String.valueOf(z),String.valueOf(j)};
    Object source = ae.getSource();
    if(ae.getSource() == (JButton)AddButton)
    addRow();
    if (ae.getSource() ==(JButton) DelButton)
    deleteRow(jt.getSelectedRow());
    //method to calculate the total mark in the TotalMark column
    //that updates the values in every other column
    //It takes the values from the column 1,2,3,4
    //and changes the value in the column 5
    public void tableChanged(TableModelEvent e) {
         System.out.println(e.getSource());
         if (e.getType() == TableModelEvent.UPDATE)
              int row = e.getFirstRow();
              int column = e.getColumn();
              if (column == 1 || column == 2 ||column == 3 ||column == 4)
                   TableModel model = jt.getModel();
              float     q= ((Float)model.getValueAt(row,1)).floatValue();
              float     w= ((Float)model.getValueAt(row,2)).floatValue();
              float     t= ((Float)model.getValueAt(row,3)).floatValue();
              float     r= ((Float)model.getValueAt(row,4)).floatValue();
                   Float tMark = new Float((q*w+t*r)/(w+r) );
                   model.setValueAt(tMark, row, 5);
    // Which cells are editable.
    // It is only necessary to implement this method
    // if the table is editable
    public boolean isCellEditable(int row, int col)
    { return true; //All cells are editable
    public static void main(String[] args) {
         NodesTable t=new NodesTable();
    }

    There are too many mistakes in your program. It looks like you are new to java.
    Your add and delete row buttons are not working because you haven't registered your action listener with these buttons.
    I have modifide your code and now it works fine. Just put some validation code for the textboxes becuase it throws exception when user presses add button without entering anything.
    Here is the updated code: Do the diff and u will know my changes
    * Created on 03-Aug-2005
    * TODO To change the template for this generated file go to
    * Window - Preferences - Java - Code Style - Code Templates
    * @author Administrator
    * TODO To change the template for this generated type comment go to Window -
    * Preferences - Java - Code Style - Code Templates
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    import javax.swing.event.TableModelEvent;
    import javax.swing.event.TableModelListener;
    import javax.swing.table.DefaultTableColumnModel;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableColumn;
    import javax.swing.table.TableModel;
    public class NodesTable extends JFrame implements TableModelListener,
              ActionListener {
         JTable jt;
         DefaultTableColumnModel dtcm;
         TableColumn column[] = new TableColumn[100];
         DefaultTableModel dtm;
         JLabel Name, m1, w1, m2, w2;
         JTextField NameTF, m1TF, w1TF, m2TF, w2TF;
         String c[] = { "Name", "Assessment1", "Weight1", "Assessment2", "Weight2 ",
                   "TotalMark" };
         float x = 0, y = 0, tMark = 0, z = 0;
         float j = 0;
         int i;
         JButton DelButton;
         JButton AddButton;
         JScrollPane scrollPane;
         JPanel mainPanel, buttonPanel;
         JFrame frame;
         public NodesTable() {
              super("Student Marking Spreadsheet");
              this.AddNodesintoTable();
              setSize(400, 250);
              setVisible(true);
         public void AddNodesintoTable() {
              // Create a vector object and load them with the data
              // to be placed on each row of the table
              dtm = new DefaultTableModel(c,0);
              dtm.addTableModelListener(this);
              jt = new JTable(dtm) {
                   // The Cost is not editable
                   public boolean isCellEditable(int row, int column) {
                        int modelColumn = convertColumnIndexToModel(column);
                        return (modelColumn == 5) ? false : true;
              //****************************User Input**************************
              //Add another node
              //Creating and setting the properties
              //of the panel's component (panels and textfields)
              Name = new JLabel("Name");
              Name.setForeground(Color.black);
              m1 = new JLabel("Mark1");
              m1.setForeground(Color.black);
              w1 = new JLabel("Weigth1");
              w1.setForeground(Color.black);
              m2 = new JLabel("Mark2");
              m2.setForeground(Color.black);
              w2 = new JLabel("Weight2");
              w2.setForeground(Color.black);
              NameTF = new JTextField(5);
              NameTF.setText("Node");
              m1TF = new JTextField(5);
              w1TF = new JTextField(5);
              m2TF = new JTextField(5);
              w2TF = new JTextField(5);
              //creating the buttons
              JPanel buttonPanel = new JPanel();
              AddButton = new JButton("Add Row");
              AddButton.addActionListener(this);
              DelButton = new JButton("Delete");
              DelButton.addActionListener(this);
              buttonPanel.add(AddButton);
              buttonPanel.add(DelButton);
              //adding the components to the panel
              JPanel inputpanel = new JPanel();
              inputpanel.add(Name);
              inputpanel.add(NameTF);
              inputpanel.add(m1);
              inputpanel.add(m1TF);
              inputpanel.add(w1);
              inputpanel.add(w1TF);
              inputpanel.add(m2);
              inputpanel.add(m2TF);
              inputpanel.add(w2TF);
              inputpanel.add(w2);
              inputpanel.add(AddButton);
              inputpanel.add(DelButton);
              //creating the panel and setting its properties
              JPanel tablepanel = new JPanel();
              tablepanel.add(new JScrollPane(jt,
                        JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                        JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS));
              getContentPane().add(tablepanel, BorderLayout.CENTER);
              getContentPane().add(inputpanel, BorderLayout.SOUTH);
         //Method to add row for each new entry
         public void addRow() {
              Float z = new Float(m2TF.getText());
              String Name = NameTF.getText();
              Float x = new Float(m1TF.getText());
              Float y = new Float(w1TF.getText());
              Float j = new Float(w2TF.getText());
              String newdata[] = { Name, String.valueOf(x), String.valueOf(y),
                        String.valueOf(z), String.valueOf(j) };
              dtm.addRow(newdata);
         // Method to delete a row from the spreadsheet
         void deleteRow(int index) {
              if (index != -1) //At least one Row in Table
                   dtm.removeRow(index);
                   jt.addNotify();
         // Method that adds and deletes rows
         // from the table by pressing the
         //corresponding buttons
         public void actionPerformed(ActionEvent ae) {
              Object source = ae.getSource();
              if (ae.getSource() == (JButton) AddButton) {
                   addRow();
              if (ae.getSource() == (JButton) DelButton) {
                   deleteRow(jt.getSelectedRow());
         //method to calculate the total mark in the TotalMark column
         //that updates the values in every other column
         //It takes the values from the column 1,2,3,4
         //and changes the value in the column 5
         public void tableChanged(TableModelEvent e) {
              System.out.println(e.getSource());
              //if (e.getType() == TableModelEvent.UPDATE) {
                   int row = e.getFirstRow();
                   int column = e.getColumn();
                   if (column == 1 || column == 2 || column == 3 || column == 4) {
                        TableModel model = jt.getModel();
                        float q = (new Float(model.getValueAt(row, 1).toString())).floatValue();
                        float w = (new Float(model.getValueAt(row, 2).toString())).floatValue();
                        float t = (new Float(model.getValueAt(row, 3).toString())).floatValue();
                        float r = (new Float(model.getValueAt(row, 4).toString())).floatValue();
                        Float tMark = new Float((q * w + t * r) / (w + r));
                        model.setValueAt(tMark, row, 5);
         // Which cells are editable.
         // It is only necessary to implement this method
         // if the table is editable
         public boolean isCellEditable(int row, int col) {
              return true; //All cells are editable
         public static void main(String[] args) {
              NodesTable t = new NodesTable();
    }

Maybe you are looking for