AddActionListener Problem

package REAL;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import javax.swing.*;
public class ClientMain extends Frame
    private Button ExitB;
      ClientMain()
  {     addWindowListener(new WindowAdapter()
    { public void windowClosing(WindowEvent e)
        System.exit(0);
    loadFrame();
    setTitle("Client Main");
    setBounds(50, 50, 360, 330);
  public void actionPerformed(ActionEvent event)
  if (event.getSource() == ExitB)
      System.exit(0);
      private void loadFrame()
    ExitB = new Button();
    ExitB.setBounds(239, 295, 56, 23);     
    ExitB.setLabel("Exit");
    setLayout(null);
    add(ExitB);
    ExitB.addActionListener(this);
public static void main(String[] args)
    ClientMain testframe = new ClientMain();
    testframe.setVisible(true);
}after compiling it gicews this error
REAL/ClientMain.java [43:1] addActionListener(java.awt.event.ActionListener) in java.awt.Button cannot be applied to (REAL.ClientMain)
ExitB.addActionListener(this);
^
1 error
Errors compiling ClientMain.

Add an implements ActionListener:
public class ClientMain extends Frame implements ActionListener

Similar Messages

  • JComboBox addActionListener problem?

    HI,
    i am using JComboBox to add each item action perform of use StyleEditorKit.FontSizeAction("String", int), but i only can add one item action perform only. See my code any problem...
    for(int i>12;i<=50 ; i++){
                  comboBox.addItem(" "+i);
               // i want to loop each item can function
                comboBox.addActionListener(new StyleEditorKit.FontSizeAcion("i ", i)Thanks

    FontSizeAction is able to set the size to a value delivered in String format as the command String of its ActionEvent. Unfortunately, the JComboBox doesn't deliver the String value of the selected item as command string but an arbitrary value to be set once. So you have to wrap your FontSizeAction in a custom ActionListener of your own where you retrieve the selected item, cast it to a String and pass this value to FontSizeAction as the command String of a new ActionEvent object.
    You should also get rid of that whitespace when creating the size value, String.valueOf(int) is a better way to create a String for an int.

  • Problem on referencing "this" keyword on addActionListener

    Hi!
    I'm Ryan, ahm I've been studying on Swing Applications, ahm on this program I'm trying to handle the JMenuItem event when the user clicks a menu item, here's my code below:
    import java.awt.event.*;
    import javax.swing.*;
    public class MenuTest implements ActionListener{
    private static void createAndShowGUI(){
    //Delarations
    JFrame frame = new JFrame("MP3Stego");
    frame.setSize(300,300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JMenuBar menuBar;
    menuBar = new JMenuBar();
    JMenu menu;
    menu = new JMenu("File");
    menu.setMnemonic(KeyEvent.VK_F);
    menu.getAccessibleContext().setAccessibleDescription("Open/Edit a File");
    menuBar.add(menu);
    JMenuItem menuFileOpen = new JMenuItem("Open");
    menuFileOpen.setMnemonic(KeyEvent.VK_O);
    menuFileOpen.addActionListener(this);
    menu.add(menuFileOpen);
    frame.setJMenuBar(menuBar);
    //frame.pack();
    frame.setVisible(true);
    public void actionPerformed(ActionEvent e){
    JOptionPane.showMessageDialog(null,"File Open");
    public static void main (String[] args){
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();
    Sir, the problem is when I try to use menuFileOpen.addActionListener(this); it says that
    MenuTest.java:24: non-static variable this cannot be referenced from a static co
    menuFileOpen.addActionListener(this);
    I see that I'm using non-static "this" on static createAndShowGUI, ahm is there a way for me to reference this keyword on a static method? or should I create a non-static method to put the action listener?
    Thank you so much Sir
    Ryan

    First, when you post code, use the button to put [code][/code] tags around your code.
    Second, a static method does not have a this to reference. You should make createAndShowGUI non-static, and create an instance of your class in your static main method. You can then call createAndShowGUI. You do not need to use a Runnable. The event thread will invoke your actionPerformed method.
    I'm not sure where you got the ideas you use to create this program, but the Swing tutorial gives some pretty clear examples of how to write Swing applications.
    http://java.sun.com/docs/books/tutorial/uiswing/learn/index.html
    � {�                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • AddActionListener to JDielog problem please help

    HI
    I have an add button on a jframe,
    The add button brings up a Jdielog, and the dielog has a save button,
    Now to the save button I have an addActionListenere to save the adding,
    And it doesn�t work.
    If I change the dielog to a jframe the addActionListenr works fine, why?
    Thanks

    the word print dosn't show
    public class Gas extends JFrame
    JButton addButton;
    public Gas( Connection connect )
    super( "Enter Information" );
    addButton = new JButton( "Add Product" );
    addButton.addActionListener( new ActionListener() {
    public void actionPerformed( ActionEvent event )
    final JDialog d = new JDialog();
    d.setModal(true);
    JButton saveB = new JButton("Save");
    Container c = d.getContentPane();
    c.setLayout(new FlowLayout(1,18,17));
    c.add(saveB);
    d.setSize(225,160);
    d.setVisible(true);
    saveB.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent event)
    System.out.print("print");

  • Problem with addActionListener()

    hey,
    i'm new to java.
    i have this code:
    import java.awt.*;
    import java.applet.*;
    import java.awt.event.*;
    import java.awt.event.ActionListener;
    public class first extends Applet {
        Button RedButton, GreenButton;
        TextField Txt;
        public void init()
            RedButton = new Button("Red");
            GreenButton = new Button("Green");
            add(RedButton);
            add(GreenButton);
            RedButton.addActionListener(this);
            Txt = new TextField("Text Field", 30);
            add(Txt);
        public void actionPerformed(ActionEvent e)
    }when i try to compile this code i get an error:
    addActionListener(java.awt.event.ActionListener) in java.awt.Button cannot be applied to (first)*
    RedButton.addActionListener(this);*
    i have no idea what it means,
    the error appears in this line:
    RedButton.addActionListener(this);*
    and it appears when i try to use the this+ operator as arggument.
    thank!
    Edited by: TrIpOd93 on Dec 11, 2009 2:17 PM

    It's saying that addActionListener wants an argument which implements ActionListener. But the class you're defining (the this) does not implement ActionListener.
    Making one big class that implements everything and adds itself to all the widgets' listeners is an old outdated idiom anyway. Create some inner classes to be the event handlers.

  • Problem with JFrame and busy/wait Cursor

    Hi -- I'm trying to set a JFrame's cursor to be the busy cursor,
    for the duration of some operation (usually just a few seconds).
    I can get it to work in some situations, but not others.
    Timing does seem to be an issue.
    There are thousands of posts on the BugParade, but
    in general Sun indicates this is not a bug. I just need
    a work-around.
    I've written a test program below to demonstrate the problem.
    I have the problem on Solaris, running with both J2SE 1.3 and 1.4.
    I have not tested on Windows yet.
    When you run the following code, three JFrames will be opened,
    each with the same 5 buttons. The first "F1" listens to its own
    buttons, and works fine. The other two (F2 and F3) listen
    to each other's buttons.
    The "BUSY" button simply sets the cursor on its listener
    to the busy cursor. The "DONE" button sets it to the
    default cursor. These work fine.
    The "SLEEP" button sets the cursor, sleeps for 3 seconds,
    and sets it back. This does not work.
    The "INVOKE LATER" button does the same thing,
    except is uses invokeLater to sleep and set the
    cursor back. This also does not work.
    The "DELAY" button sleeps for 3 seconds (giving you
    time to move the mouse into the other (listerner's)
    window, and then it behaves just like the "SLEEP"
    button. This works.
    Any ideas would be appreciated, thanks.
    -J
    import java.awt.BorderLayout;
    import java.awt.Cursor;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
    public class BusyFrameTest implements ActionListener
    private static Cursor busy = Cursor.getPredefinedCursor (Cursor.WAIT_CURSOR);
    private static Cursor done = Cursor.getDefaultCursor();
    JFrame frame;
    JButton[] buttons;
    public BusyFrameTest (String title)
    frame = new JFrame (title);
    buttons = new JButton[5];
    buttons[0] = new JButton ("BUSY");
    buttons[1] = new JButton ("DONE");
    buttons[2] = new JButton ("SLEEP");
    buttons[3] = new JButton ("INVOKE LATER");
    buttons[4] = new JButton ("DELAY");
    JPanel buttonPanel = new JPanel();
    for (int i = 0; i < buttons.length; i++)
    buttonPanel.add (buttons);
    frame.getContentPane().add (buttonPanel);
    frame.pack();
    frame.setVisible (true);
    public void addListeners (ActionListener listener)
    for (int i = 0; i < buttons.length; i++)
    buttons[i].addActionListener (listener);
    public void actionPerformed (ActionEvent e)
    System.out.print (frame.getTitle() + ": " + e.getActionCommand());
    if (e.getActionCommand().equals ("BUSY"))
    frame.setCursor (busy);
    else if (e.getActionCommand().equals ("DONE"))
    frame.setCursor (done);
    else if (e.getActionCommand().equals ("SLEEP"))
    frame.setCursor (busy);
    try { Thread.sleep (3000); } catch (Exception ex) { }
    frame.setCursor (done);
    System.out.print (" finished");
    else if (e.getActionCommand().equals ("INVOKE LATER"))
    frame.setCursor (busy);
    SwingUtilities.invokeLater (thread);
    else if (e.getActionCommand().equals ("DELAY"))
    try { Thread.sleep (3000); } catch (Exception ex) { }
    frame.setCursor (busy);
    try { Thread.sleep (3000); } catch (Exception ex) { }
    frame.setCursor (done);
    System.out.print (" finished");
    System.out.println();
    Runnable thread = new Runnable()
    public void run()
    try { Thread.sleep (3000); } catch (Exception ex) { }
    frame.setCursor (done);
    System.out.println (" finished");
    public static void main (String[] args)
    BusyFrameTest f1 = new BusyFrameTest ("F1");
    f1.addListeners (f1);
    BusyFrameTest f2 = new BusyFrameTest ("F2");
    BusyFrameTest f3 = new BusyFrameTest ("F3");
    f2.addListeners (f3); // 2 listens to 3
    f3.addListeners (f2); // 3 listens to 2

    I've had the same problems with cursors and repaints in a swing application, and I was thinking of if I could use invokeLater, but I never got that far with it.
    I still believe you would need a thread for the time consuming task, and that invokeLater is something you only need to use in a thread different from the event thread.

  • 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();
    }

  • Problem with PDFBox-0.7.3 library - Runtime Error

    Hello,
    The problem is inside the method "chamaConversor".
    " conversor.pdfToText(arquivoPdf,arquivoTxt);" make a file.txt from one file.pdf. After that it don?t return the control to "ConstrutorDeTemplate2.java", and show the following error message:
    Exception in thread "AWT-EventQueue-O" java.lang.NoClassDefFoundError : org/fontbox/afm/FontMetric
    at org.pdfbox.pdmodel.font.PDFont.getAFM (PDFont.java:334)
    I am using the NetBeans IDE 5.5.
    I have added all of these libraries below to my project from c:\Program Files\netbeans-5.5\PDFBox-0.7.3\external:
    * FontBox-0.1.0-dev.jar
    * ant.jar
    * bcmail-jdk14-132.jar
    * junit.jar
    * bcprov-jdk14-132.jar
    * lucene-core-2.0.0.jar
    * checkstyle-all-4.2.jar
    * lucene-demos-2.0.0.jar
    and PDFBox-0.7.3.jar from c:\Program Files\netbeans-5.5\PDFBox-0.7.3\lib.
    There are no more jar from PDFBox-0.7.3 directory.
    All of these libraries are in "Compile-time Libraries" option in Project Properties. Should I add they to "Run-time Libraries" option?
    What is going on?
    Thank you!
      * ConstrutorDeTemplate2.java
      * Created on 11 de Agosto de 2007, 14:54
      * @author
    package br.unifacs.dis2007.template2;
    // Java core packages
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.text.*;
    import java.util.*;
    // Java extension packages
    import javax.swing.*;
    import org.pdfbox.*;
    public class ConstrutorDeTemplate2 extends JFrame
        implements ActionListener {
        private JTextField enterField;
        private JTextArea outputArea;
        private BufferedWriter out;
        private String word;
        private PdfToText conversor = new PdfToText();
        // ajusta a interface do usu?rio
        public ConstrutorDeTemplate2()
           super( "Testing class File" );
           enterField = new JTextField("Digite aqui o nome do arquivo :" );
           enterField.addActionListener( this );
           outputArea = new JTextArea();
           ScrollPane scrollPane = new ScrollPane();
           scrollPane.add( outputArea );
           Container container = getContentPane();
           container.add( enterField, BorderLayout.NORTH );
           container.add( scrollPane, BorderLayout.CENTER );
           setSize( 400, 400 );
           show();
        // Exibe as informa??es sobre o arquivo especificado pelo usu?rio
        public void actionPerformed( ActionEvent actionEvent )
           File name = new File( actionEvent.getActionCommand() );
           // Se o arquivo existe, envia para a sa?da as informa??es sobre ele
           if ( name.exists() ) {
              outputArea.setText(
                 name.getName() + " exists\n" +
                 ( name.isFile () ?
                    "is a file\n" : "is not a file\n" ) +
                 ( name.isDirectory() ?
                    "is a directory\n" : "is not a directory\n" ) +
                 ( name.isAbsolute() ? "is absolute path\n" :
                    "is not absolute path\n" ) +
                 "Last modified: " + name.lastModified() +
                 "\nLength: " + name.length () +
                 "\nPath: " + name.getPath() +
                 "\nAbsolute path: " + name.getAbsolutePath() +
                 "\nParent: " + name.getParent() );
              // informa??o de sa?da se "name" ? um arquivo
              if ( name.isFile() ) {
                 String nameString = String.valueOf(name.getPath());
                 String nameTeste = new String(nameString);
                 if (nameString.endsWith(".pdf"))
                     nameTeste = chamaConversor(nameString);
                 else
                     if (nameString.endsWith(".doc"))
                         nameTeste = chamaConversorDoc(nameString); // chama conversor de arquivos DOC
                     else
                         if (nameString.endsWith(".txt"))
                             nameTeste = nameString;
                 // se o arquivo termina com ".txt"           
                 if (nameTeste.endsWith(".txt"))
                     // acrescenta conte?do do arquivo ? ?rea de sa?da
                     try {
                         // Create the tokenizer to read from a file
                         FileReader rd = new FileReader(nameTeste);
                         StreamTokenizer st = new StreamTokenizer(rd);
                         // Prepare the tokenizer for Java-style tokenizing rules
                         st.parseNumbers();
                         st.wordChars('_', '_');
                         st.eolIsSignificant (true);
                         // If whitespace is not to be discarded, make this call
                         st.ordinaryChars(0, ' ');
                         // These calls caused comments to be discarded
                         st.slashSlashComments(true);
                         st.slashStarComments(true);
                         // Parse the file
                         int token = st.nextToken();
                         String word_ant = "";
                         outputArea.append( " \n" );
                         out = new BufferedWriter(new FileWriter(nameTeste, true));
                         while (token != StreamTokenizer.TT_EOF) {
                             token = st.nextToken();
                             if (token == StreamTokenizer.TT_EOL){
                                 //out.write(word);
                                 out.flush();
                                 out = new BufferedWriter(new FileWriter(nameTeste, true));
                                 //outputArea.append( word + "\n" );
                                 // out.append ( "\n" );
                             switch (token) {
                             case StreamTokenizer.TT_NUMBER:
                                 // A number was found; the value is in nval
                                 double num = st.nval;
                                 break;
                             case StreamTokenizer.TT_WORD:
                                 // A word was found; the value is in sval
                                 word = st.sval;
                                 //   if (word_ant.equals("a") || word_ant.equals("an") || word_ant.equals("the") || word_ant.equals("The") || word_ant.equals("An"))
                                 outputArea.append( word.toString() + " \n " );
                                // out.append( word + "   " );
                                 //     word_ant = word;
                                 break;
                             case '"':
                                 // A double-quoted string was found; sval contains the contents
                                 String dquoteVal = st.sval;
                                 break;
                             case '\'':
                                 // A single-quoted string was found; sval contains the contents
                                 String squoteVal = st.sval;
                                 break;
                             case StreamTokenizer.TT_EOL:
                                 // End of line character found
                                 break;
                             case StreamTokenizer.TT_EOF:
                                 // End of file has been reached
                                 break;
                             default:
                                 // A regular character was found; the value is the token itself
                                 char ch = (char)st.ttype;
                                 break;
                             } // fim do switch
                         } // fim do while
                         rd.close();
                         out.close();
                     } // fim do try
                     // process file processing problems
                     catch( IOException ioException ) {
                         JOptionPane.showMessageDialog( this,
                         "FILE ERROR",
                         "FILE ERROR", JOptionPane.ERROR_MESSAGE );
                 } // fim do if da linha 92 - testa se o arquivo ? do tipo texto
              } // fim do if da linha 78 - testa se ? um arquivo
              // output directory listing
              else if ( name.isDirectory() ) {
                     String directory[] = name.list();
                 outputArea.append( "\n\nDirectory contents:\n");
                 for ( int i = 0; i < directory.length; i++ )
                    outputArea.append( directory[ i ] + "\n" );
              } // fim do else if da linha 184 - testa se ? um diret?rio
           } // fim do if da linha 62 - testa se o arquivo existe
           // not file or directory, output error message
           else {
              JOptionPane.showMessageDialog( this,
                 actionEvent.getActionCommand() + " Does Not Exist",
                 "ERROR", JOptionPane.ERROR_MESSAGE );
        }  // fim do m?todo actionPerformed
        // m?todo que chama o conversor
        public String chamaConversor(String arquivoPdf){
            String arquivoTxt = new String(arquivoPdf);
            arquivoTxt = arquivoPdf.replace(".pdf", ".txt");
            try {
                conversor.pdfToText(arquivoPdf,arquivoTxt);
            catch (Exception ex) {
                ex.printStackTrace();
            return (arquivoTxt);
        // executa a aplica??o
        public static void main( String args[] )
           ConstrutorDeTemplate2 application = new ConstrutorDeTemplate2();
           application.setDefaultCloseOperation (
              JFrame.EXIT_ON_CLOSE );
        } // fim do m?todo main
    }  // fim da classe ExtratorDeSubstantivos2
      * PdfToText.java
      * Created on 11 de Agosto de 2007, 10:57
      * To change this template, choose Tools | Template Manager
      * and open the template in the editor.
    //package br.unifacs.dis2007.template2;
      * @author www
    package br.unifacs.dis2007.template2;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.OutputStreamWriter;
    import java.io.Writer;
    import java.net.MalformedURLException;
    import java.net.URL ;
    import org.pdfbox.pdmodel.PDDocument;
    import org.pdfbox.pdmodel.encryption.AccessPermission;
    import org.pdfbox.pdmodel.encryption.StandardDecryptionMaterial;
    import org.pdfbox.util.PDFText2HTML;
    import org.pdfbox.pdmodel.font.PDFont.* ;
    import org.pdfbox.util.PDFTextStripper;
    import org.pdfbox.util.*;
    import org.pdfbox.pdmodel.*;
    public class PdfToText
        public void pdfToText( String pdfFile, String textFile) throws Exception
                Writer output = null;
                PDDocument document = null;
                try
                    try
                        //basically try to load it from a url first and if the URL
                        //is not recognized then try to load it from the file system.
                        URL url = new URL( pdfFile );
                        document = PDDocument.load( url );
                        String fileName = url.getFile();
                        if( textFile == null && fileName.length () >4 )
                            File outputFile =
                                new File( fileName.substring( 0,fileName.length() -4 ) + ".txt" );
                            textFile = outputFile.getName();
                    catch( MalformedURLException e )
                        document = PDDocument.load( pdfFile );
                        if( textFile == null && pdfFile.length() >4 )
                            textFile = pdfFile.substring( 0,pdfFile.length() -4 ) + ".txt";
                       //use default encoding
                      output = new OutputStreamWriter( new FileOutputStream( textFile ) );
                    PDFTextStripper stripper = null;
                    stripper = new PDFTextStripper();
                    stripper.writeText( document, output );
                finally
                    if( output != null )
                        output.close();
                    if( document != null )
                        document.close();
                }//finally
            }//end funcao
     

    All of these libraries are in "Compile-time
    Libraries" option in Project Properties. Should I add
    they to "Run-time Libraries" option?Yes

  • ActionListener Problem - Event not triggering properly

    Hello,
    I have slight problem ith action listeners. Below is an exercise from a book on java i'm reading. I have constructed rectangle with 3 circles inside.
    When the button in one panel is pushed the colors of these cicles should change from green,black,black to black,yellow,black to black,black,red and start over.
    When the button is clicked the event isn't triggered. However when I push the button and click the frame of the window the colors change.
    I would be grateful if anyone could explain why this is happening?
    // Zepang
    import javax.swing.*;
    import java.awt.*;
    public class Pp415
         public static void main(String [] args)
              JFrame frame = new JFrame("Traffic Lights");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              Prime panel = new Prime();
              frame.getContentPane().add(panel);
              frame.pack();
              frame.setVisible(true);
         JButton lightButton = new JButton("Change the Lights!");
         lightButton.addActionListener(this);
         buttonLight.add(lightButton);
            add(buttonLight);
         add(light);
         int color = 0;
         public void actionPerformed (ActionEvent event)
              Color g = light.getGreenLight();
              Color y=  light.getYellowLight();
              Color r=  light.getRedLight();
              if (g.equals(Color.green))
                   light.setGreenLight(Color.black);
                   light.setYellowLight(Color.yellow);
              if (y.equals(Color.yellow))
                   light.setYellowLight(Color.black);
                   light.setRedLight(Color.red);
              if (r.equals(Color.red))
                   light.setRedLight(Color.black);
                   light.setGreenLight(Color.green);
    import javax.swing.*;
    import java.awt.*;
    class TrafficLight extends JPanel
         Color redLight = Color.black;
         Color yellowLight = Color.black;
         Color greenLight = Color.green;
    public TrafficLight()
         setBackground(Color.black);
         setPreferredSize(new Dimension (200,300));
      public void setRedLight(Color c)
         redLight = c;
      public void setYellowLight(Color c)
         yellowLight = c;
      public void setGreenLight(Color c)
         greenLight = c;
      public Color getRedLight()
      return redLight;
      public Color getGreenLight()
      return greenLight;
      public Color getYellowLight()
      return yellowLight;
      public void paintComponent(Graphics page)
         final int C = 25;
         page.setColor(Color.blue);
         page.fillRect(C, C, 100, 250);
         page.setColor(greenLight);
         page.fillOval(C+10,C+5,80,80);
         page.setColor(yellowLight);
         page.fillOval(C+10,C+90,80,80);
         page.setColor(redLight);
         page.fillOval(C+10,C+170,80,80);
    }Edited by: Zepang on Dec 4, 2008 4:24 PM
    Edited by: Zepang on Dec 4, 2008 4:25 PM

    I don't in general do GUI stuff. But I can see for sure that you're never telling the system that it needs to repaint when you change state. That's why it doesn't show up until you cause an external event causing it to repaint itself, such as resizing the frame or dragging another window across the window.

  • Can some one help me with this problem with my frame???

    i have gt a veri strange problem with my program,that is teh graphic changes only when i resize the the frame,if i dun resize,it will remain the same.However what i intended is that when i click on the radio button,it will change immediately to the respective pages.A simple version of my code is below,can someone helpl me solve it??(there is 3 different class)
    import java.awt.event.*;
    import javax.swing.*;
    public class MainPg extends JFrame implements ActionListener{
         private javax.swing.JPanel jContentPane = null;
         private javax.swing.JPanel buttons = null;
         private javax.swing.JRadioButton one = null;
         private javax.swing.JRadioButton two = null;
         private javax.swing.JPanel change = null;
         public MainPg() {
              super();
              initialize();
         private void initialize() {
              this.setSize(300, 200);
              this.setContentPane(getJContentPane());
              this.setName("mainClass");
              this.setVisible(true);
         private javax.swing.JPanel getJContentPane() {
              if (jContentPane == null) {
                   jContentPane = new javax.swing.JPanel();
                   jContentPane.setLayout(new java.awt.BorderLayout());
                   jContentPane.add(getButtons(), java.awt.BorderLayout.WEST);
                   jContentPane.add(getChange(), java.awt.BorderLayout.CENTER);
              return jContentPane;
         private javax.swing.JPanel getButtons() {
              if(buttons == null) {
                   buttons = new javax.swing.JPanel();
                   java.awt.GridLayout layGridLayout1 = new java.awt.GridLayout();
                   layGridLayout1.setRows(2);
                   layGridLayout1.setColumns(1);
                   ButtonGroup group=new ButtonGroup();
                   group.add(getOne());
                   group.add(getTwo());
                   buttons.setLayout(layGridLayout1);
                   buttons.add(getOne(), null);
                   buttons.add(getTwo(), null);
              return buttons;
         private javax.swing.JRadioButton getOne() {
              if(one == null) {
                   one = new javax.swing.JRadioButton();
                   one.setText("One");
                   one.setSelected(true);
                   one.addActionListener(this);
                   one.setActionCommand("one");
              return one;
         private javax.swing.JRadioButton getTwo() {
              if(two == null) {
                   two = new javax.swing.JRadioButton();
                   two.setText("Two");
                   two.addActionListener(this);
                   two.setActionCommand("two");
              return two;
         private javax.swing.JPanel getChange() {
              if(change == null) {
                   change = new javax.swing.JPanel();
              change.add(new One());
              return change;
         public static void main(String[] args){
              new MainPg();
         public void actionPerformed(ActionEvent e) {
              change.removeAll();
              if("one".equals(e.getActionCommand())){
                   change.add(new One());
              else{
                   change.add(new Two());
              change.repaint();
    import javax.swing.*;
    public class One extends JPanel {
         private javax.swing.JPanel jPanel = null;
         private javax.swing.JLabel jLabel = null;
         private javax.swing.JPanel jPanel1 = null;
         private javax.swing.JLabel jLabel1 = null;
         private javax.swing.JLabel jLabel2 = null;
         public One() {
              super();
              initialize();
         * This method initializes this
         * @return void
         private void initialize() {
              this.setLayout(new java.awt.BorderLayout());
              this.add(getJPanel(), java.awt.BorderLayout.NORTH);
              this.add(getJPanel1(), java.awt.BorderLayout.WEST);
              this.setSize(300, 200);
         * This method initializes jPanel
         * @return javax.swing.JPanel
         private javax.swing.JPanel getJPanel() {
              if(jPanel == null) {
                   jPanel = new javax.swing.JPanel();
                   jPanel.add(getJLabel(), null);
              return jPanel;
         * This method initializes jLabel
         * @return javax.swing.JLabel
         private javax.swing.JLabel getJLabel() {
              if(jLabel == null) {
                   jLabel = new javax.swing.JLabel();
                   jLabel.setText("one");
              return jLabel;
         * This method initializes jPanel1
         * @return javax.swing.JPanel
         private javax.swing.JPanel getJPanel1() {
              if(jPanel1 == null) {
                   jPanel1 = new javax.swing.JPanel();
                   java.awt.GridLayout layGridLayout2 = new java.awt.GridLayout();
                   layGridLayout2.setRows(2);
                   layGridLayout2.setColumns(1);
                   jPanel1.setLayout(layGridLayout2);
                   jPanel1.add(getJLabel2(), null);
                   jPanel1.add(getJLabel1(), null);
              return jPanel1;
         * This method initializes jLabel1
         * @return javax.swing.JLabel
         private javax.swing.JLabel getJLabel1() {
              if(jLabel1 == null) {
                   jLabel1 = new javax.swing.JLabel();
                   jLabel1.setText("one");
              return jLabel1;
         * This method initializes jLabel2
         * @return javax.swing.JLabel
         private javax.swing.JLabel getJLabel2() {
              if(jLabel2 == null) {
                   jLabel2 = new javax.swing.JLabel();
                   jLabel2.setText("one");
              return jLabel2;
    import javax.swing.*;
    public class Two extends JPanel {
         private javax.swing.JLabel jLabel = null;
         public Two() {
              super();
              initialize();
         * This method initializes this
         * @return void
         private void initialize() {
              this.setLayout(new java.awt.FlowLayout());
              this.add(getJLabel(), null);
              this.setSize(300, 200);
         * This method initializes jLabel
         * @return javax.swing.JLabel
         private javax.swing.JLabel getJLabel() {
              if(jLabel == null) {
                   jLabel = new javax.swing.JLabel();
                   jLabel.setText("two");
              return jLabel;
    }

    //change.repaint();
    change.revalidate();

  • Puzzle Game and new Game Problem

    Hello Java Programmers,
    Once again I have encountered a problem with my ongoing puzzle game. I have completed it all. Now I want my user to be able to start a new game in after they win. I tried repaint and update method with JFrame but it deosn't reshuffle the buttons. How can I do that. The code geos below.
    [/b]
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import javax.swing.JOptionPane;
    public class PuzzleGame{
       String[] btn_Labels = {"1","2","3","4","5","6","7","8","9",
                            "10","11","12","13","14","15"," "};
       String[] labels = {"1","2","3","4","5","6","7","8","9",
                            "10","11","12","13","14","15"};
       private final int ONE = 1, TWO = 2, THREE = 3, FIVE = 5;
       private boolean WIN_STATE = false; 
       private JButton b[];
       public String clicked_btn_label = "";
       //Constructor method.
       public PuzzleGame(){
          showSplashScreen();
          initGame();
       public static void main(String args[]){
          PuzzleGame game = new PuzzleGame();
       //When a new Game started labels of buttons are shuffled using this method.
       public void shuffleNumbers(){
          String temp = null;   
          for(int j=0; j<16; j++){
          int k = (int)(Math.random()*16);
          temp = btn_Labels[j];
          btn_Labels[j] = btn_Labels[k];
          btn_Labels[k] = temp;           
       //Game initialization method.
       public void initGame(){
          b = new JButton[16];
          JPanel p = new JPanel();
          JFrame frame = new JFrame();
          shuffleNumbers();
          for(int i=0; i<16; i++){
             b[i] = new JButton();
             b.setText(btn_Labels[i]);
    b[i].setActionCommand(""+(i+1));
    for(int i=0; i<16; i++){
    b[i].addActionListener( new ActionListener(){
    public void actionPerformed(ActionEvent e){
    clicked_btn_label =(String)e.getActionCommand();
    doSwapping();
    checkWin();
    p.add(b[i]);
    p.setLayout(new GridLayout(4,4));
    frame.getContentPane().add(p);
    frame.addWindowListener(new WindowAdapter(){
    public void windowClosing(WindowEvent e){
    System.exit(0);
    Dimension dm = Toolkit.getDefaultToolkit().getScreenSize();
    int x = (dm.width - 230)/2;
    int y = (dm.height - 240)/2;
    frame.setBounds(x,y,320,240);
    frame.setSize(340,240);
    frame.setVisible(true);
    //This method swaps the clicked button with the empty button if it doesn't violate rule.
    public void doSwapping(){
    int num = Integer.parseInt(clicked_btn_label);
    String temp;
    if( (num + ONE <= 16) && b[num].getText() == " " && num % 4 != 0){
    temp = b[num].getText();
    b[num].setText(b[num-ONE].getText());
    b[num-ONE].setText(temp);
    else if((num - TWO >= 0) && b[num-TWO].getText() == " " && ((num - ONE) % 4 != 0)){
    temp = b[num-ONE].getText();
    b[num-ONE].setText(b[num-TWO].getText());
    b[num-TWO].setText(temp);
    else if( (num + THREE < 16) && b[num+THREE].getText() == " "){
    temp = b[num-ONE].getText();
    b[num-ONE].setText(b[num+THREE].getText());
    b[num+THREE].setText(temp);
    else if( (num - FIVE >= 0) && b[num-FIVE].getText() == " "){
    temp = b[num-ONE].getText();
    b[num-ONE].setText(b[num-FIVE].getText());
    b[num-FIVE].setText(temp);
    // else{}
    public void checkWin(){
    WIN_STATE = true;
    for(int i=0; i<15; i++){
    if( b[i].getText() != labels[i])
    WIN_STATE = false;
    if(WIN_STATE == true){
    JOptionPane.showMessageDialog(null,"Congratulations You Have won the Game!","You Win",JOptionPane.INFORMATION_MESSAGE);
         initGame();
    public void showSplashScreen(){
    JWindow w = new JWindow();
    JPanel p = (JPanel)w.getContentPane();
    JLabel l = new JLabel(new ImageIcon("splash.jpg"));
    Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
    int x = (d.width - 230)/2;
    int y = (d.height - 240)/2;
    p.add(l);
    w.setBounds(x,y,320,240);
    w.setVisible(true);
    try{
    Thread.sleep(10000);
    catch(Exception e){
    w.setVisible(false);
    [/b]                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    Sorry for violation. I would like to add a menubar to the application containing a single menu button for new game. adding a menubar is simple but how can i reshuffle the buttons using methods like update etc. or any other way.

  • Game of Life display problem

    The Rules of Game of Life
    For a space that is 'populated':
    Each cell with one or no neighbors dies, as if by loneliness.
    Each cell with four or more neighbors dies, as if by overpopulation.
    Each cell with two or three neighbors survives.
    For a space that is 'empty' or 'unpopulated'
    Each cell with three neighbors becomes populated.
    I have three classes: Cell, BoardComponent, and GameViewer
    I got few problems in my code: 1. the button shows wrongly, 2. without the button, there is always a dot on the upper-left corner, which is not on purpose, 3, after click the mouse to initialize few dots, nothing happened
    How could I fix those problems?
    My Code:
    1. Cell:
    import java.awt.Rectangle;
    public class Cell extends Rectangle{
         public Cell(int x, int y, int side)
              super(x, y, side, side);
    }2. BoardComponent:
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import javax.swing.JComponent;
    import com.sun.jdi.event.Event;
    public class BoardComponent extends JComponent{
         public BoardComponent()
              for(int i = 0; i < ROW; i++)
                   for(int j = 0; j < COL; j++)
                        board[i][j] = new Cell(i*SIDE, j*SIDE, SIDE);
         public void paint(Graphics g)
              Graphics2D g2 = (Graphics2D)g;
              for(int i = 0; i < ROW; i++)
                   for(int j = 0; j < COL; j++)
                        g2.draw(board[i][j]);
         public void initialize(int x, int y)
              Graphics g = getGraphics();
              Graphics2D g2 = (Graphics2D) g;
              if(g2.getColor().equals(Color.BLUE))
                   g2.getBackground();
              else
                   g2.setColor(Color.BLUE);
                   g.fillOval(mouseX, mouseY, 10, 10);
         public void generate()
              int count = 0;
              for(int i = 0; i < ROW-2; i++)
                   for(int j = 0; j < COL-2; j++)
                        for(int m = 0; m < 2; m++)
                             for(int n = 0; n < 2; n++)
                                  if(m!=0 || n !=0)
                                       if(!(board[i+m][j+n].isEmpty()))
                                            count++;
                        if(count == 3 || count < 2 || count > 4)
                             initialize(i*SIDE, j*SIDE);
         private int mouseX, mouseY;
         private boolean mouseclicked = false;
         public static final int ROW = 40;
         public static final int COL = 40;
         private Cell[][] board = new Cell[ROW][COL];
         public static final int SIDE = 14;
    }3. GameViewer:
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.Timer;
    public class GameViewer extends JFrame{
         public static void main(String[] args)
              final BoardComponent game = new BoardComponent();
              class MouseClickListener extends MouseAdapter
                   public void mouseClicked(MouseEvent event)
                        int x = event.getX();
                        int y = event.getY();
                        game.initialize(x, y);
              MouseAdapter listener = new MouseClickListener();
              game.addMouseListener(listener);
              JButton button = new JButton("Start");
             class TimerListener implements ActionListener
                   public void actionPerformed(ActionEvent event)
                        game.generate();
            ActionListener timer = new TimerListener();
            button.setSize(40, 10);
            button.setLocation(250, 500);
            button.addActionListener(timer);
            final int DELAY = 500;
            Timer t = new Timer(DELAY, timer);
            t.start();  
            JFrame window = new JFrame();
            window.setSize(600, 600);
            window.setTitle("Life of Game");
            window.setDefaultCloseOperation(EXIT_ON_CLOSE);
            window.add(game);
            window.add(button);
            window.setVisible(true);
    }Thanks a million.

    As already said, you should override paintComponent(), not paint(), and don't forget to call the superclass's paintComponent() method.
    public void paintComponent(Graphics g)
       super.paintComponent(g);
    }As for this method:
         public void initialize(int x, int y)
              Graphics g = getGraphics();
              Graphics2D g2 = (Graphics2D) g;
              if(g2.getColor().equals(Color.BLUE))
                   g2.getBackground();
              else
                   g2.setColor(Color.BLUE);
                   g.fillOval(mouseX, mouseY, 10, 10);
         }You really shouldn't be doing any painting outside the paintComponent() method.
    Finally, your GameViewer class extends JFrame, but yet you are creating another JFrame in the main method. This doesn't make sense.

  • Advance level drawing problem with Jframe and JPanel need optimize sol?

    Dear Experts,
    I m trying to create a GUI for puzzle game following some kind of "game GUI template", but i have problems in that,so i tried to implement that in various ways after looking on internet and discussions about drawing gui in swing, but i have problem with both of these, may be i m doing some silly mistake, which is still out of my consideration. please have a look at these two and recommend me one of them, which is running without problems (flickring and when you enlarge window the board draw copies (tiled) everywhere,
    Note: i don't want to inherit jpanel or Jframe
    here is my code : import java.awt.BorderLayout;
    public class GameMain extends JFrame {
         private static final long serialVersionUID = 1L;
         public int mX, mY;
         int localpoints = 0;
         protected static JTextField[][] squares;
         protected JLabel statusLabel = new JLabel("jugno");
         Label lbl_score = new Label("score");
         Label lbl_scorelocal = new Label("local score");
         protected static TTTService remoteTTTBoard;
         // Define constants for the game
         static final int CANVAS_WIDTH = 800; // width and height of the game screen
         static final int CANVAS_HEIGHT = 600;
         static final int UPDATE_RATE = 4; // number of game update per second
         static State state; // current state of the game
         private int mState;
         // Handle for the custom drawing panel
         private GameCanvas canvas;
         // Constructor to initialize the UI components and game objects
         public GameMain() {
              // Initialize the game objects
              gameInit();
              // UI components
              canvas = new GameCanvas();
              canvas.setPreferredSize(new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT));
              this.setContentPane(canvas);
              this.setDefaultCloseOperation(EXIT_ON_CLOSE);
              this.pack();
              this.setTitle("MY GAME");
              this.setVisible(true);
         public void gameInit() {     
         // Shutdown the game, clean up code that runs only once.
         public void gameShutdown() {
         // To start and re-start the game.
         public void gameStart() {
         private void gameLoop() {
         public void keyPressed(KeyEvent e) {
         public void keyTyped(KeyEvent e) {
         public void gameKeyReleased(KeyEvent e) {
              PuzzleBoard bd = getBoard();
              for (int row = 0; row < 4; ++row) {
                   for (int col = 0; col < 4; ++col) {
                        if (e.getSource() == squares[row][col]) {
                             if (bd.isOpen(col, row)) {
                                  lbl_score.setText("Highest Score = "
                                            + Integer.toString(bd.getPoints()));
                                  setStatus1(bd);
                                  pickSquare1(col, row, squares[row][col].getText()
                                            .charAt(0));
         protected void pickSquare1(int col, int row, char c) {
              try {
                   remoteTTTBoard.pick(col, row, c);
              } catch (RemoteException e) {
                   System.out.println("Exception: " + e.getMessage());
                   e.printStackTrace();
                   System.exit(1);
         // method "called" by remote object to update the state of the game
         public void updateBoard(PuzzleBoard new_board) throws RemoteException {
              String s1;
              for (int row = 0; row < 4; ++row) {
                   for (int col = 0; col < 4; ++col) {
                        squares[row][col].setText(new_board.ownerStr(col, row));
              lbl_score.setText("Highest Score = "
                        + Integer.toString(new_board.getPoints()));
              setStatus1(new_board);
         protected void setStatus1(PuzzleBoard bd) {
              boolean locals = bd.getHave_winner();
              System.out.println("local win" + locals);
              if (locals == true) {
                   localpoints++;
                   System.out.println("in condition " + locals);
                   lbl_scorelocal.setText("Your Score = " + localpoints);
              lbl_score
                        .setText("Highest Score = " + Integer.toString(bd.getPoints()));
         protected PuzzleBoard getBoard() {
              PuzzleBoard res = null;
              try {
                   res = remoteTTTBoard.getState();
              } catch (RemoteException e) {
                   System.out.println("Exception: " + e.getMessage());
                   e.printStackTrace();
                   System.exit(1);
              return res;
         /** Custom drawing panel (designed as an inner class). */
         class GameCanvas extends JPanel implements KeyListener {
              /** Custom drawing codes */
              @Override
              public void paintComponent(Graphics g) {
                   // setOpaque(false);
                   super.paintComponent(g);
                   // main box; everything placed in this
                   // JPanel box = new JPanel();
                   setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
                   // add(statusLabel, BorderLayout.NORTH);
                   // set up the x's and o's
                   JPanel xs_and_os = new JPanel();
                   xs_and_os.setLayout(new GridLayout(5, 5, 0, 0));
                   squares = new JTextField[5][5];
                   for (int row = 0; row < 5; ++row) {
                        for (int col = 0; col < 5; ++col) {
                             squares[row][col] = new JTextField(1);
                             squares[row][col].addKeyListener(this);
                             if ((row == 0 && col == 1) || (row == 2 && col == 3)
                             || (row == 1 && col == 4) || (row == 4 && col == 4)
                                       || (row == 4 && col == 0))
                                  JPanel p = new JPanel(new BorderLayout());
                                  JLabel label;
                                  if (row == 0 && col == 1) {
                                       label = new JLabel("1");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else if (row == 4 && col == 0) {// for two numbers or
                                       // two
                                       // blank box in on row
                                       label = new JLabel("2");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else if (row == 1 && col == 4) {
                                       label = new JLabel("3");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else if (row == 4) {
                                       label = new JLabel("4");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else {
                                       label = new JLabel("5");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  label.setOpaque(true);
                                  label.setBackground(squares[row][col].getBackground());
                                  label.setPreferredSize(new Dimension(label
                                            .getPreferredSize().width, squares[row][col]
                                            .getPreferredSize().height));
                                  p.setBorder(squares[row][col].getBorder());
                                  squares[row][col].setBorder(null);
                                  p.add(label, BorderLayout.WEST);
                                  p.add(squares[row][col], BorderLayout.CENTER);
                                  xs_and_os.add(p);
                             } else if ((row == 2 && col == 1) || (row == 1 && col == 2)
                                       || (row == 3 && col == 3) || (row == 0 && col == 3)) {
                                  xs_and_os.add(squares[row][col]);
                                  // board[ row ][ col ].setEditable(false);
                                  // board[ row ][ col ].setText("");
                                  squares[row][col].setBackground(Color.RED);
                                  squares[row][col].addKeyListener(this);
                             } else {
                                  squares[row][col] = new JTextField(1);
                                  // squares[row][col].addActionListener(this);
                                  squares[row][col].addKeyListener(this);
                                  xs_and_os.add(squares[row][col]);
                   this.add(xs_and_os);
                   this.add(statusLabel);
                   this.add(lbl_score);
                   this.add(lbl_scorelocal);
              public void keyPressed(KeyEvent e) {
              public void keyReleased(KeyEvent e) {
                   gameKeyReleased(e);
              public void keyTyped(KeyEvent e) {
         // main
         public static void main(String[] args) {
              SwingUtilities.invokeLater(new Runnable() {
                   @Override
                   public void run() {
                        new GameMain();
      thanks a lot for your time , consideration and efforts.
    jibby
    Edited by: jibbylala on Sep 20, 2010 6:06 PM

    jibbylala wrote:
    thanks for mentioning as i wasn't able to write complete context here.Yep thanks camickr. I think that Darryl's succinct reply applies here as well.

  • JInternalFrame drawing problem.

    Hi gurus
    Please could you help with a java problem that I cant find an answer to over the net:
    I have a JDesktop which contains multiple JInternalFrames. On one JInternalFrame i have attached a JPanel on which to draw on. I have multiple threads (simple ball shapes) that need to be drawn onto the JPanel and have left it up to the indivual threads to draw themselves (as opposed to using paintComponent in the JPanel class). The drawing on the JInternalFrame works perfectly fine.
    The problem arises when the other JInternalFrames are placed on top of each other - the balls are drawn over the top most JInternalFrame. What am i doing wrong? I have attached snippets of the code:
    public class Desktop extends JFrame implements ActionListener
              public Desktop()
                        setTitle("Agent's world");
                        setSize(w,h);
                        setDefaultCloseOperation(EXIT_ON_CLOSE);
                        JDesktopPane desktop = new JDesktopPane();
                        setContentPane(desktop);
                        /************* Agent *************/
                        JInternalFrame agents = new JInternalFrame("Agents War", true, false, true, false);                    
                        agents.reshape(0,0,(int)((w/3)*2),h);
                        Container contentPane = agents.getContentPane();
                        canvas = new AgentPanel(agents);
                        contentPane.add(canvas);
                        /************* Button *************/
                        JPanel buttonPanel = new JPanel();
                        ButtonGroup buttonGroup = new ButtonGroup();
                        JButton start = new JButton("START");
                        start.addActionListener(this);
                        buttonPanel.add(start);
                        contentPane.add(buttonPanel, "North");
                        agents.setVisible(true);
                        desktop.add(agents);
                        //sets focus to other frames within the desktop
                        try
                                  agents.setSelected(true);
                        catch(PropertyVetoException e)
                                  //attempt to refocus was vetoed by a frame
              /** Method to listen for event actions, i.e. button clicks **/
         public void actionPerformed(ActionEvent event)
                   //passes through 'this' to allow access to the getList method
                   Agents agent = new Agents(canvas, this);
                   agent.start();
    public class Agents extends Thread
              public Agents(AgentPanel panel, Desktop desktop)
                        panel =_panel;
                        desktop = _desktop;
                        setDaemon(true);
    /** Moves the agent from a spefic position to a new position **/
              public void move()
                        Graphics g = panel.getGraphics();
                        Graphics2D g2 = (Graphics2D)g;
                        try
                                  //set XOR mode
                                  g.setXORMode(panel.getBackground());
                                  //draw over old
                                  Ellipse2D.Double ballOld = new Ellipse2D.Double(i , j, length, length);
                                  g2.fill(ballOld);     
                                  i++;
                                  j++;
                                  if(flag == true)
                                            //draw new
                                            Ellipse2D.Double ballNew = new Ellipse2D.Double(i , j, length, length);
                                            g2.fill(ballNew);
                                            g2.setPaintMode();
                        finally
                                  g.dispose();
              /** Activates the Thread **/
              public void run()
                   int i = 0;
                   while(!interrupted() && i<100)
                        try
                                       for(i = 0 ; i <100 ; i++)
                                                 //draw ball in old position                                             move();          
                                                 sleep(100);                              
                             catch(InterruptedException e)
    public class AgentPanel extends JPanel
              /** local copy of internal frame */
              private JInternalFrame frame;
              public AgentPanel(JInternalFrame _frame)
                        frame = _frame;
                        setSize(frame.getWidth(), frame.getHeight());
                        setBackground(Color.white);          
              public void paintComponent(Graphics g)
                        super.paintComponent(g);
    Thank you in advance.
    Ravs

    I have the same problem. Seems to be a bug. See:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=231037
    Bummer.

Maybe you are looking for

  • Disk space and memory

    Hi. I'm interested to know where to find information about the SAP system size, both occupied and accessible size. And of course how much memory there are in the system. Please, give me some t-codes I can use. BR  //  Peter B

  • How to allow use of special characters in a particular version/Hierarchy

    How do I allow use of special character in nodename description in a particular hierarchy. If I enable InvNameSystem Preference it allows me for all hierarchies and versions,but I want to restrict it for particular version and hierarchy.

  • What are the specs for the personal pictures for the startup me

    I know it's 60-04, but I'm referring to index color, gray-scale, bit depth etc? I keep trying to get a picture in and it just shows up garbled. Any suggestions. I have the Zen Jukebox 40 GB. Will this version even do the picture thing. Any help is ap

  • Picture taking and videos vs. a digital camera?

    I mananged to break my Sony 3.2 Megapixel Cybershot camera. I have been pleased with it, picture abilities, short video ability. Anyway, it may not be worth fixing. How does the iPhones photo and video taking ability to compare to a digital camera li

  • Hotmail doesn't open and says 'server not found' but all other websites work fine...

    My macbook won't open hotmail. It works on all other websites apart from hotmail. I have tried using safari to open it but it still didn't work. It comes up with the message 'Server not Found'. I have tried another computer in the house and it worked