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

Similar Messages

  • When i am trying to create an itunes account in ipad 3 and in payment method i select none and after it when i select create ID. "Please contact ITunes Support to complete the transcation" this message will appear. kindly help me

    when i am trying to create an itunes account in ipad 3 and in payment method i select none and after it when i select create ID. "Please contact ITunes Support to complete the transcation" this message will appear. kindly help me

    You can contact iTunes support via this page (these are user-to-user forums) : http://www.apple.com/support/itunes/contact/ - click on Contact iTunes Store Support on the right-hand side of the page

  • In using Mail between my Yahoo emails i kep getting cut off telling me that my present password no longer works. This is more than annoying since i transfer files between various Yahoo accounts for my filing purposes. Help me stop this abuse. Please.

    In using Mail and moving between my Yahoo emails i keep getting cut off telling me that my present password no longer works. But i have been getting my work done and suddelnly my password no loner is acceptalbe even upon re-entering it many times.This is more than annoying since i transfer files between various Yahoo accounts for my filing purposes. Help me stop this abuse. Please.

    Ah yes school boy error there out of frustration and discontent..
    My issue is with music/apps/films etc not downloading from iTunes / App Store.
    They initially fail and message is displayed stating unable to download / purchase at this time, yet if I retry it says I've already purchased (?) or alternatively I go to the purchased section and there they are waiting with the cloud symbol..
    However some items get frozen in the download window and cannot be retried or deleted. Message appears stating to tap to retry, but even if you stole every bath and sink in the uk you'd still not have enough taps.
    I post here as the iTunes guys are useless in there 'help' and have only advised posting here or phoning apple, at my expense, to explain a problem that could be rectified by forwarding my original email to a techie. However the tech team apparently don't have an email address as they're from ye olde Middle Ages..!
    Anyways I digress.
    So I tried sync to pc, but instead of showing the file as ready to listen/use/view, the iCloud symbol shows and I'm back to square one as the item is unable to download..
    At frustration station waiting for a train from pain...
    All my software is up to date, and had all worked fine prior to the last big iOS update that resulted in all the changes in display and dismay.
    Answers in a postcard :-)
    Much love

  • So, I dropped my phone today on the cement, it works...with minor annoying glitches, has nasty bluish vertical lines and the picture is a tad distorted as well. :/ Does this mean I need to spend tons of money to get this fixed? Ahhhh! Help!

    So, I dropped my phone today on the cement, it works...with minor annoying glitches, has nasty bluish vertical lines and the picture is a tad distorted as well. :/ Does this mean I need to spend tons of money to get this fixed? Ahhhh! Help!

    Hi Rahhh829, 
    Welcome to the Apple Support Communities!
    It sounds like you may want to get your iPhone evaluated for repair. Please review the following web link for information on the iPhone repair pricing and process. 
    iPhone Repair and Service - Apple Support
    Regards, 
    Joe

  • I need help with this recursion method

         public boolean findTheExit(int row, int col) {
              char[][] array = this.getArray();
              boolean escaped = false;
              System.out.println("row" + " " + row + " " + "col" + " " + col);
              System.out.println(array[row][col]);
              System.out.println("escaped" + " " + escaped);
              if (possible(row, col)){
                   System.out.println("possible:" + " " + possible(row,col));
                   array[row][col] = '.';
              if (checkBorder(row, col)){
                   System.out.println("check border:" + " " + checkBorder(row,col));
                   escaped = true;
              else {
                    System.out.println();
                    escaped = findTheExit(row+1, col);
                    if (escaped == false)
                    escaped = findTheExit(row, col+1);
                    else if (escaped == false)
                    escaped = findTheExit(row-1, col);
                    else if (escaped == false)
                    escaped = findTheExit(row, col-1);
              if (escaped == true)
                   array[row][col] = 'O';
              return escaped;
         }I am having difficulties with this recursion method. What I wanted here is that when :
    if escaped = findTheExit(row+1, col);  I am having trouble with the following statement:
    A base case has been reached, escaped(false) is returned to RP1. The algorithm backtracks to the call where row = 2 and col = 1 and assigns false to escaped.
    How do I fix this code?
    I know what's wrong with my code now, even though that if
    if (possible(row, col))
    [/code[
    returns false then it will go to if (escaped == false)
                   escaped = findTheExit(row, col+1);
    how do I do this?

    Okay I think I got the problem here because I already consult with the instructor, he said that by my code now I am not updating my current array if I change one of the values in a specific row and column into '.' . How do I change this so that I can get an update array. He said to me to erase char[][] array = getArray and replace it with the array instance variable in my class. But I don't have an array instance variable in my class. Below is my full code:
    public class ObstacleCourse implements ObstacleCourseInterface {
         private String file = "";
         public ObstacleCourse(String filename) {
              file = filename;
         public boolean findTheExit(int row, int col) {
              boolean escaped = false;
              //System.out.println("row" + " " + row + " " + "col" + " " + col);
              //System.out.println(array[row][col]);
              //System.out.println("escaped" + " " + escaped);
              if (possible(row, col)){
                   //System.out.println("possible:" + " " + possible(row,col) + "\n");
                   array[row][col] = '.';
                   if (checkBorder(row, col)){
                   escaped = true;
                   else {
                    escaped = findTheExit(row+1, col);
                    if (escaped == false)
                    escaped = findTheExit(row, col+1);
                    else if (escaped == false)
                    escaped = findTheExit(row-1, col);
                    else if (escaped == false)
                    escaped = findTheExit(row, col-1);
              if (escaped == true)
                   array[row][col] = 'O';
              return escaped;
         public char[][] getArray() {
              char[][] result = null;
              try {
                   Scanner s = new Scanner(new File(file));
                   int row = 0;
                   int col = 0;
                   row = s.nextInt();
                   col = s.nextInt();
                   String x = "";
                   result = new char[row][col];
                   s.nextLine();
                   for (int i = 0; i < result.length; i++) {
                        x = s.nextLine();
                        for (int j = 0; j < result.length; j++) {
                             result[i][j] = x.charAt(j);
              } catch (Exception e) {
              return result;
         public int getStartColumn() {
              char[][] result = this.getArray();
              int columns = -1;
              for (int i = 0; i < result.length; i++) {
                   for (int j = 0; j < result[i].length; j++) {
                        if (result[i][j] == 'S')
                             columns = j;
              return columns;
         public int getStartRow() {
              char[][] result = this.getArray();
              int row = -1;
              for (int i = 0; i < result.length; i++) {
                   for (int j = 0; j < result[i].length; j++) {
                        if (result[i][j] == 'S')
                             row = i;
              return row;
         public boolean possible(int row, int col) {
              boolean result = false;
              char[][] array = this.getArray();
              if (array[row][col] != '+' && array[row][col] != '.')
                   result = true;
              return result;
         public String toString() {
              String result = "";
              try {
                   Scanner s = new Scanner(new File(file));
                   s.nextLine();
                   while (s.hasNextLine())
                        result += s.nextLine() + "\n";
              } catch (Exception e) {
              return result;
         public boolean checkBorder(int row, int col) {
              char[][] array = this.getArray();
              boolean result = false;
              int checkRow = 0;
              int checkColumns = 0;
              try {
                   Scanner s = new Scanner(new File(file));
                   checkRow = s.nextInt();
                   checkColumns = s.nextInt();
              } catch (Exception e) {
              if ((row + 1 == checkRow || col + 1 == checkColumns) && array[row][col] != '+')
                   result = true;
              return result;
    I thought that my problem would be not to read the file using the try and catch everytime in the method. How do I do this?? Do I have to create an array instance variable in my class?

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

  • I'm trying to recover my security questions, but my alternate email address on the link does not match the one I have put in my Apple ID, on the link it is has an old one that no longer exists. Has anyone else been through this or knows how to help m

    I've been trying to remember my security questions for ages, and I can't seem to remember them. On my Apple ID I have changed my alternate email address because the previous one was deleted, but when I go on the "Password and Security" page on my Apple ID and there is a link saying "Forgot your answers? Send reset security info email to ************@*******.com" but it is giving me my old email that does not match my current one on my Apple ID and no longer exists. I have been trying for very long to recover my security questions' answers, but Apple is not coping with me.
    Has anyone been through this or knows how to help me?
    Thank you.

    You need to ask Apple to reset your security questions. To do this, click here and pick a method; if that page doesn't list one for your country or you're unable to call, fill out and submit this form.
    (122986)

  • I have Iphone 4G. I bought when I studied in Usa. Then I returned to  Uzbekistan this Iphone doesn't work. How I can use this phone? Can you help me?

    I have Iphone 4G. I bought when I studied in Usa. Then I returned to  Uzbekistan this Iphone doesn't work. How I can use this phone? Can you help me?

    shohjahon wrote:
    I have Iphone 4G.
    No, you do not.  It simply is not possible to have a device that does not exist.
    Most likely, you have an iPhone 4.  There is no 4G iPhone.
    shohjahon wrote:
    I bought when I studied in Usa. Then I returned to  Uzbekistan this Iphone doesn't work.
    Yes, it does work.  It is carrier locked to AT&T, just like all GSM iPhones sold in the US since their introduction.
    shohjahon wrote:
    How I can use this phone?
    You can use the phone as it is, but it will be very expensive with AT&T international roaming plans.
    There is no official way to unlock the phone for use with another carrier.
    Your options:
    Sell the device and purchase one intended for use in your country.
    Find unofficial method to unlock
    Use as an iPod Touch.
    No one here can provide you with assistance on getting you AT&T locked iPhone to work on another carrier.

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

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

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

  • Error: Sorry! We could not complete the transaction using this payment method. Please contact support.

    I am everytime getting the following error
    Sorry! We could not complete the transaction using this payment method. Please contact support.
    I have put my 2 credit card information with Microsoft. I tried calling 2 times the customer support but it was a pathetic response. In a single call I talked to 4 customer support officers and everybody passed on the call to the next without resolving the
    problem, and without telling the next officer what is my issue!! they just passed on the phone call to avoid me!!
    It is really frustrating that neither Microsoft is provide a good support (it was hard for them to understand my issue, in fact one of the support guy did not even know spelling of Azure.. he/she was saying it assure!!! and One of the guy told me that I
    cannot use credit card outside US and Canada. then why you call yourself global???
    So Microsoft you have a few things to do as your homework.
    1. Your support is pathetic, frustrating and requires better people out there who know about your products, so train them first!
    2. You got my 2 credit cards information which I see at subscriptions for Windows Azure, please remove both of them if you cannot provide a good support and subscription.
    3. Learn from other cloud providers, AWS will otherwise kill your business.
    Regards
    Kajal
    Kajal Sinha

    Hi Kajal,
    Sincerely apologize for this inconvenience, for billing & account issue, usually we need to contact the support team by creating a support ticket at
    http://www.windowsazure.com/en-us/support/contact/. Or if that doesn't work because you don't have an active subscription you will need to contact general customer support to have them create
    a support ticket for you 
    http://support.microsoft.com/gp/customer-service-phone-numbers?wa=wsignin1.0).
    If above support channels don't work, at your convenient, could you please send an email to me: dxu at microsoft.com with kindly providing your:
    Name
    Email address
    Phone number 
    We will provide help via emails. Thank you.
    Best Regards,
    Ming Xu
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

Maybe you are looking for