About paintComponent method

Hello,
I am using swing to develop an user interface for a medium-complex program. Here is the code in the paintComponent method:
public void paintComponent (Graphics g) {
        Graphics2D g2 = (Graphics2D)g;
        super.paintComponents(g2);
        if (frame.m == null)
            System.out.println("Es null main");
        else {
            System.out.println("No es null main");
           Vector clusters = frame.m.obtenerClusters();
            Iterator it = clusters.iterator();
            while (it.hasNext()) {
                Cluster c = (Cluster)it.next();
                Punto p = c.obtenerCoordinador();
                Color color = c.obtenerColor();
                Vector sen = c.obtenerSensores();
                Iterator itS = sen.iterator();
                while (itS.hasNext()) {
                   Sensor s = (Sensor)itS.next();
                   dibujarSensor(g2, s, color);
                if (p != null) {
                    dibujarCoordinador(g2, p, color);
                    if (frame.isSelectedDibujarCirculo()) {
                        dibujarCirculoMinimo(g2, c.obtenerCoordinador(), c.obtenerRadio(), color);
            NodoSink s = frame.m.obtenerSink();
            if (s != null) {
              dibujarSink(g2,s);
    }Every time that this method is called (by me using repaint() or by the virtual machine), the program needs to "walk" over the hole Vector structure and paint again and again the same things, which is very inefficient.
There are some way to avoid it? I'm worry about it because the Vector structure is commonly very long.
Thanks!

Create a BufferedImage and do the custom painting on the BufferedImage.
If your painting is relatively static then you could create an ImageIcon from the BufferedImage and add the icon to a label and add the label to the GUI. If you need to change the custom painting then you would need to recreate the icon and update the image.
If you painting is relatively dynamic, then you just change the paintComponent() method to draw the buffered image.

Similar Messages

  • About paintComponent

    how can i make a panel paintComponent draw a background image only once? as i have other panel added to the background panel and i only want the component panel to redraw ... i cant seems to repaint only the component panel as i cant put them in separate paintComponent. any idea of how to go about?
    thanks~

    Create a BufferedImage and do the custom painting on the BufferedImage.
    If your painting is relatively static then you could create an ImageIcon from the BufferedImage and add the icon to a label and add the label to the GUI. If you need to change the custom painting then you would need to recreate the icon and update the image.
    If you painting is relatively dynamic, then you just change the paintComponent() method to draw the buffered image.

  • A question about a method with generic bounded type parameter

    Hello everybody,
    Sorry, if I ask a question which seems basic, but
    I'm new to generic types. My problem is about a method
    with a bounded type parameter. Consider the following
    situation:
    abstract class A{     }
    class B extends A{     }
    abstract class C
         public abstract <T extends A>  T  someMethod();
    public class Test extends C
         public <T extends A>  T  someMethod()
              return new B();
    }What I want to do inside the method someMethod in the class Test, is to
    return an instance of the class B.
    Normally, I'm supposed to be able to do that, because an instance of
    B is also an instance of A (because B extends A).
    However I cannot compile this program, and here is the error message:
    Test.java:16: incompatible types
    found   : B
    required: T
                    return new B();
                           ^
    1 errorany idea?
    many thanks,

    Hello again,
    First of all, thank you very much for all the answers. After I posted the comment, I worked on the program
    and I understood that in fact, as spoon_ says the only returned value can be null.
    I'm agree that I asked you a very strange (and a bit stupid) question. Actually, during recent months,
    I have been working with cryptography API Core in Java. I understood that there are classes and
    interfaces for defining keys and key factories specification, such as KeySpec (interface) and
    KeyFactorySpi (abstract class). I wanted to have some experience with these classes in order to
    understand them better. So I created a class implementing the interface KeySpec, following by a
    corresponding Key subclass (with some XOR algorithm that I defined myself) and everything was
    compiled (JDK 1.6) and worked perfectly. Except that, when I wanted to implement a factory spi
    for my classes, I saw for the first time this strange method header:
    protected abstract <T extends KeySpec> T engineGetKeySpec
    (Key key, Class<T> keySpec) throws InvalidKeySpecExceptionThat's why yesterday, I gave you a similar example with the classes A, B, ...
    in order to not to open a complicated security discussion but just to explain the ambiguous
    part for me, that is, the use of T generic parameter.
    The abstract class KeyFactorySpi was defined by Sun Microsystem, in order to give to security
    providers, the possibility to implement cryptography services and algorithms according to a given
    RFC (or whatever technical document). The methods in this class are invoked inside the
    KeyFactory class (If you have installed the JDK sources provided by Sun, You can
    verify this, by looking the source code of the KeyFactory class.) So here the T parameter is a
    key specification, that is, a class that implements the interface KeySpec and this class is often
    defined by the provider and not Sun.
    stefan.schulz wrote:
    >
    If you define the method to return some bound T that extends A, you cannot
    return a B, because T would be declared externally at invocation time.
    The definition of T as is does not make sense at all.>
    He is absolutely right about that, but the problem is, as I said, here we are
    talking about the implementation and not the invocation. The implementation is done
    by the provider whereas the invocation is done by Sun in the class KeyFactory.
    So there are completely separated.
    Therefore I wonder, how a provider can finally impelment this method??
    Besides, dannyyates wrote
    >
    Find whoever wrote the signature and shoot them. Then rewrite their code.
    Actually, before you shoot them, ask them what they were trying to achieve that
    is different from my first suggestion!
    >
    As I said, I didn't choose this method header and I'm completely agree
    with your suggestion, the following method header will do the job very well
    protected abstract KeySpec engineGetKeySpec (Key key, KeySpec key_spec)
    throws InvalidKeySpecException and personally I don't see any interest in using a generic bounded parameter T
    in this method header definition.
    Once agin, thanks a lot for the answers.

  • 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.

  • 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

  • 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...

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

  • TableBorder after overwrite paintComponent Method

    Hello,
    I created my own TableCellRenderer and overwrite the paintComponent() method to rotate the content in the header of my JTable.
    Now the TableHeader has no borders anymore. I tried to set the border again, but nothing solved my problem. I tried it in all classes to set the border.
    Anyone an idea how to get the borders back in the tableheader?
    Here's the Code:
    ----------------------------- class RowHeaderTable -----------------------------
    import java.awt.*;
    import javax.swing.*;
    public class RowHeaderTable extends JFrame {
         private static final long serialVersionUID = 1L;
         public RowHeaderTable() {
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              TableModel tm = new TableModel();
              // Create a column model for the main table. This model ignores the first
              // column added, and sets a minimum width of 150 pixels for all others.
              HeaderTableColumnModel colMod = new HeaderTableColumnModel();
              // Create a column model that will serve as our row header table. This
              // model picks a maximum width and only stores the first column.
              BodyTableColumnModel rowHeaderModel = new BodyTableColumnModel();
              JTable jt = new JTable(tm, colMod);
              Dimension d = jt.getTableHeader().getPreferredSize();
              d.height = 80;
              d.width = 1000;
              jt.getTableHeader().setPreferredSize(d);
              // Set up the header column and get it hooked up to everything
              JTable headerColumn = new JTable(tm, rowHeaderModel);
              jt.createDefaultColumnsFromModel();
              headerColumn.createDefaultColumnsFromModel();
              // Make sure that selections between the main table and the header stay
              // in sync (by sharing the same model)
              jt.setSelectionModel(headerColumn.getSelectionModel());
              // Make the header column look pretty
              //headerColumn.setBorder(BorderFactory.createEtchedBorder());
              headerColumn.setBackground(jt.getTableHeader().getBackground());
              headerColumn.setColumnSelectionAllowed(false);
              headerColumn.setCellSelectionEnabled(true);
              // Put it in a viewport that we can control a bit
              JViewport jv = new JViewport();
              jv.setView(headerColumn);
              jv.setPreferredSize(headerColumn.getMaximumSize());
              // With out shutting off autoResizeMode, our tables won't scroll
              // correctly (horizontally, anyway)
              jt.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
              // We have to manually attach the row headers, but after that, the scroll
              // pane keeps them in sync
              JScrollPane jsp = new JScrollPane(jt);
              jsp.setRowHeader(jv);
              jsp.setCorner(ScrollPaneConstants.UPPER_LEFT_CORNER, headerColumn.getTableHeader());
              getContentPane().add(jsp, BorderLayout.CENTER);
         public static void main(String args[]) {
              /*try {
                   UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
              } catch (ClassNotFoundException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              } catch (InstantiationException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              } catch (IllegalAccessException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              } catch (UnsupportedLookAndFeelException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              RowHeaderTable rht = new RowHeaderTable();
              rht.setTitle("Fenstertitel");
              rht.setSize(500, 480);
              rht.setLocation((rht.getToolkit().getScreenSize().width/2)-(rht.getSize().width/2), (rht.getToolkit().getScreenSize().height/2)-(rht.getSize().height/2));
              rht.setVisible(true);
    }----------------------------- class RotatedTableCellRenderer -----------------------------
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Font;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.geom.AffineTransform;
    import javax.swing.JLabel;
    import javax.swing.JTable;
    import javax.swing.UIManager;
    import javax.swing.table.TableCellRenderer;
    public class RotatedTableCellRenderer extends JLabel implements TableCellRenderer {
         private static final long serialVersionUID = 1L;
         protected int m_degreesRotation = -90;
         public RotatedTableCellRenderer(int degrees) {
              m_degreesRotation = degrees;
         public Component getTableCellRendererComponent(JTable table, Object value,
                   boolean isSelected, boolean hasFocus, int row, int column) {
              this.setToolTipText(value.toString());
              if(value.toString().length()>=15){
                   this.setText(value.toString().substring(0, 12) + "...");
              else {
                   this.setText(value.toString());
              this.setFont(new Font(this.getFont().getFamily(), Font.PLAIN, 12));
              return this;
         public void paintComponent(Graphics g) {
              Graphics2D g2 = (Graphics2D)g;
              g2.setClip(0,0,this.getWidth(),this.getHeight());
              g2.setColor(Color.BLACK);
              AffineTransform at = new AffineTransform();
              at.setToTranslation(this.getWidth(), this.getHeight());
              g2.transform(at);
              double radianAngle = ( ((double)m_degreesRotation) / ((double)180) ) * Math.PI;
              at.setToRotation(radianAngle);
              g2.transform(at);
              g2.drawString(this.getText(), 3.0f, -((this.getWidth()/2)-3));
              super.setBorder(UIManager.getBorder("TableHeader.cellBorder"));
    }----------------------------- class HeaderTableColumnModel -----------------------------
    import javax.swing.table.DefaultTableColumnModel;
    import javax.swing.table.TableColumn;
    public class HeaderTableColumnModel extends DefaultTableColumnModel {
         private static final long serialVersionUID = 1L;
         boolean first = true;
         public void addColumn(TableColumn tc) {
              // Drop the first column . . . that'll be the row header
              if (first) { first = false; return; }
              tc.setPreferredWidth(25);
              tc.setHeaderRenderer(new RotatedTableCellRenderer(-90));
              super.addColumn(tc);
    }----------------------------- class BodyTableColumnModel -----------------------------
    import javax.swing.table.DefaultTableColumnModel;
    import javax.swing.table.TableColumn;
    public class BodyTableColumnModel extends DefaultTableColumnModel{
         private static final long serialVersionUID = 1L;
         boolean first = true;
         public void addColumn(TableColumn tc) {
              if (first) {
                   tc.setMaxWidth(tc.getPreferredWidth());
                   super.addColumn(tc);                         
                   first = false;
    }----------------------------- class TableModel -----------------------------
    import javax.swing.table.AbstractTableModel;
    public class TableModel extends AbstractTableModel{
         private static final long serialVersionUID = 1L;
         String data[] = {"", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t"};
         public String headers[] = {"Row #", "Hier steht der lange Text 1", "Hier steht der lange Text 2", "Hier steht der lange Text 3", "Hier steht der lange Text 4", "Hier steht der lange Text 5", "Hier steht der lange Text 6", "Hier steht der lange Text 7", "Hier steht der lange Text 8", "Hier steht der lange Text 9", "Hier steht der lange Text 10"
                   , "Hier steht der lange Text 11", "Hier steht der lange Text 12", "Hier steht der lange Text 13", "Hier steht der lange Text 14", "Hier steht der lange Text 15", "Hier steht der lange Text 16", "Hier steht der lange Text 17", "Hier steht der lange Text 18", "Hier steht der lange Text 19", "Hier steht der lange Text 20"};
         public int getColumnCount() {
              return data.length;
         public int getRowCount() {
              return 1000;
         public String getColumnName(int col) {
              return headers[col];
         // Synthesize some entries using the data values & the row #
         public Object getValueAt(int row, int col) {
              return data[col] + row;
    Message was edited by:
    S.Beutel

    Thanks for your reply camickr.
    I've been looking into ways around the rendering issues of paintComponent and it is interesting to see some of the methods necessary to overcome this (e.g setOpaque, repaint etc).
    One method I saw was putting the objects you want to draw into a data structure (i.e ArrayList) and then using this to draw multiple objects onto the screen. Thus overcomming the super.paintComponent issue of erasing previous drawings. Is this the "preferred" way or is there a more practical solution.
    Chris.

  • Where can I find the detail document about certain method of a class?????

    Moved to correct forum by moderator
    Hi everyone,
    where can I find the detail document about certain method of a class?????
    e.g.  the class CL_GUI_ALV_GRID , when I was going through the class and looking
    at the methods, sometimes the method description is just like the method name,
    and I cannot know what the method does. 
      so, I am wondering  where I can find the detail information about the class???
    Edited by: Matt on Dec 4, 2008 11:55 AM

    Hi,
    Most of the times the SAP itself provides the documentaion of the CLASS. when you click on the METHOD name the METHOD DOCUMENTATION button you can see on the application tool bar.
    more over the names of the methods suggest what it is going to do.
    SET_ATTRIBUTE( sets the attribute)
    GET_ATTRIBUTE( gets the attribute value that is provided to the method)
    GET_CHILDNODE
    BIND_TABLE
    etc
    like this
    regards
    Ramchander Rao.K

  • About calling method with arguments

    Hi,
    I have a problem about calling method using reflection. my method is like follows:
    public myMethod(Integer var1, MyObject mobj) {
    I've tried to call the method using the following code,
    Class[] parameterTypes = new Class[] {Integer.class, MyObject.class};
    Object[] arguments = new Object[] {new Integer(2), mobj};
    Method met=cl.getMethod("myMethod", parameterTypes);
    But the in the last line NoSuchMethodException is thrown.
    How can I send the reference of MyObject to myMethod()?
    Thanx
    rony

    Should work ok:
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    public class Test {
         static class MyObject {}
         public static void main(String[] args) throws Exception {
              Class c = Test.class;
              Class[] parameterTypes = new Class[] {Integer.class, MyObject.class};                              
              try {
                   Object[] arguments = new Object[] {new Integer(2), new MyObject()};
                   Method met = c.getMethod("myMethod", parameterTypes);
                   met.invoke(new Test(), arguments);
              } catch (NoSuchMethodException e) {
                   System.out.println(e);
              } catch (IllegalAccessException e) {
                     System.out.println(e);
              } catch (InvocationTargetException e) {
                   System.out.println(e);
         public void myMethod(Integer var1, MyObject mobj) {
              System.out.println("myMethod");
    }

  • Which of the following are true about abstract methods in EJB 2.0

    Hi guys I'm beginner to EJB and i got some unanswered questions.
    Can any one of you please.. give answers?
    Thanks if you do...
    Which of the following are true about abstract methods in EJB 2.0
    CMP?
    Choose all correct answers:
    1. Abstract accessor methods should not be exposed in the EJB
    component's interface
    2.Abstract accessor/mutator methods are used to access and modify
    persistent state and relationship information for entity objects
    3.Abstract Accessor/Mutator methods do not throw exceptions
    4.The EJB developer must implement the Accessor/Mutator methods
    5.Abstract accessor methods may or may not be exposed in the EJB
    component's interface
    2.Which ONE of the following is true?
    Choose the best answer:
    1.Local interfaces cannot have a relationship with other Entity
    components
    2.Local interfaces cannot be used for Stateless Session EJB
    3.Local interfaces can be a part of Object's persistent state
    4.Local interfaces have the same functionality as that of a
    stateless Session EJB
    3.Which of the following describe the <cmr-field> in a EJB 2.0
    descriptor?
    Choose all correct answers:
    1.A Local interface/Entity can be a value of a <cmr-field>
    2.There is no <cmr-field> in EJB 2.0 descriptor
    3.It is used to represent one meaningful association between any
    pair of Entity EJBs, based on the business logic of the Application
    4.It provides a particular mapping from an object model to a
    relational database schema
    5.It allows the Local Entity interfaces to participate in
    relationships
    4.Which of the following are the advantages of using Local interfaces
    instead of dependent value classes?
    Choose all correct answers:
    1.Local Entity Interfaces can participate in Relationships
    2.The life cycle of Local Entity Interfaces is managed by EJB
    container, intelligently
    3.Local Entity Interfaces can be used in EJB QL Queries
    4.Local Entity Interfaces can be a part of the <cmp-field> but not
    <cmr-field>
    5.Which of the following are true about Local interfaces
    1.A local interface must be located in the same JVM to which the EJB
    component is deployed
    2.Local calls involve pass-by-reference.
    3.The objects that are passed as parameters in local interface
    method calls must be serializable.
    4.In general, the references that are passed across the local
    interface cannot be used outside of the immediate call chain and must
    never be stored as part of the state of another enterprise bean.
    6.Which of the following specifies the correct way for a client
    to access a Message driven Bean?
    Choose the best answer:
    1. via a Remote interface
    2. via Home interface
    3. Message driven bean can be accessed directly by the client
    4. both 1 & 2
    5. none of the above
    ------------------------------------------------------------------------7.Which of the following statements are true about message-driven
    bean Clients?
    ------------------------------------------------------------------------Choose all correct answers:
    They can create Queue and QueueConnectionFactory objects
    They can create Topic and TopicConnectionFactory objects
    They can lookup the JNDI server and obtain the references for
    Queue and Topic and their connection Factories
    Only 1 and 2 above

    Hi guys I'm beginner to EJB and i got some unanswered
    questions.
    Can any one of you please.. give answers?
    Thanks if you do...
    Which of the following are true about abstract methods
    in EJB 2.0
    CMP?
    Choose all correct answers:
    1. Abstract accessor methods should not be exposed
    d in the EJB
    component's interfacefalse
    2.Abstract accessor/mutator methods are used to
    access and modify
    persistent state and relationship information for
    entity objectstrue
    >
    3.Abstract Accessor/Mutator methods do not throw
    exceptionstrue
    >
    4.The EJB developer must implement the
    Accessor/Mutator methodsfalse
    5.Abstract accessor methods may or may not be exposed
    in the EJB
    component's interfacetrue
    2.Which ONE of the following is true?
    Choose the best answer:
    1.Local interfaces cannot have a relationship with
    other Entity
    componentsfalse
    2.Local interfaces cannot be used for Stateless
    Session EJBfalse
    3.Local interfaces can be a part of Object's
    persistent statefalse
    4.Local interfaces have the same functionality as
    that of a
    stateless Session EJBtrue
    3.Which of the following describe the <cmr-field> in a
    EJB 2.0
    descriptor?
    Choose all correct answers:
    1.A Local interface/Entity can be a value of a
    <cmr-field>true
    2.There is no <cmr-field> in EJB 2.0 descriptorfalse
    3.It is used to represent one meaningful association
    between any
    pair of Entity EJBs, based on the business logic of
    the Applicationtrue
    4.It provides a particular mapping from an object
    model to a
    relational database schematrue
    5.It allows the Local Entity interfaces to
    participate in
    relationshipstrue
    4.Which of the following are the advantages of using
    Local interfaces
    instead of dependent value classes?
    Choose all correct answers:
    1.Local Entity Interfaces can participate in
    Relationshipsis
    2.The life cycle of Local Entity Interfaces is
    managed by EJB
    container, intelligentlyis
    3.Local Entity Interfaces can be used in EJB QL
    Queriesnot
    4.Local Entity Interfaces can be a part of the
    <cmp-field> but not
    <cmr-field>not
    >
    >
    5.Which of the following are true about Local
    interfaces
    1.A local interface must be located in the same JVM
    M to which the EJB
    component is deployedtrue
    2.Local calls involve pass-by-reference.true
    3.The objects that are passed as parameters in local
    l interface
    method calls must be serializable.false
    4.In general, the references that are passed across
    s the local
    interface cannot be used outside of the immediate
    e call chain and must
    never be stored as part of the state of another
    r enterprise bean.true
    >
    6.Which of the following specifies the correct way for
    a client
    to access a Message driven Bean?
    Choose the best answer:
    1. via a Remote interfacefalse
    2. via Home interfacefalse
    3. Message driven bean can be accessed directly by
    the clientfalse
    4. both 1 & 2false
    5. none of the abovetrue.
    >
    ----------------7.Which of the following statements
    are true about message-driven
    bean Clients?
    ----------------Choose all correct answers:
    They can create Queue and QueueConnectionFactory
    objectsthe container can, dunno bout clients
    >
    They can create Topic and TopicConnectionFactory
    objectsthe container can, dunno bout clients
    >
    They can lookup the JNDI server and obtain the
    references for
    Queue and Topic and their connection Factories
    true
    Only 1 and 2 abovefalse
    somebody correct me if i'm wrong

  • Why does the parameter of the paintComponent method have....?

    Why does the parameter of the paintComponent method have type Graphics and not Graphics2D?

    masijade. wrote:
    Additionally, it is, however, normally, a Graphics2D object's reference value that is passed around....which means most painting code starts out by casting the Graphics object to Graphics2D. You know what they say: death, taxes, and cruft... :P

  • Problem after over riding paintComponent() method

    I am over riding the paintComponent() method for a button to show the text in 2 lines. But when I invoke setEnabled(false) on the button, the button is getting disabled but the text is not.
    Could any one please let me know how to do that.
    The code for the paintComponent() method is pasted for reference
    protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D)g;
    int w = getWidth();
    int h = getHeight();
    FontMetrics fm = g.getFontMetrics();
    int textw1 = fm.stringWidth(text1);
    int textw2 = fm.stringWidth(text2);
    FontRenderContext context = g2.getFontRenderContext();
    LineMetrics lm = getFont().getLineMetrics(text1, context);
    int texth = (int)lm.getHeight();
    prefHeight = texth;
    int x1 = (w - textw1) / 2;
    int x2 = (w - textw2) / 2;
    int th = (texth * 2);
    int dh = ((h - th) / 2);
    int y1 = dh + texth - 3;
    int y2 = y1 + texth;
    // Draw texts
    g.setColor(getForeground());
    g.drawString(text1, x1, y1);
    g.drawString(text2, x2, y2);
    regards,
    shantanu

    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.

Maybe you are looking for

  • How do I install OSX10.5 using an external LaCie DVD Drive?

    I purchased a External LaCie Drive recommended by Apple Genius Bar to affordably replace a dead internal DVD drive on an older iMac G4. I bought a family package of Leopard OSX10.5 and installed 10.5 on my main computer (G5) using its internal drive.

  • Cannot update drivers error code 193 on All in one 8500 Win 8.1

    Running Win 8.1 updated from 7.. All in One 8500 910A Can do basic printing but no longer have twain support for scanning etc. When trying to update get failure notice error number 193. HP message says they have no further advice

  • Format Issue

    I have a hbox that has a repeater of linkbuttons, and the datasource of the repeater is an array collection I build. I first build it from 1 to 10 (1 2 3 4 5 6 7 8 9 10), and to the right of the repeater I put an image that filters my numbers to give

  • FBL3N-Layout Creation

    HI , In Tcode FBL3N for G/L line Item display can I create a new layout.It seems the option as deactivated for me. Thanks in advance, Savitha

  • Handling Enter key in JTable

    Hi... What I m trying is to add a blank row to the table,if and only if the user presses ENTER in the last row(with some data in cell,not blank) Unfortunately,I m not able to do so . Also I want that the focus should go to the cell in the next row &