Overriding paintcomponent method JButton

Hi,
I'm trying to make my own buttons (with a JPEG image as template and a string painted on this template, depending on which button it is) by overriding the paintComponent-method of the JButton class, but I still have a small problem. I want to add some mouse-events like rollover and click and the appropriate animation with it (when going over the button, the color of the button becomes lighter, when clicking, the button is painted 2 pixels to the left and to the bottom). But my problem is there is some delay on these actions, if you move the mousepointer fast enough, the pointer can already be on another button before the previous button is restored to its original state. And of course, this isn't what I want to see.
I know you can use methods like setRollOverIcon(...), but if doing so, I think you need a lot of images ( for each different button at least 3) and I want to keep the number of images to a minimum.
I searched the internet and these forums for a solution, but I didn't found any. I'm quite sure there is at least one good tutorial on this since I already tried to do this once, but I forgot how to do it, and I can't find the tutorial anymore.
This is an example of the MyButton-class I already wrote, I hope it clarifies my problem:
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;
public class MyButton extends JButton{
     BufferedImage button = null;
     int x, y;
     String text = "";
     MyButton(String t){
          super(t);
          text = t;
          setContentAreaFilled(false);
          setBorderPainted(false);
          setFocusPainted(false);
          addMouseListener(new MouseListener(){
               public void mouseClicked(MouseEvent arg0) {
                    x += 2;
                    y += 2;
               public void mouseEntered(MouseEvent arg0) {
                    //turn lighter
               public void mouseExited(MouseEvent arg0) {
                    x -= 2;
                    y -= 2;
               public void mousePressed(MouseEvent arg0) {}
               public void mouseReleased(MouseEvent arg0) {}
     protected void paintComponent(Graphics g){
          Graphics2D g2d = (Graphics2D)g;
          try{
               button = ImageIO.read(new File("Red_Button.jpg"));
          }catch(IOException ioe){}
          //Drawing JButton
          g2d.drawImage(button, null, x, y);
          g2d.drawString(text, x+5, y+5);     
}Thanks in advance,
Sam

Okay, thanks, I replaced the image-read-in into the constructor of a JButton, and I think it goes a lot faster now (but that can be my imagination).
I still use a mouseListener because I have no idea how to use the ButtonModelinterface. I searched to find a good tutorial, but I didn't really find one? Any recommendations (yes, I read the sun-tutorial, but did not find it really explanatory).
Here's a complete SSCCE (although it isn't really necessary anymore since my main problem seams to be solved):
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;
public class MyButton extends JButton{
     BufferedImage button = null;
     int x, y;
     String text = "";
     public MyButton(String t){
          super(t);
          text = t;
          try{
               button = ImageIO.read(new File("Blue_Button.jpg"));
          }catch(IOException ioe){}
          setBorderPainted(false);
          addMouseListener(new MouseListener(){
               public void mouseClicked(MouseEvent arg0) {}
               public void mouseEntered(MouseEvent arg0) {
                    x += 2;
                    y += 2;
               public void mouseExited(MouseEvent arg0) {
                    x -= 2;
                    y -= 2;
               public void mousePressed(MouseEvent arg0) {}
               public void mouseReleased(MouseEvent arg0) {}
     protected void paintComponent(Graphics g){
          Graphics2D g2d = (Graphics2D)g;
          g2d.drawImage(button, null, x, y);
          g2d.drawString(text, x+25, y+15);     
     public void fireGUI(){
          JFrame frame = new JFrame("ButtonModelTester");
          frame.setLayout(new GridLayout(2,1,10,10));
          frame.add(new MyButton("Test1"));
          frame.add(new MyButton("Test2"));
          frame.setSize(200,100);
          frame.setVisible(true);
     public static void main(String[] args){
          SwingUtilities.invokeLater(new Runnable(){
               public void run(){
                    new MyButton(null).fireGUI();
}Thanks,
Sam
PS: you mentioned my earlier posts? So they are still somewhere on this forum, because I couldn't find the anymore, they aren't in my watch list. I Checked this since I thought I asked something similar before...

Similar Messages

  • Override scrollpane methods?

    problem: I create a time series line graph in a buffered image that has a variable width, sometimes the width is in the millions of pixels and the resulting buffered image is too large to fit into memory, even if I increase the available memory with the -Xmx1024m option. I then place the a fore mentioned buffered image into a scrollpane for viewing.
    I would like to draw only the portion of the graph that is viewable and override the scrollpane methods to redraw the image based on an x position over the total width, but I haven't found anything in the API on overriding the scrollbar or the arrow buttons. Has anyone tried this, or seen and example of how to do it?
    I am aware of products such as JFreeChart and PtolemyPlot, however I don't think either is a good fit for the project and I don't have any use for their capabilities. I am open to any other suggestions on how to accomplish this goal.
    Thanks,
    Peter

    You can try to use JScrollPane by placing a custom component extending JComponent inside the scroll pane and setting it's preferred size to the required size.
    Override paintComponent method of this component and get the view rectangle from the viewport and paint only the visible area.
    If this doesn't work you might need to use JScrollBar and write the logic yourself in this case.

  • Is not abstract and does not override abstract method actionPerformed

    I dont how to corr. Please help!! and thank you very much!!
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class test extends JFrame implements ActionListener, ItemListener
              private CenterPanel centerPanel;
              private QuestionPanel questionPanel;
              private ButtonPanel buttonPanel;
              private ResponsePanel responsePanel;
              private JButton b1,b2,b3,b4,b5;               //Create five references to Jbutton instances
         private JTextField t1,t2,t3,t4,t5;          //Create five references to JTextField instances
              private JLabel label1;                    //Create one references to JLabel instances
              private JRadioButton q1,q2,q3;               //Create three references to JRadioButton instances
              private ButtonGroup radioGroup;               //Create one references to Button Group instances
              private int que1[] = new int[5];           //Create int[4] Array
              private int que2[] = new int[5];
              private int que3[] = new int[5];
              private String temp1, temp2, temp3, temp4, temp5, temp6, temp7, temp8, temp9, temp10,
                        temp11, temp12, temp13, temp14, temp15;
    public test (String header)
              super(header);
              Container container = getContentPane();
              label1 = new JLabel ("PLease click on your response to ");     
              q1 = new JRadioButton("I understand most of the content of this subject",true);
              add(q1);
              q2 = new JRadioButton("I see the relevance of the subject to my degree",false);
              add(q2);
              q3 = new JRadioButton("The workload in this subject is appropriate",false);
              add(q3);
              radioGroup = new ButtonGroup();               //JRadioButton belong to ButtonGroup
              radioGroup.add(q1);
              radioGroup.add(q2);
              radioGroup.add(q3);
              JPanel buttonPanel = new JPanel();
              JPanel responsePanel = new JPanel();
              JPanel questionPanel = new JPanel();
              JPanel centerPanel = new JPanel();
              b1 = new JButton ("Strongly DISAGREE");          //Instantiate JButton with text
              b1.addActionListener (this);               //Register JButtons to receive events
              b2 = new JButton ("DISAGREE");
              b2.addActionListener (this);
              b3 = new JButton ("Neither AGREE or DISAGREE");
              b3.addActionListener (this);
              b4 = new JButton ("AGREE");
              b4.addActionListener (this);
              b5 = new JButton ("Strongly AGREE");
              b5.addActionListener (this);
              buttonPanel.setLayout(new GridLayout(5,1));
              buttonPanel.add(b1);
              buttonPanel.add(b2);
              buttonPanel.add(b3);
              buttonPanel.add(b4);
              buttonPanel.add(b5);
              t1 = new JTextField ("0",3);               //JTextField contains empty string
              t2 = new JTextField ("0",3);
              t3 = new JTextField ("0",3);
              t4 = new JTextField ("0",3);
              t5 = new JTextField ("0",3);
              t1.setEditable( false );
              t2.setEditable( false );
              t3.setEditable( false );
              t4.setEditable( false );
              t5.setEditable( false );
              responsePanel.setLayout(new GridLayout(5,1));
              responsePanel.add(t1);
              responsePanel.add(t2);
              responsePanel.add(t3);
              responsePanel.add(t4);
              responsePanel.add(t5);
              questionPanel.setLayout(new GridLayout(4,1));
              questionPanel.add(label1);
              questionPanel.add(q1);
              questionPanel.add(q2);
              questionPanel.add(q3);
              centerPanel.add(buttonPanel,BorderLayout.CENTER);
              centerPanel.add(responsePanel,BorderLayout.EAST);
              container.add(centerPanel,BorderLayout.WEST);
              container.add(questionPanel,BorderLayout.NORTH);
              q1.addActionListener(
                   new ActionListener(){
              public void actionPerformed( ActionEvent e )          
    {                                        //actionPerformed of all registered listeners
              if (e.getSource() == b1) {
                   que1[0] = Integer.parseInt(t1.getText()) + 1;
                   String temp1 = String.valueOf(que1[0]);
              t1.setText(temp1);
              else if (e.getSource() == b2)     {
                   que1[1] = Integer.parseInt(t2.getText()) + 1;
                   String temp2 = String.valueOf(que1[1]);
              t2.setText(temp2);
              else if (e.getSource() == b3)     {
                   que1[2] = Integer.parseInt(t3.getText()) + 1;
                   String temp3 = String.valueOf(que1[2]);
              t3.setText(temp3);
              else if (e.getSource() == b4)     {
                   que1[3] = Integer.parseInt(t4.getText()) + 1;
                   String temp4 = String.valueOf(que1[3]);
              t4.setText(temp4);
              else if (e.getSource() == b5)     {
                   que1[4] = Integer.parseInt(t5.getText()) + 1;
                   String temp5 = String.valueOf(que1[4]);
              t5.setText(temp5);
    } //end action performed
              q2.addActionListener(
                   new ActionListener(){
              public void actionPerformed( ActionEvent e )          
    {                                        //actionPerformed of all registered listeners
              if (e.getSource() == b1) {
                   que2[0] = Integer.parseInt(t1.getText()) + 1;
                   String temp6 = String.valueOf(que2[0]);
              t1.setText(temp1);
              else if (e.getSource() == b2)     {
                   que2[1] = Integer.parseInt(t2.getText()) + 1;
                   String temp7 = String.valueOf(que2[1]);
              t2.setText(temp7);
              else if (e.getSource() == b3)     {
                   que2[2] = Integer.parseInt(t3.getText()) + 1;
                   String temp8 = String.valueOf(que2[2]);
              t3.setText(temp8);
              else if (e.getSource() == b4)     {
                   que2[3] = Integer.parseInt(t4.getText()) + 1;
                   String temp9 = String.valueOf(que2[3]);
              t4.setText(temp9);
              else if (e.getSource() == b5)     {
                   que2[4] = Integer.parseInt(t5.getText()) + 1;
                   String temp10 = String.valueOf(que2[4]);
              t5.setText(temp10);
    } //end action performed
              q3.addActionListener(
                   new ActionListener(){
              public void actionPerformed( ActionEvent e )          
    {                                        //actionPerformed of all registered listeners
              if (e.getSource() == b1) {
                   que3[0] = Integer.parseInt(t1.getText()) + 1;
                   String temp11 = String.valueOf(que3[0]);
              t1.setText(temp11);
              else if (e.getSource() == b2)     {
                   que3[1] = Integer.parseInt(t2.getText()) + 1;
                   String temp12 = String.valueOf(que3[1]);
              t2.setText(temp12);
              else if (e.getSource() == b3)     {
                   que3[2] = Integer.parseInt(t3.getText()) + 1;
                   String temp13 = String.valueOf(que3[2]);
              t3.setText(temp13);
              else if (e.getSource() == b4)     {
                   que3[3] = Integer.parseInt(t4.getText()) + 1;
                   String temp14 = String.valueOf(que3[3]);
              t4.setText(temp14);
              else if (e.getSource() == b5)     {
                   que3[4] = Integer.parseInt(t5.getText()) + 1;
                   String temp15 = String.valueOf(que3[4]);
              t5.setText(temp15);
    } //end action performed
    }//end constructor test
    public void itemStateChanged(ItemEvent item) {
    //int state = item.getStateChange();
    //if (q1 == item.SELECTED)
              public class ButtonPanel extends JPanel
                   public ButtonPanel()
              public class CenterPanel extends JPanel
                   public CenterPanel()
              public class QuestionPanel extends JPanel
                   public QuestionPanel()
              public class ResponsePanel extends JPanel
                   public ResponsePanel()
    public static void main(String [] args)
         test surveyFrame = new test("Student Survey") ;
         surveyFrame.setSize( 500,300 );
         surveyFrame.setVisible(true);
         surveyFrame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
         }//end main
    }//end class test

    is not abstract and does not override abstract method actionPerformed
    Oh, I see that the title of your post is an error message? Ok. Well, the test class is declared as implementing an ActionListener. That means the test class must have an actionPerformed() method. Your test class apparently does not.
    It does not appear that the test class needs to implement ActionListener. You are using annonymous classes as listeners.

  • PaintComponent method refuses to be invoked.

    Hello All!
    I have a problem with graphics representation by swing. Namely I have an application based on Jframe object. It includes three Jpanel components. I need to map information from Jtable as diagram in the plotPanel. That�s code fragment I try to use:
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.JComponent.*;
    import java.lang.*;
    import java.io.*;
    * @author  Administrator
    public class ROC extends javax.swing.JFrame{
    public ROC() {
            initComponents();
    /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        private void initComponents() {
            menuPanel = new javax.swing.JPanel();
            openButton = new javax.swing.JButton();
            tablePanel = new javax.swing.JPanel();
            pointsTable = new javax.swing.JTable();
            generateButton = new javax.swing.JButton();
            plotPanel = new javax.swing.JPanel();
            plotPanel.add(new PlotArea(), java.awt.BorderLayout.CENTER);
    ������ //This is a piece of code to initialize other components
            plotPanel.setLayout(new java.awt.BorderLayout());
            plotPanel.setBackground(java.awt.Color.white);
            plotPanel.setPreferredSize(new java.awt.Dimension(600, 380));
            plotPanel.setDebugGraphicsOptions(javax.swing.DebugGraphics.NONE_OPTION);
            plotPanel.addContainerListener(new java.awt.event.ContainerAdapter() {
                public void componentAdded(java.awt.event.ContainerEvent evt) {
                    plotPanelComponentAdded(evt);
            getContentPane().add(plotPanel, java.awt.BorderLayout.CENTER);
            pack();
    ������  // Different functions (such as loading data from the file to JTable i.e.)
           public static void main(String args[]) {
            System.out.println("Application starts");
            new ROC().show();
        // Variables declaration - do not modify
        private javax.swing.JPanel menuPanel;
        private javax.swing.JButton openButton;
        private javax.swing.JPanel tablePanel;
        private javax.swing.JTable pointsTable;
        private javax.swing.JButton generateButton;
        private javax.swing.JPanel plotPanel;
        // End of variables declaration
    public class PlotArea extends javax.swing.JComponent{
        /** Creates new plotPanel */
        public PlotArea() {
            System.out.println("PlotArea has been created");
            setPreferredSize(new java.awt.Dimension(600, 380));
            setMinimumSize(new java.awt.Dimension(200, 100));
            super.setBorder(BorderFactory.createLineBorder(Color.red, 5));
            repaint();
        public void paintComponent(java.awt.Graphics g) {
            System.out.println("PaintComponent method has been invoked");
            Graphics2D g2d = (Graphics2D)g;
    ������ // this is the code to implement custom painting
    }The trouble is that PaintComponent method hasn�t been invoked. Help me please. What should I do to cause PaintComponent to be performed?

    You might want to ensure your "plotPanel" uses a BorderLayout if you're specifying a constraint:
    plotPanel = new javax.swing.JPanel(new BorderLayout());
    plotPanel.add(new PlotArea(), java.awt.BorderLayout.CENTER);You shouldn't need to call "repaint" in the constructor of PlotArea, either. I doubt it'll make any difference.
    Hope this helps.

  • PaintComponent Method

    Hello,
    can any one tell me when paintComponent(Graphics gc){} method will be called???
    it's needed that i have to extends JPanel.
    in my prog m extending theJApplet class.
    can paintComponent(Graphics gc){} will called if m extending the JApplet..
    plz tell me..
    waiting 4 yr reply.
    Regards,
    Shruti.

    Swing related questions should be posted in the Swing forum.
    You override paintComponent of JPanel and add the panel to your JApplet. The paintComponent() method will be called as required.

  • PaintComponent method problems...

    Hi, I am developing an game application ( just for fun ) and I have a huge problem with paintComponent method. I Have a class ImagePanel that extends JPanel class. The ImagePanel class overrides the paintComponent method and paintChildren method ( since i have added components inside the JPanel also these must be painted ). The ImagePanel is instantied in my main class IntroView which extends JFrame where it's added. Now when the IntroPanel is created i have noticed that the paintComponent and paintChildren method is called all over again . I Have a soundclip playing in background in it's own thread and this continously paintComponent method call causes the sound clip to break off in few seconds. I Have tried to use JLabel instead of JPanel, but then the image is not shown( alltougth the methods are called only once ). I Have also tried next code to get rid of continous paintComponent call
    ...from ImagePanel class
    ImagePanel extends JPanel.....
    public final void paintComponent( Graphics g )
    if( firstTime )
    super.paintComponent( g );
    g.drawImage( myImage, 0, 0, this );
    firstTime = false;
    public final void paintChildrens( Graphics g )
    if( paintChildren )
    super.paintChildren( g );
    add( startLabel );
    add( optionsLabel );
    paintChildren = false;
    public boolean isOpaque()
    return true;
    Now the paintComponent and paintChildren is called only once. There is still a "little problem" since the paintComponent doesen't paint the image, it paints only the background( I think g.drawImage(...) didint have time to paint the image? ). Also the labels added in paintChildren method are not shown. Sounds paly now just fine.This situation makes me grazy. Please consult me with this problem.....i can surely send also the whole source if needed. There is no effect if I change isOpaque to true or false.

    Hi,
    Thanks for advices, I solved the problem...it was simplier than i thought. When the g.drawImage(.... is called ) i just added Thread.sleep( time ) after that line. This gives the sound therad time to play the sound without interrput and time to main thread to handle the image. All works now pretty much as i thought, except when JFrame is overlapped the image is not drawn again...this can be corrected ( maybe?)by adding windoslistener and implement the methods in that inteface and make some repainting in different situations. But cause you gave me the magic work Thread priority I hox! the problem, so here goes 10 duke dollars.

  • PaintComponent method seems not to be called - im stumped

    Please find two simple classes:
    When debugging why my background image wont display I have discovered that the paintComponent() method of my BackgroundJPanel class never gets invoked. Its part of the heirarchy so im not sure why.. You will notice a few system.out's the only thing my console shows is a "zooob!" comment..
    package xrpg.client;
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.awt.Dimension;
    import java.awt.Toolkit;
    import javax.swing.*;  
    import javax.swing.ImageIcon;
    import javax.swing.JLayeredPane;
    import java.awt.Frame;
    import java.awt.Color;
    import jka.swingx.*;
    public class XClient {
          * @param args
         public static void main(String[] args)
              XClient app = new XClient();
         public XClient()
              //set look and feel
              try { UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName()); }
              catch (Exception e) { }
              //     Create the top-level container
              JFrame frame = new JFrame("XClient");
              frame.setUndecorated(true);
              frame.setBackground(Color.black);  
              // create background panel and add it to frame
              BackgroundJPanel bPanel = new BackgroundJPanel("xrpg/client/content/xrpg00002.jpg");
              bPanel.setBackground(Color.white);  
              frame.getContentPane().add(bPanel, java.awt.BorderLayout.CENTER);
              //JButton button = new JButton("I'm a Swing button!");
              //bPanel.add(button);
              //button.setLocation(10,10);
              frame.addWindowListener(new WindowAdapter(){
               public void windowClosing(WindowEvent e)
                    System.exit(0);
          // show & size frame
              frame.pack();
          frame.setVisible(true);
          Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
              frame.setSize(dim);
    package jka.swingx;
    import javax.swing.*;
    import java.awt.*;
    public class BackgroundJPanel extends JPanel {
              private Image img ;
              private boolean draw = true;
              public BackgroundJPanel(String imageResource)
                   System.out.println( "zooob!" );
                   // load & validate image
                   ClassLoader cl = this.getClass().getClassLoader();
                   try { img = new ImageIcon(cl.getResource(imageResource)).getImage(); } catch(Exception e){}
                   if( img == null ) {
                        System.out.println( "Image is null" );
                        draw=false;
                   if( img.getHeight(this) <= 0 || img.getWidth( this ) <= 0 ) {
                        System.out.println( "Image width or height must be +ve" );
                        draw=false;
                   setLayout( new BorderLayout() ) ;
              public void drawBackground( Graphics g ) {
                   System.out.println( "zeeeb!" );
                   int w = getWidth() ;
                   int h = getHeight() ;
                   int iw = img.getWidth( this ) ;
                   int ih = img.getHeight( this ) ;
                   for( int i = 0 ; i < w ; i+=iw ) {
                        for( int j = 0 ; j < h ; j+= ih ) {
                             g.drawImage( img , i , j , this ) ;
              protected void paintComponent(Graphics g) {
                   System.out.println( "zeeeha!" );
                   super.paintComponent(g);
                   if (draw) drawBackground( g ) ;
    }

    why my "original post with two class" example is not calling the paintComponent() A couple of things have conspired to prevent the invocation of the paintComponent() method.
    The preferredSize of your panel is (0, 0). Therefore, the size of all the components added to the frame is (0, 0). when the frame is made visible. It also appears than when you reset the size of the frame there is no need to repaint the panel since its size is (0, 0);
    Simple solution is to change the order of your code to be:
    frame.setSize(dim);
    frame.setVisible(true);A couple of notes:
    a) to maximize the frame, rather than setting the size manually it is better to use:
    frame.setExtendedState (JFrame.MAXIMIZED_BOTH);
    b) instead of using a window listener to close the frame it is easier to use:
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

  • Overriding paintComponent ?

    Hello,
    I'm working with some JScrollBars, but I want to give them a more unique look, because it's for use in a game. But I'm not sure how to repaint them. should I override the paintComponent method, and how will I know all the dimensions of al the parts of the scrollbar? Does anyone have any ideas about this ?
    thanks in advance,
    Rabon

    Hi,
    It would be better if you subclassed the UI class (BasicScrollBarUI) and wrote your own paintTrack() and paintThumb() methods. If you want them to be different sizes from the standard values, override getTrackBounds() and getThumbBounds() as well.
    Hope that helped,
    Ian

  • Is not abstract and does not override abstract method tablechanged

    I will remove all the gui code to make it shorter, but my problem lies with my InteractiveTableModelListener.
    public class Meet extends JPanel{
      private static void createAndShowGUI() {
            JFrame frame = new JFrame("MEET_dataTable");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(new Meet(), BorderLayout.CENTER);
            frame.pack();
            frame.setVisible(true);
    public class InteractiveTableModelListener implements TableModelListener {
         public void TableChanged(TableModelEvent evt) {
      if (evt.getType() == TableModelEvent.UPDATE) {
          int column = evt.getColumn();
          int row = evt.getFirstRow();
          dataTable.setColumnSelectionInterval(column + 1, column + 1);
          dataTable.setRowSelectionInterval(row, row);
    class InteractiveRenderer extends DefaultTableCellRenderer {
      protected int interactiveColumn;
      public InteractiveRenderer(int interactiveColumn) {
          this.interactiveColumn = interactiveColumn;
    public Component getTableCellRendererComponent(JTable dataTable,
         Object value, boolean isSelected, boolean hasFocus, int row,
         int column)
      Component c = super.getTableCellRendererComponent(dataTable, value, isSelected, hasFocus, row, column);
       if (column == interactiveColumn && hasFocus) {
         if ((Meet.this.tableModel.getRowCount() - 1) == row &&
            !Meet.this.tableModel.hasEmptyRow())
             Meet.this.tableModel.addEmptyRow();
        highlightLastRow(row);
      return c;
    public void highlightLastRow(int row) {
         int lastrow = tableModel.getRowCount();
      if (row == lastrow - 1) {
          dataTable.setRowSelectionInterval(lastrow - 1, lastrow - 1);
      else {
          dataTable.setRowSelectionInterval(row + 1, row + 1);
         dataTable.setColumnSelectionInterval(0, 0);
    public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                UIManager.put("swing.boldMetal", Boolean.FALSE);
                createAndShowGUI();
    }As i say, i have removed all the gui code to make it shorter, but in this code i create the table and add all the model to it. I am being returned with the error
    Meet.InteractiveTableModelListener is not abstract and does not override abstract method tableChanged(javax.swing.event.TableModelEvent)in javax.swing.event.TableModelListener
    what would be causing this error?
    Cheers

    Sorry, just figured out my silly error, the method is tableChanged not TableChanged.
    cheers
    TOPIC CLOSED
    Edited by: nick2price on Sep 11, 2008 7:08 AM

  • Is not abstract and does not override abstract method ERROR

    Hello. I'm new at all this, and am attempting to recreate a sample code out of my book (Teach Yourself XML in 24 Hours), and I keep getting an error. I appriciate any help.
    This is the Error that I get:
    DocumentPrinter is not abstract and does not override abstract method skippedEntity(java.lang.String) in org.xml.sax.ContentHandler
    public class DocumentPrinter implements  ContentHandler, ErrorHandler
            ^This is the sourcecode:
    import org.xml.sax.Attributes;
    import org.xml.sax.ContentHandler;
    import org.xml.sax.ErrorHandler;
    import org.xml.sax.Locator;
    import org.xml.sax.SAXParseException;
    import org.xml.sax.XMLReader;
    public class DocumentPrinter implements  ContentHandler, ErrorHandler
    // A Constant containing the name of the SAX parser to use.
    private static final String PARSER_NAME = "org.apache.xerces.parsers.SAXParser";
    public static void main(String[] args)
       // Check to see whether the user supplied any command line arguments.  If not, print an error and exit.
       if (args.length == 0)
         System.out.println("No XML document path specified.");
         System.exit(1);
       // Create a new instance of the DocumentPrinter class.
       DocumentPrinter dp = new DocumentPrinter();
       try
         // Create a new instance of the XML Parser.
         XMLReader parser = (XMLReader)Class.forName(PARSER_NAME).newInstance();
         // Set the parser's content handler
        // parser.setContentHandler(dp);
         // Set the parsers error handler
         parser.setErrorHandler(dp);
         // Parse the file named in the argument
         parser.parse(args[0]);
       catch (Exception ex)
         System.out.println(ex.getMessage());
         ex.printStackTrace();
    public void characters(char[] ch, int start, int length)
       String chars ="";
       for (int i = start; i < start + length; i++)
         chars = chars + ch;
    System.out.println("Recieved characters: " + chars);
    public void startDocument()
    System.out.println("Start Document.");
    public void endDocument()
    System.out.println("End of Document.");
    public void startElement(String namespaceURI, String localName, String qName, Attributes atts)
    System.out.println("Start element: " + localName);
    for (int i = 0; i < atts.getLength(); i++)
    System.out.println(" Attribute: " + atts.getLocalName(i));
    System.out.println(" Value: " + atts.getValue(i));
    public void endElement(String namespaceURI, String localName, String qName)
    System.out.println("End of element: " + localName);
    public void startPrefixMapping(String prefix, String uri)
    System.out.println("Prefix mapping: " + prefix);
    System.out.println("URI: " + uri);
    public void endPrefixMapping(String prefix)
    System.out.println("End of prefix mapping: " + prefix);
    public void ignorableWhitespace(char[] ch, int start, int length)
    System.out.println("Recieved whitespace.");
    public void processingInstruction(String target, String data)
    System.out.println("Recieved processing instruction:");
    System.out.println("Target: " + target);
    System.out.println("Data: " + data);
    public void setDocumentLocation(Locator locator)
    // Nada
    public void error(SAXParseException exception)
    System.out.println("Parsing error on line " + exception.getLineNumber());
    public void fatalError(SAXParseException exception)
    System.out.println("Fatal parsing error on line " + exception.getLineNumber());
    public void warning(SAXParseException exception)
    System.out.println("Warning on line " + exception.getLineNumber());

    Check to make sure that the arguments are consistent with your ContentHandler class. Probably the wrong type.
    I think you forgot to include the skippedEntity method, it seems to be missing. Even if an implemented class has a method that you are not using, you still have to include the method in your code even if it doesn't do anything.
    Message was edited by:
    ChargersTule1

  • ...is not abstract and does not override abstract method compare

    Why am I getting the above compile error when I am very clearly overriding abstract method compare (ditto abstract method compareTo)? Here is my code -- which was presented 1.5 code and I'm trying to retrofit to 1.4 -- followed by the complete compile time error. Thanks in advance for your help (even though I'm sure this is an easy question for you experts):
    import java.util.*;
       This program sorts a set of item by comparing
       their descriptions.
    public class TreeSetTest
       public static void main(String[] args)
          SortedSet parts = new TreeSet();
          parts.add(new Item("Toaster", 1234));
          parts.add(new Item("Widget", 4562));
          parts.add(new Item("Modem", 9912));
          System.out.println(parts);
          SortedSet sortByDescription = new TreeSet(new
             Comparator()
                public int compare(Item a, Item b)   // LINE CAUSING THE ERROR
                   String descrA = a.getDescription();
                   String descrB = b.getDescription();
                   return descrA.compareTo(descrB);
          sortByDescription.addAll(parts);
          System.out.println(sortByDescription);
       An item with a description and a part number.
    class Item implements Comparable     
          Constructs an item.
          @param aDescription the item's description
          @param aPartNumber the item's part number
       public Item(String aDescription, int aPartNumber)
          description = aDescription;
          partNumber = aPartNumber;
          Gets the description of this item.
          @return the description
       public String getDescription()
          return description;
       public String toString()
          return "[descripion=" + description
             + ", partNumber=" + partNumber + "]";
       public boolean equals(Object otherObject)
          if (this == otherObject) return true;
          if (otherObject == null) return false;
          if (getClass() != otherObject.getClass()) return false;
          Item other = (Item) otherObject;
          return description.equals(other.description)
             && partNumber == other.partNumber;
       public int hashCode()
          return 13 * description.hashCode() + 17 * partNumber;
       public int compareTo(Item other)   // OTHER LINE CAUSING THE ERROR
          return partNumber - other.partNumber;
       private String description;
       private int partNumber;
    }Compiler error:
    TreeSetTest.java:25: <anonymous TreeSetTest$1> is not abstract and does not over
    ride abstract method compare(java.lang.Object,java.lang.Object) in java.util.Com
    parator
                public int compare(Item a, Item b)
                           ^
    TreeSetTest.java:41: Item is not abstract and does not override abstract method
    compareTo(java.lang.Object) in java.lang.Comparable
    class Item implements Comparable
    ^
    2 errors

    According to the book I'm reading, if you merely take
    out the generic from the code, it should compile and
    run in v1.4 (assuming, of course, that the class
    exists in 1.4). I don't know what book you are reading but that's certainly incorrect or incomplete at least. I've manually retrofitted code to 1.4, and you'll be inserting casts as well as replacing type references with Object (or the erased type, to be more precise).
    These interfaces do exist in 1.4, and
    without the generics.Exactly. Which means compareTo takes an Object, and you should change your overriding method accordingly.
    But this raises a new question: how does my 1.4
    compiler know anything about generics? It doesn't and it can't. As the compiler is telling you, those interfaces expect Object. Think about it, you want to implement one interface which declares a method argument type of Object, in several classes, each with a different type. Obviously all of those are not valid overrides.

  • Product is not abstract and does not override abstract method

    Received the following errors.
    Product.java:3: Product is not abstract and does not override abstract method ge
    tDisplayText() in Displayable
    public class Product implements Displayable
    ^
    Product.java:16: getDisplayText() in Product cannot implement getDisplayText() i
    n Displayable; attempting to use incompatible return type
    found : void
    required: java.lang.String
    public void getDisplayText()
    ^
    2 errors
    Code reads as follows
    import java.text.NumberFormat;
    public class Product implements Displayable
         private String code;
         private String description;
         private double price;
         public Product()
              this.code = "";
              this.description = "";
              this.price = 0;
    public void getDisplayText()
    String message =
    "Code: " + code + "\n" +
    "Description: " + description + "\n" +
    "Price: " + this.getFormattedPrice() + "\n";
         public Product(String code, String description, double price)
              this.code = code;
              this.description = description;
              this.price = price;
         public void setCode(String code)
              this.code = code;
         public String getCode(){
              return code;
         public void setDescription(String description)
              this.description = description;
         public String getDescription()
              return description;
         public void setPrice(double price)
              this.price = price;
         public double getPrice()
              return price;
         public String getFormattedPrice()
              NumberFormat currency = NumberFormat.getCurrencyInstance();
              return currency.format(price);
    Please help!

    Received the following errors.
    Product.java:3: Product is not abstract and does not
    override abstract method ge
    tDisplayText() in Displayable
    public class Product implements Displayable
    ^
    Product.java:16: getDisplayText() in Product cannot
    implement getDisplayText() i
    n Displayable; attempting to use incompatible return
    type
    found : void
    required: java.lang.String
    public void getDisplayText()
    ^
    2 errors
    Code reads as follows
    Please use the code tags when posting code. There is a code button right above the text box where you enter your post. Click on it and put the code between the code tags.
    These error messages are quite clear in telling what is wrong. You have an Interface called Displayable that specifies a method something like thispublic String getDisplayText() {But in your Product source code, you created thismethodpublic void getDisplayText() {The compiler is complaining because the methods are not the same.
    You also need to return a String in the method probalby like thisreturn message;

  • Overriding a method in abap

    In Java it is simple to extend a class and override a method - the whole idea of polymorphism. In abap, I'm attempting to do the same, but don't know quite how. I've created as a demo a zclass and made a sap standard class its superclass in properties. How do I override a protected method from here?

    Marcin says:
    Unfortunatelly overriding is not possible in ABAP, only redefinition is allowed. The method singature must stay the same in all subsequent classes.
    I guess,
    Overriding - Redefinition of the implementation of inherited method. This is possible by addition REDEFINITION to the method.
    Overloading - Changing the method parameters of inherited method
    Regards,
    Naimesh Patel

  • How to override a method in an inner class of the super class

    I have a rather horribly written class, which I need to adapt. I could simply do this if I could override a method in one of it's inner classes. My plan then was to extend the original class, and override the method in question. But here I am struggling.
    The code below is representative of my situation.
    public class ClassA
       ValueChecks vc = null;
       /** Creates a new instance of Main */
       public ClassA()
          System.out.println("ClassA Constructor");
          vc = new ValueChecks();
          vc.checkMaximum();
         // I want this to call the overridden method, but it does not, it seems to call
         // the method in this class. probably because vc belongs to this class
          this.vc.checkMinimum();
          this.myMethod();
       protected void myMethod()
          System.out.println("myMethod(SUPER)");
       protected class ValueChecks
          protected boolean checkMinimum()
             System.out.println("ValueChecks.checkMinimum (SUPER)");
             return true;
          protected boolean checkMaximum()
             return false;
    }I have extended ClassA, call it ClassASub, and it is this Class which I instantiate. The constructor in ClassASub obviously calls the constructor in ClassA. I want to override the checkMinimum() method in ValueChecks, but the above code always calls the method in ClassA. The ClassASub code looks like this
    public class ClassASub extends ClassA
       public ClassAInner cias;
       /** Creates a new instance of Main */
       public ClassASub()
          System.out.println("ClassASub Constructor");
       protected void myMethod()
          System.out.println("myMethod(SUB)");
       protected class ValueChecks extends ClassA.ValueChecks
          protected boolean checkMinimum()
             System.out.println("ValueChecks.checkMinimum (SUB)");
             return true;
    }The method myMethod seems to be suitably overridden, but I cannot override the checkMinimum() method.
    I think this is a stupid problem to do with how the ValueChecks class is instantiated. I think I need to create an instance of ValueChecks in ClassASub, and pass a reference to it into ClassA. But this will upset the way ClassA works. Could somebody enlighten me please.

    vc = new ValueChecks();vc is a ValueChecks object. No matter whether you subclass ValueChecks or not, vc is always of this type, per this line of code.
    // I want this to call the overridden method, but it does not, it seems to > call
    // the method in this class. probably because vc belongs to this class
    this.vc.checkMinimum();No, it's because again vc references a ValueChecks object, because it was created as such.
    And when I say ValueChecks, I mean the original class, not the one you tried to create by the same name, attempting to override the original.

  • This paintComponent Method is Annoying - HELP

    ok, I think I touched upon this problem sometime earlier, however I face a larger problem which I've been trying to solve by a different and simpler means but I get nothin.
    I have a paintComponent method which DRAWS lines, strings and shapes that get PAINTED on to a JFrame all good and well.
    Now, because of the amount of lines, strings and shapes I have on this "paintComponent", I want to put it in a class of its own. and THEN call it from the class it was in.
    So I want to create a new class, just for the paintComponent.
    Now, I've tried Numerous ways of trying to call it from another class but it just comes up as a blank screen. Oh and no I am not calling it directly too.
    Does anyone know where I am going wrong?
    help would be very much appreciated.

    ok LETS do this.
    class beep
    I call the paintComponent here to paint my JFrame BUT HOW!
    class drawingBoard----------------------------------------------------
    // create a rectangle called 'therectangle';
    protected void paintComponent(Graphics g)
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g;
    g2.draw(therectangle)
    g2.drawString("", 100, 100)
    Edited by: Calibre2007 on Feb 20, 2008 4:11 PM
    Edited by: Calibre2007 on Feb 20, 2008 4:11 PM

Maybe you are looking for

  • Error while opening any Page in my ADF App

    Dear All i have BC + JSF Project, and while opening any page in the first time , i am facing the below error oracle.jdevimpl.webapp.faces.config.modelimpl.FacesConfigHandler:Aug 24, 2011 10:27:24 AM oracle.jdevimpl.webapp.faces.config.modelimpl.Faces

  • Offline payment processing email not being received?

    We just got an event booking today with credit card payment and have yet to receive the secure PDF for processing. Is anyone else having this issue today or in the recent past? I noticed that this occured back in Feb but is it still not fixed? Any cl

  • BLOB unicode file name problem

    Hi,        I am trying to upload pdf file into SecureLOB column, I am getting error when I try to upload file name/directory  with unicode char, for other files/directory it works fine. w_src_loc := bfilename('LDIR', in_file_name);   dbms_lob.open(w_

  • How to have jtextfield focus enabled after window loading

    Hi Can I know how a JTextField can have cursor in it after the window it consists is loaded? Tried using the requestFocus(), but it did not work even after isFocusable() returned true. Could I get a whole piece of working code if possible, to see wha

  • Fastest way to handle and store a large number of posts in a very short time?

    I need to handle a very large number of HTTP posts in a very short period of time. The handling will consist of nothing more than storing the data posted and returning a redirect. The data will be quite small (email, postal code). I don't know exactl