G.drawLine problem...

I'm trying to make it so you click and option from the menu bar which will then open a JDialogBox, you enter text, it turns it into a string, then use g.drawline to ad it to the JPanel.
Heres my code:
// Scribble.java //
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
* This JFrame subclass is a simple "paint" application.
public class Scribble extends JFrame {   
   * The main method instantiates an instance of the class, sets it size, and
   * makes it visible on the screen
  public static void main(String[] args) {
    Scribble scribble = new Scribble();
    scribble.setSize(500, 300);
    scribble.setVisible(true);
  // The scribble application relies on the ScribblePane2 component developed
  // earlier. This field holds the ScribblePane2 instance it uses.
  ScribblePane2 scribblePane;
   * This constructor creates the GUI for this application.
  public Scribble() {
    super("Scribble"); // Call superclass constructor and set window title
    // Handle window close requests
    this.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
    // All content of a JFrame (except for the menubar) goes in the
    // Frame's internal "content pane", not in the frame itself.
    // The same is true for JDialog and similar top-level containers.
    Container contentPane = this.getContentPane();
    // Create the main scribble pane component,
    // a background color, and add it to the content pane
    scribblePane = new ScribblePane2();
    scribblePane.setBackground(Color.white);
    contentPane.add(scribblePane);
    // Create a menubar and add it to this window. Note that JFrame
    // handles menus specially and has a special method for adding them
    // outside of the content pane.
    JMenuBar menubar = new JMenuBar(); // Create a menubar
    this.setJMenuBar(menubar); // Display it in the JFrame
    // Create menus and add to the menubar
    JMenu filemenu = new JMenu("File");
    JMenu colormenu = new JMenu("Color");
    JMenu textmenu = new JMenu("Text");
    menubar.add(filemenu);
    menubar.add(colormenu);
    menubar.add(textmenu);
    // Create some Action objects for use in the menus and toolbars.
    // An Action combines a menu title and/or icon with an ActionListener.
    // These Action classes are defined as inner classes below.
    Action open = new OpenAction();
    Action save = new SaveAction();
    Action clear = new ClearAction();
    Action select = new SelectColorAction();
    Action text = new TextAction();
    // Populate the menus using Action objects
    filemenu.add(open);
    filemenu.add(save);
    filemenu.add(clear);
    colormenu.add(select);
    textmenu.add(text);
private final static int//initialization
                 CURVE = 0,
                 LINE = 1,
                 RECT = 2,             
                 OVAL = 3,              
                 ROUNDRECT = 4,         
                 FILLED_RECT = 5,
                 FILLED_OVAL = 6,
                 FILLED_ROUNDRECT = 7;
      Image OSI;  // The off-screen image (created in checkOSI()).
      int widthOSI, heightOSI;   
  private int mouseX, mouseY;   // The location of the mouse.
      private int begnX, begnY;     // The previous location of the mouse.
      private int startngX, startngY;   // The starting position of the mouse.
                                    // (Not used for drawing curves.)
      private boolean dragging;     // This is set to true when the user is drawing.
      private int shape;    // What type of figure is being drawn.  This is
                             //    specified by the shapeChoice menu.
      private Graphics dragGraphics;  // A graphics context for the off-screen image,
                                      // to be used while a drag is in progress.
      private Color dragColor;  // The color that is used for the shape that is
                                // being drawn.
      private void drawShape(Graphics g, int shape, int x1, int y1, int x2, int y2) {
           if (shape == LINE) {
               // For a line, just draw the line between the two points.
            g.drawLine(x1,y1,x2,y2);
            return;
         int x, y;  // Top left corner of rectangle that contains the figure.
         int w, h;  // Width and height of rectangle that contains the figure.
         if (x1 >= x2) {  // x2 is left edge
            x = x2;
            w = x1 - x2;
         else {          // x1 is left edge
            x = x1;
            w = x2 - x1;
         if (y1 >= y2) {  // y2 is top edge
            y = y2;
            h = y1 - y2;
         else {          // y1 is top edge.
            y = y1;
            h = y2 - y1;
         switch (shape) {   // Draw the appropriate figure.
            case RECT:
               g.drawRect(x, y, w, h);
               break;
            case OVAL:
               g.drawOval(x, y, w, h);
               break;
            case ROUNDRECT:
               g.drawRoundRect(x, y, w, h, 20, 20);
               break;
            case FILLED_RECT:
               g.fillRect(x, y, w, h);
               break;
            case FILLED_OVAL:
               g.fillOval(x, y, w, h);
               break;
            case FILLED_ROUNDRECT:
               g.fillRoundRect(x, y, w, h, 20, 20);
               break;
  //This inner class defines the "open" action to open an image file
  class OpenAction extends AbstractAction {
    public OpenAction() {
      super("Open");
    public void actionPerformed(ActionEvent e) {
      scribblePane.open();
//This inner class defines the "save" action to save as .jpg
  class SaveAction extends AbstractAction {
    public SaveAction() {
      super("Save As");
    public void actionPerformed(ActionEvent e) {
      scribblePane.save();
  /** This inner class defines the "clear" action that clears the scribble */
  class ClearAction extends AbstractAction {
    public ClearAction() {
      super("Clear"); // Specify the name of the action
    public void actionPerformed(ActionEvent e) {
      scribblePane.clear();
    //This inner class defines an Action that sets the current drawing color of
    //the ScribblePane2 component.
  class ColorAction extends AbstractAction {
    Color color;
    public ColorAction(Color color) {
    this.color = color;
    public void actionPerformed(ActionEvent e) {
      scribblePane.setColor(color); // Set current drawing color
   // This inner class defines an Action that uses JColorChooser to allow the
   // user to select a drawing color
  class SelectColorAction extends AbstractAction {
    public SelectColorAction() {
      super("Select Color...");
    public void actionPerformed(ActionEvent e) {
      Color color = JColorChooser.showDialog(Scribble.this,
          "Select Drawing Color", scribblePane.getColor());
      if (color != null)
        scribblePane.setColor(color);
  class TextAction extends AbstractAction {
    public TextAction() {
      super("Paste Text");
    public void actionPerformed(ActionEvent e) {
    scribblePane.text();
// A simple JPanel subclass that uses event listeners to allow the user to
// scribble with the mouse. Note that scribbles are not saved or redrawn.
class ScribblePane2 extends JPanel {
  public ScribblePane2() {
    // Give the component a preferred size
    setPreferredSize(new Dimension(450, 200));
    // Register a mouse event handler defined as an inner class
    // Note the call to requestFocus(). This is required in order for
    // the component to receive key events.
    addMouseListener(new MouseAdapter() {
      public void mousePressed(MouseEvent e) {
        moveto(e.getX(), e.getY()); // Move to click position
        requestFocus(); // Take keyboard focus
    // Register a mouse motion event handler defined as an inner class
    // By subclassing MouseMotionAdapter rather than implementing
    // MouseMotionListener, we only override the method we're interested
    // in and inherit default (empty) implementations of the other methods.
    addMouseMotionListener(new MouseMotionAdapter() {
      public void mouseDragged(MouseEvent e) {
        lineto(e.getX(), e.getY()); // Draw to mouse position
    // Add a keyboard event handler to clear the screen on key 'C'
    addKeyListener(new KeyAdapter() {
      public void keyPressed(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_C)
          clear();
  /** These are the coordinates of the the previous mouse position */
  protected int last_x, last_y;
  /** Remember the specified point */
  public void moveto(int x, int y) {
    last_x = x;
    last_y = y;
  /** Draw from the last point to this point, then remember new point */
  public void lineto(int x, int y) {
    Graphics g = getGraphics(); // Get the object to draw with
    g.setColor(color); // Tell it what color to use
    g.drawLine(last_x, last_y, x, y); // Tell it what to draw
    moveto(x, y); // Save the current point
   * Clear the drawing area, using the component background color. This method
   * works by requesting that the component be redrawn. Since this component
   * does not have a paintComponent() method, nothing will be drawn. However,
   * other parts of the component, such as borders or sub-components will be
   * drawn correctly.
  public void open() { //Function to open file
    JFileChooser fileChooser = new JFileChooser(".");
    fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); 
    int status = fileChooser.showOpenDialog(null);
      if (status == JFileChooser.APPROVE_OPTION) {
        File selectedFile = fileChooser.getSelectedFile();
  public void save() { //Function to save file [needs work]
    JFileChooser fileChooser = new JFileChooser(".");
      fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); 
      int status = fileChooser.showSaveDialog(null);
        if (status == JFileChooser.APPROVE_OPTION) {
          File selectedFile = fileChooser.getSelectedFile();
  public void clear() {
    repaint();
  /** This field holds the current drawing color property */
  Color color = Color.black;
  /** This is the property "setter" method for the color property */
  public void setColor(Color color) {
    this.color = color;
  /** This is the property "getter" method for the color property */
  public Color getColor() {
    return color;
  public void text() {
    String inputValue = JOptionPane.showInputDialog("Enter yee olde string...");
    System.out.println("String entered is:" + inputValue);
  //  g.drawString(inputValue, startngX, startngY);
  //  String text = text.getText();
  public void paintComponent(Graphics g) {
         checkOSI();
         g.drawImage(OSI, 0, 0, this);
         if (dragging && shape != CURVE) {
            g.setColor(dragColor);
            drawShape(g,shape,startngX,startngY,mouseX,mouseY);
      private void checkOSI() {
         if (OSI == null || widthOSI != getSize().width || heightOSI != getSize().height) {
                // Create the OSI, or make a new one if panel size has changed.
            OSI = null;  // (If OSI already exists, this frees up the memory.)
            OSI = createImage(getSize().width, getSize().height);
            widthOSI = getSize().width;
            heightOSI = getSize().height;
            Graphics OSG = OSI.getGraphics();  // Graphics context for drawing to OSI.
            OSG.setColor(getBackground());
            OSG.fillRect(0, 0, widthOSI, heightOSI);
            OSG.dispose();
}when i try and do this:
  public void text(Graphics g) {
    String inputValue = JOptionPane.showInputDialog("Enter yee olde string...");
    System.out.println("String entered is:" + inputValue);
    g.drawString(inputValue, startngX, startngY);It says i can't put Graphics g there, not sure why :|
Any help would be great! Thanks :)

...alex wrote:
-Kayaman- wrote:
So you write the method to accept a Graphics object as a parameter, then you try to call it without passing a parameter.
GEE WIZ, I WONDER WHAT COULD BE THE PROBLEM?wow... thanks... that really helps me considering i'm posting in the "New To Java" section.Don't mention it.
>
As for the OSI = null, this is part of a group assignment. All the code between the /////////////'s is from another group member, i haven't even looked at the code yet as i just pasted it in and don't need to worry about it until i can get it the program to compile with drawLine.Well, you can get mental brownie points by telling him that it doesn't free any memory to explicitly assign it to null, especially since you're assigning it again on the next line.
There is almost never a need to explicitly set something to null like that.

Similar Messages

  • Drawline() problem

    Hi all,
    I am trying to write an applet which prompts the user to enter some data
    into a textfield. I then need to print a line based on the information supplied by the user to draw an image. the problem I am having is reading in the information in from the text field.
    I have a variable x which is the number of pixels, I also have varibales for the directions..FD = forward direction
    BK = backward direction
    TURN = turning sw or nw etc.
    COLOUR =(there are only 4 colours)
    here is an example of the textfield. FD 50, BK 50, TURN sw, COLOUR red.
    I cannot find any relevant examples of reading this data in.
    I have a void paint(Graphics g) method, but cannot get the 2 to talk to each other. any help would be appreciated.
    cheers
    mark

    Here is a fake class to store the drawing commands
    class LineCommand {
         String sCmd;
         String sVal;
         public LineCommand(String cmd, String val ) {
              sCmd = cmd;
              sVal = val;
    Let's assume you're using a vector to store all commands in the Applet and a boolean to tell the applet it has to repaint:
    Vector vecCommands = new Vector()
    boolean bRepaint = false;
    In the init() :
    textField.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e) {              
         String sData = textField.getText();
         // Parse each command (FD, BD...) and build all data
         // For example, command = "FD" and value = "50"
         for (...) {
              vecCommands.add(new LineCommand(command, value);
         // Repaint the Applet
         bRepaint = true;
         // Call the applet repaint() method
    In the paint() :
    if ( bRepaint ) {
    for ( int i = 0; i < vecCommands.size(); i++) {
         // Read each command and draw the stuff
    It's only an image. It won't compile of course. And the LineCommand class is just a fake. You'll have to store the data an other. It's simply to illustrate the timing.

  • Problem with drawLine and GridLayout Manager

    Hi
    I am writing a piece of software that lets you design a local area network. Currently I have a JPanel with a GridLayout of 10 squares by 10 squares. Each of these grid spaces is filled with a small custom component that is blank if empty or displaying the relevant graphic to the user if a node has been placed. The difficulty that I am having is that I want to be able to draw a section of cable between nodes. As an example, when the user places a Server and a client, I want them to be able to hold down SHIFT, select the two nodes, then press a key (probably 'c') to automatically generate a run of cable between the two nodes. The software achieves this by getting the co-ordinates of the center point of the two nodes and drawing a line between them using the graphics class drawLine() method. I have all of this working fine apart from the bit where the cable needs to be drawn. The reason is that I can only create a section of cable by creating a new component and then using g.drawLine(). Fair enough. However, I can only draw within the small grid section designated by the GridLayout manager in the JPanel. What I am asking is how would I go about getting the software to draw a line between two relative co-ordinates on the screen, disregarding any positioning that the GridLayout manager tries to impose. To put it another way, how would I go about getting the software to draw a line between two absolutety specified co-ordinates, as opposed to relative co-ordinates currently being used? Any help would be greatly appeciated, thanks

    Here's a way to draw lines between component centers irrespective of layouts.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.util.*;
    import java.util.List;
    import javax.swing.*;
    public class GridDrawing
        public static void main(String[] args)
            JLabel[] labels = new JLabel[100];
            JPanel loPanel = new JPanel(new GridLayout(0,10));
            for(int j = 0; j < labels.length; j++)
                labels[j] = new JLabel(String.valueOf(j + 1), JLabel.CENTER);
                labels[j].setBorder(BorderFactory.createEtchedBorder());
                loPanel.add(labels[j]);
            OverdrawPanel overdrawPanel = new OverdrawPanel();
            CableSelector selector = new CableSelector(overdrawPanel, loPanel);
            JPanel panel = new JPanel();
            OverlayLayout overlay = new OverlayLayout(panel);
            panel.add(overdrawPanel);
            panel.setLayout(overlay);
            panel.add(loPanel);
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(panel);
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
    class OverdrawPanel extends JPanel
        List cableList;
        public OverdrawPanel()
            cableList = new ArrayList();
            setOpaque(false);
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setPaint(Color.red);
            for(int j = 0; j < cableList.size(); j++)
                g2.draw((Line2D)cableList.get(j));
        public void addCable(Point2D p1, Point2D p2)
            Line2D line = new Line2D.Double(p1, p2);
            cableList.add(line);
            repaint();
        public void register(CableSelector cs)
            addMouseListener(cs);
    class CableSelector extends MouseAdapter
        OverdrawPanel overdrawPanel;
        JPanel loPanel;
        boolean firstPointSet;
        Point2D firstPoint;
        public CableSelector(OverdrawPanel op, JPanel lp)
            overdrawPanel = op;
            loPanel = lp;
            firstPointSet = false;
            overdrawPanel.register(this);
        public void mousePressed(MouseEvent e)
            Point p = e.getPoint();
            Component[] c = loPanel.getComponents();
            Rectangle r;
            for(int j = 0; j < c.length; j++)
                r = c[j].getBounds();
                if(r.contains(p))
                    if(!firstPointSet)
                        firstPoint = new Point2D.Double(r.getCenterX(), r.getCenterY());
                        firstPointSet = true;
                    else
                        Point2D p2 = new Point2D.Double(r.getCenterX(), r.getCenterY());
                        overdrawPanel.addCable(firstPoint, p2);
                        firstPointSet = false;
    }

  • Problems with drawRect and drawLine in connjunction with using scaling

    Hi,
    we have trouble with drawing rects and lines when using scaling. Using Java 1.6 Update 6 results in a different drawing than using 1.6_11. Lines and rects are sonetimes shifted one pixel with 1.6_11 while everything is ok using 1.6_06.
    public void paint(Graphics g) // paint method of a subclass of Canvas
       ((Graphics2D)g).scale (0.99, 0.99);
       g.setColor(Color.black);
       for (int i=30; i<900; i+=31)
       g.drawRect (10, i, 150, 21);
       g.drawLine (10, i, 160, i);
    }If scaling is deactivated, then the lines and rects are correctly positioned.
    Any idea? Thank you very much in advance.

    Hi Les,
    Thank you! Yes, you are right. I have just found that topic you mean at [http://forums.sun.com/thread.jspa?forumID=20&threadID=5409536|http://forums.sun.com/thread.jspa?forumID=20&threadID=5409536]. Unfortunately the answer there is a little bit frustrating ;-(
    I wonder why such a fundamental functionality does not work correctly for so many updates of Java. We are involved in engineering charting software and in this area it is strongly recommended to have exact diagrams. Otherwise the general appearance suffers too much.
    What would be the best way to proceed? Send a report to Sun's bug database?

  • Problem in java.awt.print

    Hi here is my code .
    I am generating page dynamically and passing to printer.
    Printing Functionalities working file. But I am taking some data from database (Access). And in this code for example i have 4 records in Database and i am generating 4 pages (each page for resord).
    I am getting only 2 records. And for other two records i am getting blank page.
    Reason is My ResultSet object is moving to next record twice.
    I mean if i have 6 records i get only 3 pages.
    If i have 10 records i get only 5 pages and If i have 1 record i dont get any page.
    How shall i solve this problem.
    Thanx in advance.
    import java.awt.*;
    import java.awt.print.*;
    import java.sql.*;
    public class SubbuBook extends Thread implements Printable {
    Connection con;
         Statement stmt;
         static ResultSet rsValue;
         public void run() {
              dataConnection();
              PrinterJob job = PrinterJob.getPrinterJob();
              Book bk = new Book();
              job.setPageable(bk);
              if (job.printDialog()) {
         try {
              bk.append(new SubbuBook(),job.defaultPage(), 4);
              job.print();
              }catch (Exception e) {
              System.out.println("Exception "+e);
         System.exit(0);
    public int print(Graphics g, PageFormat pf, int pageIndex) throws PrinterException {
         Font fntHeading = new Font("Helvetica",Font.BOLD,24);
    Font fntRow = new Font("Helvetica",Font.PLAIN,14);
         try{
         if(rsValue.next()) {
              g.setFont(fntHeading);
              g.setColor(Color.red);
              g.drawString("Main Report",200,100);
              g.setColor(Color.blue);
              g.drawLine(100,150,500,150);
              g.drawLine(100,150,100,500);
              g.drawLine(100,500,500,500);
              g.drawLine(500,100,500,500);
              g.drawLine(200,150,200,500);
              g.setFont(fntRow);
              g.setColor(Color.black);
              g.drawString("Program Id",120,200);
              g.drawString(rsValue.getString("prog_id"),250,200);
              g.drawString("Program Name",120,250);
              g.drawString(rsValue.getString("prog_name"),250,250);
              g.drawString("Artist Name",120,300);
              g.drawString(rsValue.getString("Artist"),250,300);
         }catch(Exception ae) {
         System.out.println("Exception inside Paint"+ae);
         return Printable.PAGE_EXISTS;
    private void dataConnection() {
         try{
         Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
         con=DriverManager.getConnection("jdbc:odbc:artist");
         stmt=con.createStatement();
         rsValue=stmt.executeQuery("select * from artist order by Prog_name");
         System.out.println("Connection is Proper");
         }catch(Exception e){
              System.out.println("Exception at Connection"+e);

    I am not sure this..
    Instead of if pls give while and check:
    try{
    while(rsValue.next()) {
    g.setFont(fntHeading);
    g.setColor(Color.red);
    g.drawString("Main Report",200,100);

  • Bouncing off the wall: Problems with passing/using pointers to classes

    I have a mostly completed "msPaint" (=assigment) program that is driving me nuts!!!
    1. First shape you draw doesn't appear.
    1.5 Draw a shape by clicking twice on Panel, can change shape, color, fill with what buttons you see.
    2. Subsequently only the newest shape appears. Using System.println(); it appears to be drawing as many shapes as it has made, but it doesn't.
    3. I owe much to anyone who helps me, here is complete code. Specifically will ask/reward you to reply to a diff link in which I have dukes, got no answer, and can't reallocate dukes. (=5)
    Thank you very much.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Prog4 extends JApplet implements ActionListener
         //private MainPanel drawingpanel;
         private JPanel top;
         private JPanel left;
         private JPanel bottom;
         private JPanel bottomleft,bottommiddletop,bottommiddle,bottomright;
         //top buttons created
         private JButton first,next,previous,last,help;
         //bottom buttons created
         private JButton custom;
         private JButton white,gray,red,purple,blue,green,yellow,orange;
         private JButton black,darkgray,darkred,darkpurple,darkblue,darkgreen,darkyellow,darkorange;
         private JButton rect,oval,line,solid,hollow,erase;
         private CardLayout drawingscreens;
         private MyShape [] shapes=new MyShape[10];
         private MyShape newshape=new MyShape();     
         private Data information;//=new Data(newshape, shapes);
         private MyPanel temp;//=new MyPanel(information);
         private int thiscard;
         public int x,y;
         //Holder Variable to hold info about shape to be drawn
         int shape;
         int fill;
         int draw;
         int tx,ty,bx,by;
         public void init()
              Container window=getContentPane();
                   window.setLayout(new FlowLayout(0,0,FlowLayout.LEFT));
                   //Top Button Setup
                   first=new JButton("First");
                   first.addActionListener(this);
                   first.setPreferredSize(new Dimension(100,40));
                   next=new JButton("Next");
                   next.addActionListener(this);
                   next.setPreferredSize(new Dimension(100,40));
                   previous=new JButton("Previous");
                   previous.addActionListener(this);
                   previous.setPreferredSize(new Dimension(100,40));
                   last=new JButton("Last");
                   last.addActionListener(this);
                   last.setPreferredSize(new Dimension(100,40));
                   help=new JButton("Help");
                   help.addActionListener(this);
                   help.setPreferredSize(new Dimension(100,40));
                   //TOP PANEL SETUP
                   top=new JPanel();
                   top.setLayout(new FlowLayout(0,0,FlowLayout.LEFT));
                   top.setPreferredSize(new Dimension(800,40));
                   top.setOpaque(true);
                   top.setBackground(Color.white);
                   top.add(first);
                   top.add(next);
                   top.add(previous);
                   top.add(last);
                   top.add(help);
                   window.add(top);
                   //Left Buttons Setup
                   rect=new JButton("Rectangle");
                   rect.setPreferredSize(new Dimension(100,40));
                   rect.addActionListener(this);
                   oval=new JButton("Oval");
                   oval.setPreferredSize(new Dimension(100,40));
                   oval.addActionListener(this);
                   line=new JButton("Line");
                   line.setPreferredSize(new Dimension(100,40));
                   line.addActionListener(this);
                   solid=new JButton("Solid");
                   solid.setPreferredSize(new Dimension(100,40));
                   solid.addActionListener(this);
                   hollow=new JButton("Hollow");
                   hollow.setPreferredSize(new Dimension(100,40));
                   hollow.addActionListener(this);
                   erase=new JButton("Erase");
                   erase.setPreferredSize(new Dimension(100,40));
                   erase.addActionListener(this);
                   //Left Panel Setup
                   left=new JPanel();
                   left.setLayout(new FlowLayout(0,0,FlowLayout.LEFT));
                   left.setPreferredSize(new Dimension(200,600));     
                   left.add(rect);
                   left.add(oval);
                   left.add(line);
                   left.add(solid);
                   left.add(hollow);
                   left.add(erase);
                   window.add(left);// FlowLayout.LEFT);
                   //Middle Setup
                   temp=new panel();
                   temp.setPreferredSize(new Dimension(600,600));
                   temp.setOpaque(true);
                   temp.setBackground(Color.red);
                   temp.addMouseListener(this);
                   window.add(temp);
                   //Panel Listener Initailization
                   for(int i=0; i<shapes.length; i++)
                        shapes=new MyShape();
                   information=new Data(newshape, shapes);
                   temp=new MyPanel(information);
                   Listener panelListener=new Listener(temp, newshape, information);
                   //shapes
                   window.add(temp);
                   temp.addMouseListener(panelListener);
                   //Bottom Buttons Setup
                   int bsize=20; //Int for horz/vert size of buttons
                   //Left Setup, creates a JPanel which displays the current color
                   bottomleft=new JPanel();
                   bottomleft.setPreferredSize(new Dimension(2*bsize,2*bsize));
                   bottomleft.setLayout(new FlowLayout(0,0, FlowLayout.LEFT));
                   bottomleft.setOpaque(true);
                   //Middle Setup creates buttons for each pregenerated color in the top row
                   black=new JButton();
                   black.setPreferredSize(new Dimension(bsize,bsize));
                   black.setOpaque(true);
                   black.setBackground(new Color(0,0,0));
                   black.addActionListener(this);
                   darkgray=new JButton();
                   darkgray.setPreferredSize(new Dimension(bsize,bsize));
                   darkgray.setOpaque(true);
                   darkgray.setBackground(new Color(70,70,70));
                   darkgray.addActionListener(this);
                   darkred=new JButton();
                   darkred.setPreferredSize(new Dimension(bsize,bsize));
                   darkred.setOpaque(true);
                   darkred.setBackground(new Color(180,0,0));
                   darkred.addActionListener(this);
                   darkpurple=new JButton();
                   darkpurple.setPreferredSize(new Dimension(bsize,bsize));
                   darkpurple.setOpaque(true);
                   darkpurple.setBackground(new Color(185,0,185));
                   darkpurple.addActionListener(this);
                   darkblue=new JButton();
                   darkblue.setPreferredSize(new Dimension(bsize,bsize));
                   darkblue.setOpaque(true);
                   darkblue.setBackground(new Color(0,0,150));
                   darkblue.addActionListener(this);
                   darkgreen=new JButton();
                   darkgreen.setPreferredSize(new Dimension(bsize,bsize));
                   darkgreen.setOpaque(true);
                   darkgreen.setBackground(new Color(0,140,0));
                   darkgreen.addActionListener(this);
                   darkyellow=new JButton();
                   darkyellow.setPreferredSize(new Dimension(bsize,bsize));
                   darkyellow.setOpaque(true);
                   darkyellow.setBackground(new Color(176,176,0));
                   darkyellow.addActionListener(this);
                   darkorange=new JButton();
                   darkorange.setPreferredSize(new Dimension(bsize,bsize));
                   darkorange.setOpaque(true);
                   darkorange.setBackground(new Color(170,85,0));
                   darkorange.addActionListener(this);
                   //Adds each button to a Panel
                   bottommiddletop=new JPanel();
                   bottommiddletop.setLayout(new FlowLayout(0,0,FlowLayout.LEFT));
                   bottommiddletop.setPreferredSize(new Dimension(8*bsize,bsize));
                   bottommiddletop.add(black);
                   bottommiddletop.add(darkgray);
                   bottommiddletop.add(darkred);
                   bottommiddletop.add(darkpurple);
                   bottommiddletop.add(darkblue);
                   bottommiddletop.add(darkgreen);
                   bottommiddletop.add(darkyellow);
                   bottommiddletop.add(darkorange);     
                   //Bottom Middle Creates bottom row of colors like top
                   white=new JButton();
                   white.setPreferredSize(new Dimension(bsize,bsize));
                   white.setOpaque(true);
                   white.setBackground(new Color(255,255,255));
                   white.addActionListener(this);
                   gray=new JButton();
                   gray.setPreferredSize(new Dimension(bsize,bsize));
                   gray.setOpaque(true);
                   gray.setBackground(new Color(192,192,192));
                   gray.addActionListener(this);
                   red=new JButton();
                   red.setPreferredSize(new Dimension(bsize,bsize));
                   red.setOpaque(true);
                   red.setBackground(new Color(255,0,0));
                   red.addActionListener(this);
                   purple=new JButton();
                   purple.setPreferredSize(new Dimension(bsize,bsize));
                   purple.setOpaque(true);
                   purple.setBackground(new Color(213,0,213));
                   purple.addActionListener(this);
                   blue=new JButton();
                   blue.setPreferredSize(new Dimension(bsize,bsize));
                   blue.setOpaque(true);
                   blue.setBackground(new Color(0,0,255));
                   blue.addActionListener(this);
                   green=new JButton();
                   green.setPreferredSize(new Dimension(bsize,bsize));
                   green.setOpaque(true);
                   green.setBackground(new Color(0,255,0));
                   green.addActionListener(this);
                   yellow=new JButton();
                   yellow.setPreferredSize(new Dimension(bsize,bsize));
                   yellow.setOpaque(true);
                   yellow.setBackground(new Color(255,255,0));
                   yellow.addActionListener(this);
                   orange=new JButton();
                   orange.setPreferredSize(new Dimension(bsize,bsize));
                   orange.setOpaque(true);
                   orange.setBackground(new Color(244,122,0));
                   orange.addActionListener(this);
                   //Attaches buttons to a panel
                   bottommiddle=new JPanel();
                   bottommiddle.setLayout(new FlowLayout(0,0,FlowLayout.LEFT));
                   bottommiddle.setPreferredSize(new Dimension(8*bsize,bsize));
                   bottommiddle.add(white);
                   bottommiddle.add(gray);
                   bottommiddle.add(     red);
                   bottommiddle.add(purple);
                   bottommiddle.add(blue);
                   bottommiddle.add(green);
                   bottommiddle.add(yellow);
                   bottommiddle.add(orange);     
                   //Creates middle panel for bottom
                   bottom=new JPanel();
                   bottom.setLayout(new FlowLayout(0,0,FlowLayout.LEFT));
                   bottom.setPreferredSize(new Dimension(8*bsize,2*bsize));
                   bottom.add(bottommiddletop);
                   bottom.add(bottommiddle);               
                   //This is for a button on buttom right to make custom colors.
                   //Right Setup creates a button which allows you to make your own color
                   custom=new JButton("More");
                   custom.setPreferredSize(new Dimension(4*bsize,2*bsize));
                   custom.setOpaque(true);
                   bottomright=new JPanel();
                   bottomright.setLayout(new FlowLayout(0,0,FlowLayout.LEFT));
                   bottomright.setPreferredSize(new Dimension(4*bsize,2*bsize));
                   bottomright.add(custom);
                   //The Panel containing current color is added first
                   //Then the two colors panels are added
                   //Then the panel with a custom button is added
                   window.add(bottomleft);
                   window.add(bottom);
                   window.add(bottomright);
         public void actionPerformed(ActionEvent e)
              //Buttons to change colors
              if(e.getSource()==black)
                   bottomleft.setBackground(new Color(0,0,0));
                   newshape.setColor(0,0,0);
              if(e.getSource()==darkgray)
                   bottomleft.setBackground(new Color(70,70,70));
                   newshape.setColor(70,70,70);
              if(e.getSource()==darkred)
                   bottomleft.setBackground(new Color(180,0,0));
                   newshape.setColor(180,0,0);
              if(e.getSource()==darkpurple)
                   bottomleft.setBackground(new Color(185,0,185));
                   newshape.setColor(185,0,185);
              if(e.getSource()==darkblue)
                   bottomleft.setBackground(new Color(0,0,150));
                   newshape.setColor(0,0,150);
              if(e.getSource()==darkgreen)
                   bottomleft.setBackground(new Color(0,140,0));
                   newshape.setColor(0,140,0);
              if(e.getSource()==darkyellow)
                   bottomleft.setBackground(new Color(176,176,0));
                   newshape.setColor(176,176,0);
              if(e.getSource()==darkorange)
                   bottomleft.setBackground(new Color(170,85,0));
                   newshape.setColor(170,85,0);
              if(e.getSource()==white)
                   bottomleft.setBackground(new Color(255,255,255));
                   newshape.setColor(255,255,255);
              if(e.getSource()==blue)
                   bottomleft.setBackground(new Color(0,0,255));
                   newshape.setColor(0,0,255);
              if(e.getSource()==red)
                   bottomleft.setBackground(new Color(255,0,0));
                   newshape.setColor(255,0,0);
              if(e.getSource()==green)
                   bottomleft.setBackground(new Color(0,255,0));
                   newshape.setColor(0,255,0);
              if(e.getSource()==purple)
                   bottomleft.setBackground(new Color(213,0,213));
                   newshape.setColor(213,0,213);
              if(e.getSource()==yellow)
                   bottomleft.setBackground(new Color(255,255,0));
                   newshape.setColor(255,255,0);
              if(e.getSource()==orange)
                   bottomleft.setBackground(new Color(244,122,0));
                   newshape.setColor(244,122,0);
              if(e.getSource()==gray)
                   bottomleft.setBackground(new Color(192,192,192));
                   newshape.setColor(192,192,192);
              //Code for setting shape to draw
              if(e.getSource()==rect)
                   setShapes();
                   rect.setBackground(Color.blue);               
                   newshape.setShape(1);
              if(e.getSource()==line)
                   setShapes();
                   newshape.setShape(0);
                   line.setBackground(Color.blue);
              if(e.getSource()==oval)
                   setShapes();
                   newshape.setShape(2);
                   oval.setBackground(Color.blue);
              //Code for setting to fill or not
              if(e.getSource()==solid)
                   solid.setBackground(Color.blue);
                   hollow.setBackground(Color.gray);
                   newshape.setFill(1);
              if(e.getSource()==hollow)
                   hollow.setBackground(Color.blue);
                   solid.setBackground(Color.gray);
                   newshape.setFill(0);
         public void setShapes()
              rect.setBackground(Color.gray);
              oval.setBackground(Color.gray);
              line.setBackground(Color.gray);
    class Data
         private MyShape newshape;
         private MyShape [] shapes;
         public Data(MyShape a, MyShape [] b)
              newshape=a;
              shapes=b;
         public void drawShapes(Graphics g)
              drawAllShapes(g);
         public void sortShapes()
              for(int t=8; t>=0; t--)
                   shapes[t+1]=shapes[t];
              shapes[0]=newshape;
              System.out.println("Shapes Sorted");
         public void drawAllShapes(Graphics g)
              newshape.reset(true);
              for(int i=9; i>=0; i--)
                   shapes[i].drawShape(g);
              System.out.println("Shapes Drawn??");
    class MyPanel extends JPanel
         private Data information;
         public MyPanel(Data a)
              information=a;
              setPreferredSize(new Dimension(600,600));
              setBackground(Color.blue);
         public void paintComponent(Graphics g)
              super.paintComponent(g);
              information.drawShapes(g);
    class Listener extends MouseAdapter
         int x,y;
         private int [] loc=new int[4];
         int horzL, vertL;
         private boolean clicked=false;
         private boolean sortonce;
         private MyPanel temp;
         private MyShape newshape;
         private Data information;
         private int xt,yt,xl,yl;
         public Listener(MyPanel d, MyShape b, Data c)
              temp=d;
              newshape=b;          
              information=c;
         public void mouseClicked(MouseEvent e)
              if(clicked==false)
                   x=e.getX();
                   y=e.getY();
                   clicked=true;
              else
              if(clicked==true)
                   mouseloc(x,y,e.getX(),e.getY());
                   information.sortShapes();
                   temp.repaint();
                   clicked=false;
         public void mouseloc(int xt,int yt,int xl,int yl)
              loc[0]=xt;
              loc[1]=yt;
              loc[2]=xl;
              loc[3]=yl;
              newshape.setLoc(xt,yt,xl,yl);
              newshape.doDraw(true);
    class MyShape
         private int xL, yL, xR, yR; //Local location ints for this class;
         private int red, blue, green; //Local ints defining this color;
         private int shape,fill; //Local info about shape
         private boolean draw=false; // Determines if Shape will draw
         private boolean setupshape=true;
         public void MyShape()
         public void doDraw(boolean a)
              draw=a;
         public void setLoc(int xt,int yt,int xb,int yb)
              xL=xt;
              yL=yt;
              xR=xb;
              yR=yb;
         public void setColor(int r,int b,int g)
              red=r;
              blue=b;
              green=g;
         public void setShape(int thisshape)
              shape=thisshape;
         public void setFill(int fil)
              fill=fil;
         public void drawShape(Graphics g)
              if(draw==true && setupshape==true)
                   System.out.println("This shape setup");
                   g.setColor(new Color(red,blue,green));
                   switch(shape)
                        case 0: makeLine(g);break;
                        case 1: makeRect(g);break;
                        case 2: makeOval(g);break;
                   setupshape=false;
              else if(draw==true)
                   System.out.println("This shape redrawn");
                   switch(shape)
                        case 0: drawLine(g);break;
                        case 1: drawRect(g);break;
                        case 2: drawOval(g);break;
         public void reset(boolean a)
              setupshape=a;
         public void drawLine(Graphics g)
              g.drawLine(xL,yL,xR,yR);
         public void drawRect(Graphics g)
              if(fill==0)
                   g.drawRect(xL,yL,xR,yR);
              else
                   g.fillRect(xL,yL,xR,yR);
         public void drawOval(Graphics g)
              if(fill==0)
                   g.drawOval(xL,yL,xR,yR);
              else
                   g.fillOval(xL,yL,xR,yR);
         public void makeLine(Graphics g)
              g.drawLine(xL,yL,xR,yR);
         public void makeRect(Graphics g)
              sortvalue();
              if(fill==0)
                   g.drawRect(xL,yL,xR,yR);
              else
                   g.fillRect(xL,yL,xR,yR);
         public void makeOval(Graphics g)
              sortvalue();
              if(fill==0)
                   g.drawOval(xL,yL,xR,yR);
              else
                   g.fillOval(xL,yL,xR,yR);
         public void sortvalue()
                   if(xR<xL)
                   int temp=xR;
                   xR=xL;
                   xL=temp;
              if(yR<yL)
                   int temp=yR;
                   yR=yL;
                   yL=temp;
              yR=(yR-yL);
              xR=(xR-xL);     

    Sorry mate but you need a lot of work....
    I like what you've done but (in my humble opinion) it needs a lot of reworking.
    Your problem is you're not storing the shapes. You've set up an array but you never assign the shapes to it. I would reccomend using a vector. Heres a quick bit of pseudo code.
    Listener class
    mouseClicked method
    if first click
    get mouse x/y
    if second click
    get mouse x/y
    create new MyShape(x1, y1, x2, y2)
    call data.addShape(new MyShape)
    Data class
    constructor
    this.myVector = new Vector()
    addShape(MyShape shape) method
    this.myVector.addElement(shape) -- add new shape
    this.myVector.remove(0) -- remove bottom shape
    drawAllShapes method
    Enumeration enum= this.myVector.elements()
    while(enum.hasMoreElements())
    MyShape shape = (MyShape)enum.nextElement()
    shape.draw()
    Feel free to ask any questions.
    Rob.

  • Problem with repaint() in JPanel

    Hi,
    This is the problem: I cyclically call the repaint()-method but there is no effect of it.
    When does it appear: The problem occurs by calling the repaint()-method of a JPanel -class.
    This is what i am doing: The repaint() is called from a different class which is my GUI. I do this call in an endless loop which is done within a Thread.
    I tried to add a KeyListener to the JPanel-class and there I called the repaint()-method when i press a Key. Then the Panel is repainted.
    so I implemented a "callRepaint"-method in the JPanel-class that does nothing else than call repaint() (just like the keyPressed()-method does). But when i cyclically call this "callRepaint"-method from my GUI nothing happens.
    Now a few codedetails:
    // JPanel-class contains:
    int i = 0;
    public void callRepaint(){
                    repaint();
    public void paintComponent(Graphics g){
            super.paintComponent(g);
            g.drawLine(i++,0,200,200);
    public void keyPressed(KeyEvent e) {
            repaint();                       // This is working
    //GUI-class contains:
    // This method is called cyclically
    public void draw() {
                  lnkJPanelclass.repaint();             // This calling didn't work
                  // lnkJPanelclass.callRepaint();  // This calling didn't work     
    Thanks for your advices in advance!
    Cheers spike

    @ARafique:
    This works fine:
    import java.awt.*;
    import java.awt.event.*;
    import java.util.Date;
    import javax.swing.*;
    public class Test extends JFrame implements ActionListener{
        private JTextField label;
        private Timer timer;
        private Container cont;
        public Test() {
            label = new JTextField("",0);
            timer = new Timer(1000,this);
            cont = getContentPane();
            cont.add(label);
            setSize(250,70);
            setDefaultCloseOperation(3);
            setVisible(true);
            timer.start();
        public void actionPerformed(ActionEvent e){
            label.setText(new Date(System.currentTimeMillis()).toString());
        public static void main(String[] args){
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    new Test();
    }no repaint()/revalidate() needed

  • Problem with drawing in a scrollpane using clipbounds

    Hello
    Setup is a JFrame containing a splitpane with on the left just some config buttons and on the right a scrollpane.
    Inside the scrollpane I want to draw big waveforms.
    This is represented by a long array of 1's and 0's for the Y coordinates.
    On drawing in paintComponents method I allways reconstruct a GeneralPath, based on the Clipbouns returned by the Graphics variable.
    I have to reconstruct the GeneralPath polygon because my data can be millions long. And therefor I have to limit the points that are drawn.
    When I allways reconstruct this GeneralPath, upon scrolling the polygon is shown scrappy, as in the line connecting the points will only be half shown or almost not.
    Resizing the window or just minimize maximize and it is shown ok.
    I do not have this problem when the GeneralPath I construct is only once made upfront and never remade in the paintComponent method.
    But as I need the clipbounds to know which part to construct I need to rebuild this polygon over and over again.
    I have tried to draw it with Line2D.Double but I get almost the same effect, parts of the lines not being drawn ok.
    Below is the code of the Panel inside the ScrollPane responsible for this drawing.
    public class Usr_Test_L extends JPanel
      final static Color bg   = Color.black;
      final static Color fg   = Color.white;
      final static Color wave = Color.red;
      final static Color txt  = Color.green;
      final static Color grid = Color.lightGray;
      private static final BasicStroke SOLID = new BasicStroke(1.0f);
      private static final BasicStroke BOLD  = new BasicStroke(3.0f);
      private double maxX = 0.0;
      private double maxY = 0.0;
      private double gridWidth;
      private double gridHeight;
      private int panelWidth;
      private int panelHeight;
      boolean firstTime = true;
      private double[] xPoints = null;
      private double[] yPoints = null;
      GeneralPath polygon;
      boolean polyOk = false;
      private double waveHeight = 0;
      private boolean gridOn = true;
      private Usr_Test_R scrollPane = null;
      Usr_Test_L(Usr_Test_R scrollPane)
        super(true);
        this.scrollPane = scrollPane;
        buildGui();
      void buildGui()
        setBackground(bg);
        setForeground(fg);
        //Let the user scroll by dragging to outside the window.
        setAutoscrolls(true); //enable synthetic drag events
    //    addMouseMotionListener(this); //handle mouse drags
        repaint();
      private void generateWave(int cycles, double height)
        waveHeight = height;
        xPoints = new double[cycles];
        yPoints = new double[cycles];
        Random r = new Random();
        for ( int i = 0; i < cycles; i++ )
          xPoints[i] = i;
          yPoints[i] = (int)( Math.pow(-1.0,i) ) * ( r.nextInt(2) );
    //      if ( ( i % 10 ) == 0 ) yPoints[i] = height;
    //      else                   yPoints[i] = height + gridHeight;
    //      System.err.println("P"+i+"("+xPoints[i]+","+yPoints[i]+")");
      private void generateSineWave(int cycles, double height)
        waveHeight = height;
        xPoints = new double[cycles];
        yPoints = new double[cycles];
        double j, xval, yval;
        j = 0;
        int i = 0;
        while (i < cycles)
          xval = j;
          yval = Math.sin(j) * 10.0 + 20;
          xPoints[i] = xval;
          yPoints[i] = yval;
          i++;
          j += 0.01;
      public Dimension getPreferredSize()  // <== used because of revalidate, parent scrollpane asks preferredsize ..., so we overruled the method
        return new Dimension(panelWidth, panelHeight);
      public void drawLine(int cycles, int height)
        generateWave(cycles,(int)(gridHeight*height));
        maxX = gridWidth  * cycles;
        maxY = gridHeight * cycles;
        while ( maxX > panelWidth  ) panelWidth  *= 2;
        while ( maxY > panelHeight ) panelHeight *= 2;
    //    polyOk = buildPolygon();
        revalidate();
        repaint();
      public void drawSine(int cycles, int height)
        generateSineWave(cycles,(int)(gridHeight*height));
        maxX = gridWidth  * cycles;
        maxY = gridHeight * cycles;
        while ( maxX > panelWidth  ) panelWidth  *= 2;
        while ( maxY > panelHeight ) panelHeight *= 2;
    //    polyOk = buildPolygon();
        revalidate();
        repaint();
      public void zoomIn()
        gridWidth  *= 2;
        gridHeight *= 2;
        repaint();
      public void zoomOut()
        gridWidth  /= 2;
        gridHeight /= 2;
        repaint();
      private void initPanel()
        Dimension d = getSize();
        panelWidth = d.width;
        panelHeight = d.height;
        maxX = panelWidth;
        maxY = panelHeight;
        gridWidth  = panelWidth / 8;
        gridHeight = panelHeight / 8;
        scrollPane.getHorBar().setUnitIncrement((int)(gridWidth*3));           // times 2 otherwise no clipbounds are allways too small
        scrollPane.getHorBar().setBlockIncrement((int)(gridWidth*3));
        scrollPane.getVerBar().setUnitIncrement((int)(gridHeight*3));
        scrollPane.getVerBar().setBlockIncrement((int)(gridHeight*3));
      public void grid()
        if ( gridOn ) gridOn = false;
        else          gridOn = true;
      private void drawGrid(Graphics2D g2, Rectangle clip)
        if ( ! gridOn ) return;
        // draw grid
        g2.setPaint(grid);
        // new good grid
        double startX = clip.getX() + ( gridWidth - ( clip.getX() % gridWidth ) );
        double endX   = clip.getX() + clip.getWidth();
        double startY = clip.getY() + ( gridHeight - ( clip.getY() % gridHeight ) );
        double endY   = clip.getY() + clip.getHeight();
        double y = startY;
        while ( startX < endX )
          while ( y < endY )
            g2.draw(new Rectangle2D.Double( startX - 0.5, y - 0.5, 1.0, 1.0 ));
            y += gridHeight;
          y = startY;
          startX += gridWidth;
      private boolean buildPolygon(Rectangle clip)
        if ( xPoints != null && yPoints != null )
          polygon = new GeneralPath(GeneralPath.WIND_NON_ZERO,xPoints.length);
        else
          return false;
        double x = xPoints[0] * gridWidth;
        double y = waveHeight;
        polygon.moveTo((float)xPoints[0], (float)yPoints[0]);
        for ( int index = 0; index < xPoints.length; index++ )
          x = xPoints[index] * gridWidth;
          y = waveHeight + ( yPoints[index] * gridHeight );
          if ( x > ( clip.getX() + clip.getWidth() ) ) break;
          if ( y < clip.getY() || y > ( clip.getY() + clip.getHeight() ) ) continue;
          if ( x < clip.getX() || x > ( clip.getX() + clip.getWidth()  ) ) continue;
          polygon.lineTo((float)x, (float)y);
        return true;
      private boolean drawLines(Graphics2D g2, Rectangle clip)
        if ( xPoints == null || yPoints == null ) return false;
        double x1 = xPoints[0] * gridWidth;
        double y1 = waveHeight;
        double x2, y2;
        boolean cont = false;
        for ( int index = 0; index < xPoints.length; index++ )
          x2 = xPoints[index] * gridWidth;
          y2 = waveHeight + ( yPoints[index] * gridHeight );
          if ( x1 > ( clip.getX() + clip.getWidth() ) )
            break;
          if ( x2 > ( clip.getX() + clip.getWidth() ) )
            break;
          if ( y2 < clip.getY() || y2 > ( clip.getY() + clip.getHeight() ) )
            cont = true;
          if ( x2 < clip.getX() || x2 > ( clip.getX() + clip.getWidth()  ) )
            cont = true;
          if ( ! cont ) g2.draw(new Line2D.Double(x1,y1,x2,y2));
          x1 = x2;
          y1 = y2;
          cont = false;
        return true;
      public void paintComponent(Graphics g)
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        if ( firstTime )
          initPanel();
          firstTime = false;
        // get clip bounds
        Rectangle clip = new Rectangle();
        clip = g2.getClipBounds(clip);
        // draw grid
        drawGrid(g2,clip);
        // draw waveform
        g2.setPaint(wave);
        g2.setStroke(SOLID);
        if ( buildPolygon(clip) ) g2.draw(polygon);
    //    if ( polyOk ) g2.draw(polygon);
    //    drawLines(g2,clip);
      }

    I have added a standalone testcase for ease.
    import java.awt.*;
    import java.awt.geom.*;
    import javax.swing.*;
    import java.util.*;
    public class Scrolling {
        public static void main(String[] args) {
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new JScrollPane(new DrawPanel()));
            f.setSize(400,300);
            f.setLocationRelativeTo(null);
            f.setVisible(true);
    class DrawPanel extends JPanel {
        private GeneralPath polygon = new GeneralPath(GeneralPath.WIND_NON_ZERO,1000);
        private int[] coords;
        public DrawPanel() {
            setBackground(Color.white);
            buildPolygon();
        private void buildPolygon() {
         coords = new int[2000];
            Random r = new Random();
            int height = 80;
            int gridHeight = 10;
            int gridWidth = 10;
         int j = 0;       
            for (int i=0, dir=-1; i<1000; i++, dir=-dir) {
                coords[j++] = i * gridWidth;
                coords[j++] = height + dir*gridHeight*r.nextInt(2);
        private void drawPolygonClipped(Rectangle clip)
    polygon = new GeneralPath(GeneralPath.WIND_NON_ZERO,1000);
           polygon.moveTo(0,80);
           for ( int i = 0; i < 2000; i++ )
          if ( coords[i] > ( clip.getX() + clip.getWidth() ) ) break;
          if ( coords[i+1] < clip.getY() || coords[i+1] > ( clip.getY() + clip.getHeight() ) ) continue;
          if ( coords[i] < clip.getX() || coords[i] > ( clip.getX() + clip.getWidth()  ) ) continue;
                polygon.lineTo(coords[i++],coords);
    private void drawPolygon(Rectangle clip)
    polygon = new GeneralPath(GeneralPath.WIND_NON_ZERO,1000);
         polygon.moveTo(0,80);
         for ( int i = 0; i < 2000; i++ )
              polygon.lineTo(coords[i++],coords[i]);
    protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D)g;
         Rectangle clip = new Rectangle();
         g.getClipBounds(clip);
         drawPolygonClipped(clip);
         //drawPolygon(clip);
    g2.draw(polygon);
    public Dimension getPreferredSize() {
    return new Dimension(1500,500);

  • Problem on drawin a graph

    I'm a just beginner in Swing.I want to draw a graph on a frame.My problem is.....:in the o/p window graph is just become disable afterit came.it will reappear whwn we maximize thhe o/p window...my part of code is following:
    public void paint(Graphics g) {//main graph drawing part
              super.paint(g);
              Graphics2D g2 = (Graphics2D)g;
              g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
              for(i=0;i<ss2;i++){//assigning the the values of FROM node and TO node
                   pf=p[Integer.parseInt(str2[i][0])];
                   pt[i]=p[Integer.parseInt(str2[i][2])];
              for(i=0;i<ss2;i++){//to print the value like a,b,c...
                   xf=pf[i].x;
                   yf=pf[i].y;
                   xt=pt[i].x;
                   yt=pt[i].y;
                   xm=(xf+xt*3)/4;
                   ym=((yf+yt*3)/4)-5;
                   sssss=str2[i][1].charAt(0);
                   g2.setColor(Color.black);
                   if(xf==xt&&yf==yt){
                        g2.drawArc(xf,yf,35,20,0,360);
                        g2.drawString(Character.toString(sssss),xf+15,yf+12);
                   else{
                        g2.drawLine(xf,yf,xt,yt);
                        g2.setColor(Color.black);
                        g2.drawString(Character.toString(sssss),xm,ym);
                        g2.fillOval(m,n,7,7);
              for(i=0;i<sc1;i++) {//for loop to draw the circle class to draw circles
                   int _x;
                   int _y;
                   _x=(p[i].x-10);
                   _y=(p[i].y-10);
                   if(str1[i][3].equals("1")){
                   g2.setColor(Color.PINK);
                   g2.fillOval(_x, _y,20,20);
                   x=0;y=0;
              else if(str1[i][3].equals("2")){
                   g2.setColor(Color.CYAN);
                   g2.fillOval(_x, y,20,20);x=0;_y=0;
              else if(str1[i][3].equals("4")){
                   g2.setColor(Color.YELLOW);
                   g2.fillOval(_x, y,20,20);x=0;_y=0;
              else{
                   g2.setColor(Color.ORANGE);
                   g2.fillOval(_x, y,20,20);x=0;_y=0;
              for(i=0;i<sc1;i++){//to put the node name like 1,2...i'll changed it to Q0,Q1,... later
                   g2.setColor(Color.BLACK);
                   g2.drawString(Integer.toString(i),p[i].x,p[i].y);

    Comments:
    If you had gone through the painting tutorial linked, you would know that custom painting is not normally performed on a JFrame. And knowing that, you would find no reason to extend JFrame.
    If you had taken a look at the API you would know that JFrame doesn't have a method paintComponent.
    If you had gone through the Swing tutorial linked, you would know about concurrency in Swing, and that the GUI should be launched on the EDT.
    So. With the wealth of knowledge already available in the tutorials, do you really think forum members should waste their time teaching you the basics? Please go through the changed code and post back what you conclude about the differences that make it work.
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
    public class FrameTest {
       int px, py, ox, oy;
       JFrame frame;
       JPanel panel;
       FrameTest(String title, int x1, int y1, int x2, int y2){
          frame = new JFrame(title);
          px = x1;
          py = y1;
          ox = x2;
          oy = y2;
       private void makeUI() {
          panel = new JPanel() {
             public void paintComponent(Graphics g){
                super.paintComponent(g);
                g.drawLine(px, py, ox, oy);
          frame.setContentPane(panel);
          frame.setSize(300, 300);
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.setVisible(true);
       public static void main(String args[]) {
          SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                new FrameTest("Show", 10, 10, 100, 100).makeUI();
    }db

  • Is there any problems in IE if using RMI.?

    Hello buddies,
    this is my 3rd attempt to get answer. before it i tried 2 times but didn't get answered.
    actually i m making a chat application. in that there is a canvas on which we can draw something and send it to all users. i make an applet and from within the applet i m calling a frame. all this awt components like canvas and buttons etc. displays in the frame. applet is just a platform do call the frame. i m using RMI to do the chat. i tried to run it first in appletviewer and it works fine. but when i tried to run in IE from <applet> tag no frame is displays. i am trying to solve it from last 20 days but still unsolved. here is the code if anybody wishes to try it.
    // clinet frame...
    import java.rmi.*;
    import java.rmi.server.*;
    import canvas.Drawer;
    import java.awt.*;
    import java.applet.*;
    import java.applet.Applet;
    import java.awt.event.*;
    import java.util.*;
    import ru.zhuk.graphics.*;
    /*<applet code="ChatClient" width=600 height=300>
    </applet>
    public class ChatClient extends Frame implements IChatClient,ActionListener,MouseListener,MouseMotionListener
         // GLOBAL VARIABLES USED IN THE PROGRAMME...
         boolean flag=false;
         int n;
         String str="";
         String Coord=null;
         IChatService service=null;
         FrameApplet fa=null;
         TextField servername,serverport,username;
         Button connect,disconnect;
         TextField message;
         Button send,sendText;
         TextArea fromserver;
         int i=0,j=0;
         int x[] = new int[1000];
         int y[] = new int[1000];
         Drawer canvas;
         boolean connected=false;
         String title,user="";
         // Class Members //
         public ChatClient()
         public ChatClient(String str)
              super(str);
              setBounds(50,20,600,450);
              setLayout(new FlowLayout(FlowLayout.CENTER,45,10));
              title=str;
              setStatus();
              // Create controls //
              add(new Label("Chat Server Name : "));
              servername=new TextField(20);
              add(servername);
              servername.setText("localhost");
              add(new Label("Chat Server Port : "));
              serverport=new TextField(20);
              add(serverport);
              serverport.setText("900");
              add(new Label("Your User Name : "));
              username=new TextField(20);
              add(username);
              username.setText("Umesh");
              connect=new Button("Connect");
              connect.addActionListener(this);
              add(connect);
              disconnect=new Button("Disconnect");
              disconnect.addActionListener(this);
              add(disconnect);
              message=new TextField(30);
              add(message);
              sendText=new Button("Send Text");
              sendText.addActionListener(this);
              add(sendText);
              fromserver=new TextArea(10,50);
              add(fromserver);
              fromserver.setEditable(false);
    canvas = new Drawer();
              canvas.setSize(250,250);
              canvas.setBackground(Color.cyan);
              add(canvas);
              canvas.addMouseListener(this);
              canvas.addMouseMotionListener(this);
              send=new Button("Send");
              send.addActionListener(this);
              add(send);
              try
                   UnicastRemoteObject.exportObject(this);
              catch(Exception e)
              setVisible(true);
              for(j=0;j<1000;j++)
                   x[j]=0;
                   y[j]=0;
              Coord = new String();
              Coord = "";
    //          fa=new FrameApplet();
         public void mousePressed(MouseEvent me){}
         public void mouseReleased(MouseEvent me)
              Coord = Coord + "r";
         public void mouseClicked(MouseEvent me){}
         public void mouseEntered(MouseEvent me){}
         public void mouseExited(MouseEvent me){}
         public void mouseDragged(MouseEvent me)
              if (Coord == "")
                   Coord = me.getX() + "," + me.getY();
              else
                   Coord = Coord + " " + me.getX() + "," + me.getY();
         public void mouseMoved(MouseEvent me){}
         // RMI connection //
         private void connect()
              try
                   service = (IChatService)Naming.lookup("rmi://pcname/ChatService");
                   service.addClient(this);
                   connected=true;
                   setStatus();
                   user=username.getText();
                   Coord = "";
              catch(Exception e)
                   fromserver.append("Error Connecting ...\n" + e);
                   System.out.println(e);
                   connected=false;
                   setStatus();
                   service=null;
         private void disconnect()
              try
                   if(service==null)
                        return;
                   service.removeClient(this);
                   service=null;
              catch(Exception e)
                   fromserver.append("Error Connecting ...\n");
              finally
                   connected=false;
                   setStatus();
         private void setStatus()
              if(connected)
                   setTitle(title+" : Connected");
              else
                   setTitle(title+" : Not Connected");
         // IChatClient methods //
         public String getName()
              return user;
         public void sendMessage(String msg)
              fromserver.append(msg+"\n");
         public void SendCanvasObject(String str)
              this.str = str;
              fromserver.append(str + "\n");
              Graphics g = canvas.getGraphics();
              paint(g);
         // Actionlistener //
         public void actionPerformed(ActionEvent e)
              if(e.getSource()==connect)
                   connect();
                   if(connected)
                        servername.setEnabled(false);
                        serverport.setEnabled(false);
                        username.setEnabled(false);
                        connect.setEnabled(false);
                        Coord = "";
              else
              if(e.getSource()==disconnect)
                   disconnect();
                   servername.setEnabled(true);
                   serverport.setEnabled(true);
                   username.setEnabled(true);
                   connect.setEnabled(true);
              else
              if(e.getSource()==send)
                   flag = true;
                   if(service==null)
                        return;
                   try
                        fromserver.append("Sending an image...\n");
                        service.SendCanvasObject(this,Coord);
                        i=0;
                        for(j=0;j<1000;j++)
                             x[j]=0;
                             y[j]=0;
                        Coord = "";
                        fromserver.append("\n" + "Image Sent...");
                   catch(RemoteException re)
                        fromserver.append("Error Sending Message ...\n" + re);
                   catch(Exception ee)
                        fromserver.append("Error Sending Message ...\n" + ee);
              else
              if(e.getSource()==sendText)
                   if(service==null)
                        return;
                   try
                        service.sendMessage(this,message.getText());
                        message.setText("");
                   catch(RemoteException exp)
                        fromserver.append("Remote Error Sending Message ...\n" + exp);
                   catch(Exception ee)
                        fromserver.append("Error Sending Message ...\n" + ee);
         public void paint(Graphics g)
              if(flag==true)
                   i=0;
                   StringTokenizer stoken = new StringTokenizer(str,"r");
                   String strin = "";
                   while(stoken.hasMoreTokens())
                        strin = stoken.nextToken();
                        fromserver.append("\n" + strin + "\n");
                        StringTokenizer stoken1 = new StringTokenizer(strin," ");
                        String strin1 = "";
                        j=0;
                        while(stoken1.hasMoreTokens())
                             strin1 = stoken1.nextToken();
                             fromserver.append("\n" + strin1 + "\n");
                             x[j]=Integer.parseInt(strin1.substring(0,strin1.indexOf(",")));
                             y[j]=Integer.parseInt(strin1.substring(strin1.indexOf(",")+1,strin1.length()));
                             j++;
                        for(int k=0;k<j-1;k++)
                             g.drawLine(x[k],y[k],x[k+1],y[k+1]);     
                   i++;
    import java.rmi.*;
    import java.rmi.server.*;
    import canvas.Drawer;
    import java.util.*;
    import ru.zhuk.graphics.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.*;
    public class FrameApplet extends Applet implements ActionListener
         ChatClient f;
         public void init()
              Button b = new Button("Start Chat");
              b.addActionListener(this);
              add(b);
         public void actionPerformed(ActionEvent ae)
              f=new ChatClient("Chat");
              f.show();
              f.setSize(400,400);
    here is html file which i calls from IE
    <html>
    <title>Micky Chat</title>
    <body>
    <br>
    <br>
    <center>
    <applet code="FrameApplet.class" width=200 height=200>
    </applet>
    </center>
    </body>
    </html>
    and at last a shocking thing is it is runs in Netscape displaying frames but not calling paint method.
    pls. help me
    thanks a lot
    umesh

    Hi Umesh!
    Sorry that I cannot be too concrete about that since it has to be centuries ago when I fell over this problem.
    As far as I can remember, the JDK provided by MS has no RMI built-in. These was probably one of the main reasons why Sun sued Microsoft concering its handling of Java.
    Afterwards MS released a path for its Java Runtime that included RMI support, but AFAIK they never included it in the standard package. So much luck when searching for the ZIP! (-;
    A little bit of googling might help, e.g.:
    http://groups.google.com/groups?hl=de&lr=&ie=UTF-8&oe=UTF-8&threadm=37f8ddf6.4532124%40news.online.no&rnum=17&prev=/groups%3Fq%3Dmicrosoft%2Bjvm%2Brmi%2Bsupport%26start%3D10%26hl%3Dde%26lr%3D%26ie%3DUTF-8%26oe%3DUTF-8%26selm%3D37f8ddf6.4532124%2540news.online.no%26rnum%3D17
    cheers,
    kdi

  • Question about drawLIne(x1,y1,x2,y2) and repaint()

    i am doing this project, which i suppose to use drawLine and repaint() to generate graphs. my problem is, every time i hit a new button it will call the repaint() then my old graph is gone, only the new graph is left.
    for example
    i have 4 buttons. movesouth() movenorth() moveeast() movewest()
    when i hit movesouth two times there should be a staight line, when i hit movewest() my old graph is gone() it only left me with 1 unit to west cuz i have repaint() inside my actionPerformed function, my question is: is there a way that i can redraw these line without calling repaint () ? cuz repaint is kinda like redraw the new stuff and forget about the old ones, however i would like to keep the old one while adding the new graph to it.
    your suggestions would be great appreciated.

    well of course, your Graphics-Object is of the type Graphics2D, you just need a cast so that the compiler is happy ;-)
    Its the same Graphics2D object/instance as withought the cast...
    lg Clemens

  • Having a problem saving the graphics on a canvas.

    I'm having a problem saving graphics on a canvas. It draws on the canvas but when another window comes up the graphics disappear. I put in a method to take the graphics on the canvas and repaint it with the graphics. But this comes up blank. So I don't know why this is happening. It is probably the paint method but I don't know why. If anyone has any ideas could you please respond because I have had this problem for ages now and it's driving me mad and I have to get this finished or I'm going to be a lot of trouble. I'll show you the code for the class I am concerned with. It is long but most of it can be disregarded. The only parts which are relevent are the paint method and where the drawline e.t.c are called which is in the mouse release
    package com.project.CSSE4;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.ImageFilter;
    import java.awt.image.CropImageFilter;
    import java.awt.image.FilteredImageSource;
    import java.io.*;
    import java.util.*;
    import java.net.*;
    import javax.swing.*;
    import java.sql.*;
    public class CanvasOnly extends JPanel
           implements MouseListener, MouseMotionListener
       public static final int line = 1;
       public static final int freehand = 2;
       public static final int text = 3;
       public static final int mode_paint = 0;
       public static final int mode_xor = 1;
       public Color drawColor;
       public int drawThickness = 1;
       public int drawType = 0;
       public boolean fill = false;
       private boolean dragging = false;
       public int oldx = 0;
       public int oldy = 0;
       private int rectangleWidth;
       private int rectangleHeight;
       private tempLine draftLine;
       private tempText draftText;
       public Canvas pad;
       public static final Font defaultFont =
         new Font("Helvetica", Font.BOLD, 14);
       protected boolean floatingText = false;
       boolean showingPicture;
       protected Image offScreen;
       public JTextArea coor;
       public JButton writeIn;
       Connection connection;
       String codeLine;
       int x = 0;
       int y = 0;
       public CanvasOnly()
           try
                Class.forName("com.mysql.jdbc.Driver").newInstance();
           }catch( Exception e)
                 System.err.println("Unable to find and load driver");
                 System.exit(1);
            pad = new Canvas();
            pad.setBackground(Color.white);
            pad.setVisible(true);
            pad.setSize(400, 400);
           coor = new JTextArea(15, 15);
           writeIn = new JButton("load TExt");
           writeIn.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent event1)
                     try
                   Statement statement = connection.createStatement();
                   ResultSet rs = statement.executeQuery("SELECT * FROM submit WHERE file_name = 'cmd.java'");
                   rs.next();
                   String one1 = rs.getString("student_id");
                   //System.out.println("one1 :" + one1);
                   String two1 = rs.getString("file_name");
                   //System.out.println("two1 : " + two1);
                    InputStream textStream = rs.getAsciiStream("file");
                    BufferedReader textReader = new BufferedReader(
                                     new InputStreamReader(textStream));
                    codeLine = textReader.readLine();
                    x = 0;
                    y = -12;
                    while(codeLine != null)
                        y = y + 12;
                        //fileText.append( line + "\n");
                        //canvasPad.drawTheString(line, x, y);
                        drawText(Color.black, x, y, codeLine, mode_paint);
                        codeLine = textReader.readLine();
                     textReader.close();
                    pad.setSize(400, y);
                    Timestamp three1 = rs.getTimestamp("ts");
                    //System.out.println(three1);
                    textReader.close();
                    rs.close();
              }catch (SQLException e)
                System.err.println(e);
              catch(IOException ioX)
                System.err.println(ioX);
            //setSize(300,300);
            drawColor = Color.black;
            pad.addMouseListener(this);
         pad.addMouseMotionListener(this);
         offScreen = null;
       public Image getContents()
         // Returns the contents of the canvas as an Image.  Only returns
         // the portion which is actually showing on the screen
         // If the thing showing on the canvas is a picture, just send back
         // the picture
         if (showingPicture)
             return (offScreen);
         ImageFilter filter =
             new CropImageFilter(0, 0, getWidth(), getHeight());
         Image newImage =
             createImage(new FilteredImageSource(offScreen.getSource(),
                                  filter));
         return(newImage);
        public void setImage(Image theImage)
         // Fit it to the canvas
         offScreen = theImage;
         repaint();
         showingPicture = true;
        synchronized public void paint(Graphics g)
         int width = 0;
         int height = 0;
         //The images are stored on an off screen buffer.
            //offScreen is the image declared at top
         if (offScreen != null)
                  //intislise the widt and heigth depending on if showingpicture is true
              if (!showingPicture)
                       width = offScreen.getWidth(this);
                       height = offScreen.getHeight(this);
                   //width = getWidth(this);
                   //height = getHeight(this);  //offScreen
              else
                   //width = pad.getSize().width;
                   //height = getSize().height;
                   width = pad.getWidth();
                   //width = getSize().width;
                   height = pad.getHeight();
                   //height = getSize().height;
                    //Draws as much of the specified image as has already
                    //been scaled to fit inside the specified rectangle
                    //The "this" is An asynchronous update interface for receiving
                    //notifications about Image information as the Image is constructed
    //This is causing problems
              g.drawImage(offScreen, 0, 0, width, height, pad);
              g.dispose();
         //clear the canvas with this method
        synchronized public void clear()
         // The maximum size of the usable drawing canvas, for now, will be
         // 1024x768
         offScreen = createImage(1024, 768);
         //Creates an off-screen drawable image to be used for double buffering
         pad.setBackground(Color.white);
         //Set the showingPicture to false for paint method
         showingPicture = false;
         repaint();
         synchronized public void drawLine(Color color, int startx, int starty,
                              int endx, int endy, int thickness,
                              int mode)
         int dx, dy;
         Graphics g1 = pad.getGraphics();
         Graphics g2;
         //if image is not intialised to null
         //the getGraphics is used for freehand drawing
         //Image.getGraphics() is often used for double buffering by rendering
            //into an offscreen buffer.
         if (offScreen != null)
             g2 = offScreen.getGraphics();
         else
             g2 = g1;
            //mode is put into the method and XOR is final and equal to 1
         if (mode == this.mode_xor)
                  //calls the setXOR mode for g1 and g2
                  //Sets the paint mode of this graphics context to alternate
                    //between this graphics context's current color and the
                    //new specified color.
              g1.setXORMode(Color.white);//This will
              g2.setXORMode(Color.white);
         else
                  //Sets this graphics context's current color to the
                    //specified color
              g1.setColor(color);
              g2.setColor(color);
         if (endx > startx)
             dx = (endx - startx);
         else
             dx = (startx - endx);
         if (endy > starty)
             dy = (endy - starty);
         else
             dy = (starty - endy);
         if (dx >= dy)
              starty -= (thickness / 2);
              endy -= (thickness / 2);
         else
              startx -= (thickness / 2);
              endx -= (thickness / 2);
         for (int count = 0; count < thickness; count ++)
              g1.drawLine(startx, starty, endx, endy);
              g2.drawLine(startx, starty, endx, endy);
              if (dx >= dy)
                  { starty++; endy++; }
              else
                  { startx++; endx++; }
            //Disposes of this graphics context and releases any system
            //resources that it is using.
         g1.dispose();
         g2.dispose();
         //This method is not causing trouble
         synchronized public void drawText(Color color, int x, int y,
                String text, int mode)
         Graphics g1 = pad.getGraphics();
         Graphics g2;
         if (offScreen != null)
             g2 = offScreen.getGraphics();
         else
             g2 = g1;
         if (mode == this.mode_xor)
              g1.setXORMode(Color.white);
              g2.setXORMode(Color.white);
         else
              g1.setColor(color);
              g2.setColor(color);
         g1.setFont(new Font("Times Roman", Font.PLAIN, 10));
         g2.setFont(new Font("Times Roman", Font.PLAIN, 10));
         g1.drawString(text, x, y);
         g2.drawString(text, x, y);
         g1.dispose();
         g2.dispose();
          //connect to database
      public void connectToDB()
        try
           connection = DriverManager.getConnection(
           "jdbc:mysql://localhost/submissions?user=root&password=football");
                     //may have to load in a username and password
                                                     //code "?user=spider&password=spider"
        }catch(SQLException connectException)
           System.out.println("Unable to connect to db");
           System.exit(1);
      //use this method to instatiate connectToDB method
      public void init()
           connectToDB();
        protected void floatText(String text)
         draftText = new tempText(this.drawColor,
                            this.oldx,
                            this.oldy,
                                        text);
         this.floatingText = true;
        //nothing happens when the mouse is clicked
        public void mouseClicked(MouseEvent e)
        //When the mouse cursor enters the canvas make it the two
        //straigth lines type
        public void mouseEntered(MouseEvent e)
         pad.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
        //When mouse exits canvas set to default type
        public void mouseExited(MouseEvent E)
         pad.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
        //used for creating the shapes and positioning thetext
        public void mousePressed(MouseEvent e)
             // Save the coordinates of the mouse being pressed
         oldx = e.getX();
         oldy = e.getY();
         // If we are doing lines, rectangles, or ovals, we will show
         // draft lines to suggest the final shape of the object
         //Draw type is a publc int which can be changed
         if (drawType == this.line)
            draftLine = new tempLine(drawColor, oldx, oldy, oldx,
                                 oldy, drawThickness);
            // Set the draw mode to XOR and draw it.
            drawLine(draftLine.color, draftLine.startx,
            draftLine.starty, draftLine.endx,
            draftLine.endy, drawThickness, this.mode_xor);
        //mouse listener for when the mouse button is released
        public void mouseReleased(MouseEvent e)
             if (drawType == this.line)
              // Erase the draft line
              drawLine(draftLine.color, draftLine.startx, draftLine.starty,
                    draftLine.endx, draftLine.endy, drawThickness,
                    this.mode_xor);
              // Add the real line to the canvas
              //When the imput changes to "mode_paint" it is drawen
              //on the canvas
              drawLine(drawColor, oldx, oldy, e.getX(), e.getY(),
                    drawThickness, this.mode_paint);
              dragging = false;
         else if (drawType == this.text)
              if (floatingText)
                   // The user wants to place the text (s)he created.
                   // Erase the old draft text
                   drawText(drawColor, draftText.x, draftText.y,
                                            draftText.text, this.mode_xor);
                       String str = Integer.toString(e.getX());
                       String str1  = Integer.toString(e.getY());
                       coor.append(str + " " + str1 + "\n");
                   // Set the new coordinates
                   draftText.x = e.getX();
                   draftText.y = e.getY();
                   // Draw the permanent text
                   drawText(drawColor, draftText.x, draftText.y,
                         draftText.text, this.mode_paint);
                   floatingText = false;
         public void mouseDragged(MouseEvent e)
            if (drawType == this.freehand)
              drawLine(drawColor, oldx, oldy, e.getX(), e.getY(),
                    drawThickness, this.mode_paint);
              oldx = e.getX();
              oldy = e.getY();
         else
             dragging = true;
         if (drawType == this.line)
            // Erase the old draft line
            drawLine(draftLine.color, draftLine.startx, draftLine.starty,
              draftLine.endx, draftLine.endy, drawThickness,
              this.mode_xor);
            // Draw the new draft line
            draftLine.endx = e.getX();
            draftLine.endy = e.getY();
            drawLine(draftLine.color, draftLine.startx, draftLine.starty,
              draftLine.endx, draftLine.endy, drawThickness,
              this.mode_xor);
         public void mouseMoved(MouseEvent e)
             if (floatingText)
              // When the user has entered some text to place on the
              // canvas, it remains sticky with the cursor until another
              // click is entered to place it.
              // Erase the old draft text
              drawText(drawColor, draftText.x, draftText.y,
                                draftText.text, this.mode_xor);
              // Set the new coordinates
              draftText.x = e.getX();
              draftText.y = e.getY();
              // Draw the new floating text
              drawText(drawColor, draftText.x, draftText.y,
                        draftText.text, this.mode_xor);
         //declare  a class for the line shown before the is as wanted
        class tempLine
         public Color color;
         public int startx;
         public int starty;
         public int endx;
         public int endy;
         public int thickness;
         public tempLine(Color mycolor, int mystartx, int mystarty,
                      int myendx, int myendy, int mythickness)
             color = mycolor;
             startx = mystartx;
             starty = mystarty;
             endx = myendx;
             endy = myendy;
             thickness = mythickness;
        class tempText
         public Color color;
         public int x;
         public int y;
         public String text;
         public tempText(Color mycolor, int myx, int myy, String mytext)
             color = mycolor;
             x = myx;
             y = myy;
             text = mytext;
    }

    http://www.java2s.com/ExampleCode/2D-Graphics/DemonstratingUseoftheImageIOLibrary.htm

  • Problem GameCanvas for Nokia 6260!!!!

    Hi,
    I tested some applications that extends the GameCanvas, when I tested on simulator J2ME Wireless Toolkit it hasn't problem when I download the application on phone (Nokia 6260) the program show screen and it work ok but when i try go out the application send the two errors
    "Buffer closed java.lang.RunTimeException
    0 java.lang.NullPointerException"
    It's possible that phone not support the class javax.microedition.lcdui.game.GameCanvas? or what's the problem?
    Help me please,
    Thanks
    P.S Below put the code, maybe this way is easer.
    // A simple example of a game canvas that displays
    // a scrolling star field. The UP and DOWN keys
    // speed up or slow down the rate of scrolling.
    public class StarField extends GameCanvas implements Runnable{
         private static final int SLEEP_INCREMENT = 10;
         private static final int SLEEP_INITIAL = 150;
         private static final int SLEEP_MAX = 300;
         private Graphics graphics;
         private Random random;
         private int sleepTime = SLEEP_INITIAL;
         private volatile Thread thread;
         private Command salir = null;
         public StarField(){
              super( true );
              graphics = getGraphics();
              graphics.setColor( 0, 0, 0 );
              graphics.fillRect( 0, 0, getWidth(), getHeight() );
         // When the game canvas is hidden, stop the thread.
         protected void hideNotify(){
              thread = null;
         // The game loop.
         public void run(){
              int w = getWidth();
              int h = getHeight() - 1;
              while( thread == Thread.currentThread() ){
                   // Increment or decrement the scrolling interval
                   // based on key presses
                   int state = getKeyStates();
                   if( ( state & DOWN_PRESSED ) != 0 ){
                        sleepTime += SLEEP_INCREMENT;
                        if( sleepTime > SLEEP_MAX )
                             sleepTime = SLEEP_MAX;
                   } else if( ( state & UP_PRESSED ) != 0 ){
                        sleepTime -= SLEEP_INCREMENT;
                        if( sleepTime < 0 ) sleepTime = 0;
                   // Repaint the screen by first scrolling the
                   // existing starfield down one and painting in
                   // new stars...
                   graphics.copyArea( 0, 0, w, h, 0, 1,
                   Graphics.TOP | Graphics.LEFT );
                   graphics.setColor( 0, 0, 0 );
                   graphics.drawLine( 0, 0, w, 1 );
                   graphics.setColor( 255, 255, 255 );
                   for( int i = 0; i < w; ++i ){
                        int test = Math.abs( random.nextInt() ) % 10;
                        if( test < 4 ){
                             graphics.drawLine( i, 0, i, 0 );
                   flushGraphics();
                   // Now wait...
                   try {
                        Thread.currentThread().sleep( sleepTime );
                   catch( InterruptedException e ){
         // When the canvas is shown, start a thread to
         // run the game loop.
         protected void showNotify(){
              random = new Random();
              thread = new Thread( this );
              thread.start();
    Thanks, see you

    do you have a memory card in your phone? Try freeing up your phones memo by deleting text,images and videos
    If  i have helped at all a click on the white star below would be nice thanks.
    Now using the Lumia 1520

  • Printing problem with muliple page 2D graphics.........URGENT

    /*hi
    I want to print the drawings that i create in my painting application.
    Following is the extract from my drawing application, which takes care of the printing part. The problem i am facing is that, i am able to print only one page, the other parts of my drawing are clipped (both from the horizontal as well as vertical direction)
    However i did found some help on printing multiple page TEXT documents, from some literature, but nothing was mentioned about printing drawing that may extend to multiple pages.
    Since printing forms a very important part of any painting application, the whole of my project now relies on the success of the printing code. Its really urgent for me to get out of this problem, any kind of help from anyone would be a great contribution in completing my project */
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.print.*;
    public class Print {
    public static void main(String[] args) {
    PrintFrame f = new PrintFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.show();
    class PrintFrame extends JFrame implements ActionListener{
    DrawingPanel drawingPanel = new DrawingPanel();
    public PrintFrame() {
    setTitle("Test Printing");
    setBounds(100,100,500,400);
    getContentPane().add(new JScrollPane(drawingPanel), BorderLayout.CENTER);
    JButton printButton = new JButton("Print");
    getContentPane().add(printButton,BorderLayout.SOUTH);
    printButton.addActionListener(this);
    public void actionPerformed(ActionEvent event) {
    PrintUtilities.printComponent(drawingPanel);
    class DrawingPanel extends JPanel {
    private int fontSize = 90;
    private String message = "Java 2D";
    private int messageWidth;
    Dimension pref = new Dimension(1500, 1500);//will define the max scrollable area
    public Dimension getPreferredSize() {
    return pref;
    public DrawingPanel() {
    setBackground(Color.white);
    Font font = new Font("Serif", Font.PLAIN, fontSize);
    setFont(font);
    FontMetrics metrics = getFontMetrics(font);
    messageWidth = metrics.stringWidth(message);
    int width = messageWidth*5/3;
    int height = fontSize*3;
    setPreferredSize(new Dimension(width, height));
    public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D)g;
    int x = messageWidth/10;
    int y = fontSize*5/2;
    g2d.translate(x, y);
    g2d.setPaint(Color.lightGray);
    AffineTransform origTransform = g2d.getTransform();
    g2d.shear(-0.95, 0);
    g2d.scale(1, 3);
    g2d.drawString(message, 0, 0);
    g2d.setTransform(origTransform);
    g2d.setPaint(Color.black);
    g2d.drawString(message, 0, 0);
    g2d.drawLine(5,5,1490,500);//this line goes outside my paper width, & does not get printed
    class PrintUtilities implements Printable {
    private Component componentToBePrinted;
    public static void printComponent(Component c) {
    new PrintUtilities(c).print();
    public PrintUtilities(Component componentToBePrinted) {
    this.componentToBePrinted = componentToBePrinted;
    public void print() {
    PrinterJob printJob = PrinterJob.getPrinterJob();
    printJob.setPrintable(this);
    if (printJob.printDialog())
    try {
    printJob.print();
    } catch(PrinterException pe) {
    System.out.println("Error printing: " + pe);
    public int print(Graphics g, PageFormat pageFormat, int pageIndex) {
    if (pageIndex > 0) {
    return(NO_SUCH_PAGE);
    } else {
    Graphics2D g2 = (Graphics2D)g;
    g2.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
    disableDoubleBuffering(componentToBePrinted);
    componentToBePrinted.paint(g2);
    enableDoubleBuffering(componentToBePrinted);
    return(PAGE_EXISTS);
    /* disables double buffering globally. */
    public static void disableDoubleBuffering(Component c) {
    RepaintManager currentManager = RepaintManager.currentManager(c);
    currentManager.setDoubleBufferingEnabled(false);
    /* Re-enables double buffering globally. */
    public static void enableDoubleBuffering(Component c) {
    RepaintManager currentManager = RepaintManager.currentManager(c);
    currentManager.setDoubleBufferingEnabled(true);
    }

    Um I dont know if im doing something daft but I tried this like you said
    PrinterJob printJob = PrinterJob.getPrinterJob();
    printJob.setPrintable(this);
    if(printJob.printDialog()){
    try {
              PageFormat pageFormat = printJob.defaultPage();
              if (pageFormat.getOrientation() == PageFormat.PORTRAIT) {
              landscape = 0;} else {
                   landscape = 1;}
              System.out.println("THE ORIENTATION IS "+ landscape);
              printJob.print(); }
    catch (Exception PrinterExeption) { PrinterExeption.printStackTrace();}
    and it doesnt seem to work as I tried it both as landscape and portrait in the print dialog but landscape is always 0.
    cheers
    pmiggy

  • JTable sorting - problem when adding elements (complete code inside)

    I�m writing this email with reference to a recent posting here but this time with the code example. (I apologize for the duplicated posting � this time it will be with the code)
    Problem: when adding more elements to the JTable (sorted) the exception: ArrayIndexOutOfBoundsException is thrown.
    Example: If the elements in the table are 10 and then the user requests for 8 � the table will produce the correct result. However, if the user will ask for 11 items (>10) the exception will be thrown.
    The program: The program below (compiles and running). A JTable is constructed with 3 items, when you click the button - the return result should be 4 items - this will generate the error, WHY?
    I would highly appreciate your thoughts why this is happening and most importantly � how to fix it.
    Thanks a lot
    3 files:
    (1) TableSorterDemo
    (2) Traveler
    (3)TableSorter
    //TableSorterDemo:
    package sorter;
    import javax.swing.DefaultListModel;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    * TableSorterDemo is like TableDemo, except that it
    * inserts a custom model -- a sorter -- between the table
    * and its data model.  It also has column tool tips.
    public class TableSorterDemo implements ActionListener
         private JPanel superPanel;
         private JButton clickMe = new JButton("click me to get diff data");
         private boolean DEBUG = false;
         private DefaultListModel defaultListModel;
         private JTable table;
        public TableSorterDemo()
             superPanel = new JPanel(new BorderLayout());
             defaultListModel = new DefaultListModel();
             init1();
            TableSorter sorter = new TableSorter(new MyTableModel(defaultListModel)); //ADDED THIS     
            table = new JTable(sorter);             //NEW
            sorter.setTableHeader(table.getTableHeader()); //ADDED THIS
            table.setPreferredScrollableViewportSize(new Dimension(500, 70));
            //Set up tool tips for column headers.
            table.getTableHeader().setToolTipText(
                    "Click to specify sorting; Control-Click to specify secondary sorting");
            //Create the scroll pane and add the table to it.
            JScrollPane scrollPane = new JScrollPane(table);
            //Add the scroll pane to this panel.
            superPanel.add("Center", scrollPane);
            superPanel.add("South",clickMe);
            clickMe.addActionListener(this);              
        public JPanel getPanel()
             return superPanel;
        public void init1()
             //in real life this will be done from the db
             Traveler a = new Traveler();
             Traveler b = new Traveler();
             Traveler c = new Traveler();
             a.setFirstName("Elvis");
             a.setLastName("Presley");
             a.setSprot("Ping Pong");
             a.setNumYears(3);
             a.setVegetarian(true);
             b.setFirstName("Elton");
             b.setLastName("John");
             b.setSprot("Soccer");
             b.setNumYears(2);
             b.setVegetarian(true);
             c.setFirstName("shaquille");
             c.setLastName("oneil");
             c.setSprot("Golf");
             c.setNumYears(22);
             c.setVegetarian(true);
             defaultListModel.addElement(a);
             defaultListModel.addElement(b);
             defaultListModel.addElement(c);
        public void init2()
             //in real life this will be done from the db
             Traveler d = new Traveler();
             Traveler e = new Traveler();
             Traveler f = new Traveler();
             Traveler g = new Traveler();
             d.setFirstName("John");
             d.setLastName("Smith");
             d.setSprot("Tennis");
             d.setNumYears(32);
             d.setVegetarian(true);
             e.setFirstName("Ron");
             e.setLastName("Cohen");
             e.setSprot("Baseball");
             e.setNumYears(12);
             e.setVegetarian(true);
             f.setFirstName("Donald");
             f.setLastName("Mac Novice");
             f.setSprot("Vallyball");
             f.setNumYears(1);
             f.setVegetarian(true);
             g.setFirstName("Eithan");
             g.setLastName("Superstar");
             g.setSprot("Vallyball");
             g.setNumYears(21);
             g.setVegetarian(true);
             defaultListModel.addElement(d);
             defaultListModel.addElement(e);
             defaultListModel.addElement(f);
             defaultListModel.addElement(g);            
        class MyTableModel extends AbstractTableModel
             private DefaultListModel myModel;
             public MyTableModel(DefaultListModel m)
                  myModel=m;
            private String[] columnNames = {"First Name",
                                            "Last Name",
                                            "Sport",
                                            "# of Years",
                                            "Vegetarian"};
            public int getColumnCount()
                return columnNames.length;
            public int getRowCount()
                return myModel.size();
            public String getColumnName(int column)
                 return getNames()[column];             
             public String[] getNames()
                  String[] names = {"First Name", "Last Name", "Sport", "# of Years", "Vegetarian"};
                  return names;
            public Object getValueAt(int row, int col)
                 return distributeObjectsInTable(row, col, (Traveler) myModel.elementAt(row));
            public Object distributeObjectsInTable(int row, int col, Traveler tr)
               switch(col)
                         case 0:
                              return tr.getFirstName();
                         case 1:
                           return tr.getLastName();
                      case 2:
                           return tr.getSprot();
                      case 3:
                           return new Integer(tr.getNumYears());
                      case 4:
                           return new Boolean (tr.isVegetarian());
                     default:
                         return "Error";
            public Class getColumnClass(int c)
                return getValueAt(0, c).getClass();
        private static void createAndShowGUI()
            //Make sure we have nice window decorations.
            JFrame.setDefaultLookAndFeelDecorated(true);
            //Create and set up the window.
            JFrame frame = new JFrame("TableSorterDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            TableSorterDemo newContentPane = new TableSorterDemo();
            newContentPane.getPanel().setOpaque(true); //content panes must be opaque
            frame.setContentPane(newContentPane.getPanel());
            //Display the window.
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args)
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable()                   
                public void run()
                    createAndShowGUI();
         public void actionPerformed(ActionEvent ae)
              if (ae.getSource()==clickMe)
                   defaultListModel.removeAllElements();
                   init2(); //if the size of the model was less than 2 items - the result will be ok.
                              //in other words, if you commens the last 2 rows of this method (addElement(f) & g)
                             // the result will be fine.
                   table.updateUI();          
    }//(2) Traveler
    package sorter;
    public class Traveler
         private String firstName;
         private String lastName;
         private String sprot;
         private int numYears;
         private boolean vegetarian;
         public String getFirstName()
              return firstName;
         public String getLastName()
              return lastName;
         public int getNumYears()
              return numYears;
         public String getSprot()
              return sprot;
         public boolean isVegetarian()
              return vegetarian;
         public void setFirstName(String firstName)
              this.firstName = firstName;
         public void setLastName(String lastName)
              this.lastName = lastName;
         public void setNumYears(int numYears)
              this.numYears = numYears;
         public void setSprot(String sprot)
              this.sprot = sprot;
         public void setVegetarian(boolean vegetarian)
              this.vegetarian = vegetarian;
    }//(3)TableSorter
    package sorter;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.util.List;
    import javax.swing.*;
    import javax.swing.event.TableModelEvent;
    import javax.swing.event.TableModelListener;
    import javax.swing.table.*;
    public class TableSorter extends AbstractTableModel {
        protected TableModel tableModel;
        public static final int DESCENDING = -1;
        public static final int NOT_SORTED = 0;
        public static final int ASCENDING = 1;
        private static Directive EMPTY_DIRECTIVE = new Directive(-1, NOT_SORTED);
        public static final Comparator COMPARABLE_COMAPRATOR = new Comparator() {
            public int compare(Object o1, Object o2) {
                return ((Comparable) o1).compareTo(o2);
        public static final Comparator LEXICAL_COMPARATOR = new Comparator() {
            public int compare(Object o1, Object o2) {
                return o1.toString().compareTo(o2.toString());
        private Row[] viewToModel;
        private int[] modelToView;
        private JTableHeader tableHeader;
        private MouseListener mouseListener;
        private TableModelListener tableModelListener;
        private Map columnComparators = new HashMap();
        private List sortingColumns = new ArrayList();
        public TableSorter() {
            this.mouseListener = new MouseHandler();
            this.tableModelListener = new TableModelHandler();
        public TableSorter(TableModel tableModel) {
            this();
            setTableModel(tableModel);
        public TableSorter(TableModel tableModel, JTableHeader tableHeader) {
            this();
            setTableHeader(tableHeader);
            setTableModel(tableModel);
        private void clearSortingState() {
            viewToModel = null;
            modelToView = null;
        public TableModel getTableModel() {
            return tableModel;
        public void setTableModel(TableModel tableModel) {
            if (this.tableModel != null) {
                this.tableModel.removeTableModelListener(tableModelListener);
            this.tableModel = tableModel;
            if (this.tableModel != null) {
                this.tableModel.addTableModelListener(tableModelListener);
            clearSortingState();
            fireTableStructureChanged();
        public JTableHeader getTableHeader() {
            return tableHeader;
        public void setTableHeader(JTableHeader tableHeader) {
            if (this.tableHeader != null) {
                this.tableHeader.removeMouseListener(mouseListener);
                TableCellRenderer defaultRenderer = this.tableHeader.getDefaultRenderer();
                if (defaultRenderer instanceof SortableHeaderRenderer) {
                    this.tableHeader.setDefaultRenderer(((SortableHeaderRenderer) defaultRenderer).tableCellRenderer);
            this.tableHeader = tableHeader;
            if (this.tableHeader != null) {
                this.tableHeader.addMouseListener(mouseListener);
                this.tableHeader.setDefaultRenderer(
                        new SortableHeaderRenderer(this.tableHeader.getDefaultRenderer()));
        public boolean isSorting() {
            return sortingColumns.size() != 0;
        private Directive getDirective(int column) {
            for (int i = 0; i < sortingColumns.size(); i++) {
                Directive directive = (Directive)sortingColumns.get(i);
                if (directive.column == column) {
                    return directive;
            return EMPTY_DIRECTIVE;
        public int getSortingStatus(int column) {
            return getDirective(column).direction;
        private void sortingStatusChanged() {
            clearSortingState();
            fireTableDataChanged();
            if (tableHeader != null) {
                tableHeader.repaint();
        public void setSortingStatus(int column, int status) {
            Directive directive = getDirective(column);
            if (directive != EMPTY_DIRECTIVE) {
                sortingColumns.remove(directive);
            if (status != NOT_SORTED) {
                sortingColumns.add(new Directive(column, status));
            sortingStatusChanged();
        protected Icon getHeaderRendererIcon(int column, int size) {
            Directive directive = getDirective(column);
            if (directive == EMPTY_DIRECTIVE) {
                return null;
            return new Arrow(directive.direction == DESCENDING, size, sortingColumns.indexOf(directive));
        private void cancelSorting() {
            sortingColumns.clear();
            sortingStatusChanged();
        public void setColumnComparator(Class type, Comparator comparator) {
            if (comparator == null) {
                columnComparators.remove(type);
            } else {
                columnComparators.put(type, comparator);
        protected Comparator getComparator(int column) {
            Class columnType = tableModel.getColumnClass(column);
            Comparator comparator = (Comparator) columnComparators.get(columnType);
            if (comparator != null) {
                return comparator;
            if (Comparable.class.isAssignableFrom(columnType)) {
                return COMPARABLE_COMAPRATOR;
            return LEXICAL_COMPARATOR;
        private Row[] getViewToModel() {
            if (viewToModel == null) {
                int tableModelRowCount = tableModel.getRowCount();
                viewToModel = new Row[tableModelRowCount];
                for (int row = 0; row < tableModelRowCount; row++) {
                    viewToModel[row] = new Row(row);
                if (isSorting()) {
                    Arrays.sort(viewToModel);
            return viewToModel;
        public int modelIndex(int viewIndex)
            return getViewToModel()[viewIndex].modelIndex;
        private int[] getModelToView()
            if (modelToView == null) {
                int n = getViewToModel().length;
                modelToView = new int[n];
                for (int i = 0; i < n; i++) {
                    modelToView[modelIndex(i)] = i;
            return modelToView;
        // TableModel interface methods
        public int getRowCount() {
            return (tableModel == null) ? 0 : tableModel.getRowCount();
        public int getColumnCount() {
            return (tableModel == null) ? 0 : tableModel.getColumnCount();
        public String getColumnName(int column) {
            return tableModel.getColumnName(column);
        public Class getColumnClass(int column) {
            return tableModel.getColumnClass(column);
        public boolean isCellEditable(int row, int column) {
            return tableModel.isCellEditable(modelIndex(row), column);
        public Object getValueAt(int row, int column) {
            return tableModel.getValueAt(modelIndex(row), column);
        public void setValueAt(Object aValue, int row, int column) {
            tableModel.setValueAt(aValue, modelIndex(row), column);
        // Helper classes
        private class Row implements Comparable {
            private int modelIndex;
            public Row(int index) {
                this.modelIndex = index;
            public int compareTo(Object o) {
                int row1 = modelIndex;
                int row2 = ((Row) o).modelIndex;
                for (Iterator it = sortingColumns.iterator(); it.hasNext();) {
                    Directive directive = (Directive) it.next();
                    int column = directive.column;
                    Object o1 = tableModel.getValueAt(row1, column);
                    Object o2 = tableModel.getValueAt(row2, column);
                    int comparison = 0;
                    // Define null less than everything, except null.
                    if (o1 == null && o2 == null) {
                        comparison = 0;
                    } else if (o1 == null) {
                        comparison = -1;
                    } else if (o2 == null) {
                        comparison = 1;
                    } else {
                        comparison = getComparator(column).compare(o1, o2);
                    if (comparison != 0) {
                        return directive.direction == DESCENDING ? -comparison : comparison;
                return 0;
        private class TableModelHandler implements TableModelListener {
            public void tableChanged(TableModelEvent e) {
                // If we're not sorting by anything, just pass the event along.            
                if (!isSorting()) {
                    clearSortingState();
                    fireTableChanged(e);
                    return;
                // If the table structure has changed, cancel the sorting; the            
                // sorting columns may have been either moved or deleted from            
                // the model.
                if (e.getFirstRow() == TableModelEvent.HEADER_ROW) {
                    cancelSorting();
                    fireTableChanged(e);
                    return;
                // We can map a cell event through to the view without widening            
                // when the following conditions apply:
                // a) all the changes are on one row (e.getFirstRow() == e.getLastRow()) and,
                // b) all the changes are in one column (column != TableModelEvent.ALL_COLUMNS) and,
                // c) we are not sorting on that column (getSortingStatus(column) == NOT_SORTED) and,
                // d) a reverse lookup will not trigger a sort (modelToView != null)
                // Note: INSERT and DELETE events fail this test as they have column == ALL_COLUMNS.
                // The last check, for (modelToView != null) is to see if modelToView
                // is already allocated. If we don't do this check; sorting can become
                // a performance bottleneck for applications where cells 
                // change rapidly in different parts of the table. If cells
                // change alternately in the sorting column and then outside of            
                // it this class can end up re-sorting on alternate cell updates -
                // which can be a performance problem for large tables. The last
                // clause avoids this problem.
                int column = e.getColumn();
                if (e.getFirstRow() == e.getLastRow()
                        && column != TableModelEvent.ALL_COLUMNS
                        && getSortingStatus(column) == NOT_SORTED
                        && modelToView != null) {
                    int viewIndex = getModelToView()[e.getFirstRow()];
                    fireTableChanged(new TableModelEvent(TableSorter.this,
                                                         viewIndex, viewIndex,
                                                         column, e.getType()));
                    return;
                // Something has happened to the data that may have invalidated the row order.
                clearSortingState();
                fireTableDataChanged();
                return;
        private class MouseHandler extends MouseAdapter {
            public void mouseClicked(MouseEvent e) {
                JTableHeader h = (JTableHeader) e.getSource();
                TableColumnModel columnModel = h.getColumnModel();
                int viewColumn = columnModel.getColumnIndexAtX(e.getX());
                int column = columnModel.getColumn(viewColumn).getModelIndex();
                if (column != -1) {
                    int status = getSortingStatus(column);
                    if (!e.isControlDown()) {
                        cancelSorting();
                    // Cycle the sorting states through {NOT_SORTED, ASCENDING, DESCENDING} or
                    // {NOT_SORTED, DESCENDING, ASCENDING} depending on whether shift is pressed.
                    status = status + (e.isShiftDown() ? -1 : 1);
                    status = (status + 4) % 3 - 1; // signed mod, returning {-1, 0, 1}
                    setSortingStatus(column, status);
        private static class Arrow implements Icon {
            private boolean descending;
            private int size;
            private int priority;
            public Arrow(boolean descending, int size, int priority) {
                this.descending = descending;
                this.size = size;
                this.priority = priority;
            public void paintIcon(Component c, Graphics g, int x, int y) {
                Color color = c == null ? Color.GRAY : c.getBackground();            
                // In a compound sort, make each succesive triangle 20%
                // smaller than the previous one.
                int dx = (int)(size/2*Math.pow(0.8, priority));
                int dy = descending ? dx : -dx;
                // Align icon (roughly) with font baseline.
                y = y + 5*size/6 + (descending ? -dy : 0);
                int shift = descending ? 1 : -1;
                g.translate(x, y);
                // Right diagonal.
                g.setColor(color.darker());
                g.drawLine(dx / 2, dy, 0, 0);
                g.drawLine(dx / 2, dy + shift, 0, shift);
                // Left diagonal.
                g.setColor(color.brighter());
                g.drawLine(dx / 2, dy, dx, 0);
                g.drawLine(dx / 2, dy + shift, dx, shift);
                // Horizontal line.
                if (descending) {
                    g.setColor(color.darker().darker());
                } else {
                    g.setColor(color.brighter().brighter());
                g.drawLine(dx, 0, 0, 0);
                g.setColor(color);
                g.translate(-x, -y);
            public int getIconWidth() {
                return size;
            public int getIconHeight() {
                return size;
        private class SortableHeaderRenderer implements TableCellRenderer {
            private TableCellRenderer tableCellRenderer;
            public SortableHeaderRenderer(TableCellRenderer tableCellRenderer) {
                this.tableCellRenderer = tableCellRenderer;
            public Component getTableCellRendererComponent(JTable table,
                                                           Object value,
                                                           boolean isSelected,
                                                           boolean hasFocus,
                                                           int row,
                                                           int column) {
                Component c = tableCellRenderer.getTableCellRendererComponent(table,
                        value, isSelected, hasFocus, row, column);
                if (c instanceof JLabel) {
                    JLabel l = (JLabel) c;
                    l.setHorizontalTextPosition(JLabel.LEFT);
                    int modelColumn = table.convertColumnIndexToModel(column);
                    l.setIcon(getHeaderRendererIcon(modelColumn, l.getFont().getSize()));
                return c;
        private static class Directive {
            private int column;
            private int direction;
            public Directive(int column, int direction) {
                this.column = column;
                this.direction = direction;
    }

    The table listens to the TableModel for changes. Changing the table by adding/removing
    rows or columns has no affect on its table model. If you make changes to the table model
    the table will be notified by its TableModelListener and change its view. So tell
    MyTableModel about the change of data:
    public class TableSorterDemo implements ActionListener
        MyTableModel tableModel;
        public TableSorterDemo()
            defaultListModel = new DefaultListModel();
            init1();
            tableModel = new MyTableModel(defaultListModel);
            TableSorter sorter = new TableSorter(tableModel);
        public void actionPerformed(ActionEvent ae)
            if (ae.getSource()==clickMe)
                defaultListModel.removeAllElements();
                init2();
                tableModel.fireTableStructureChanged();
    }

Maybe you are looking for

  • Webutil_host.host problems (bugs???)

    Hi, I'm using the webutil_host.host(commandline) command to execute batchfiles on a client pc. These batch files are also echoing messages to the screen. In the client server version, when I use the host command, the messages appear in my ms-dos box.

  • Cannot connect to Internet when click on a link in Reader X?

    Hi, I have this problem with Reader X - when I click on a link, the Reader asks me if I want to "allow access"? I click Yes, but nothing happens - I am not redirected to a page on the net, nor any of my browsers open it. Basically I now have to manua

  • EP Sneak Preview - Moving from Portal Authentication to LDAP

    Has anyone used the EP sneak preview, configuring first against portal authentication alone and then moving users to LDAP and leaving just the roles in the portal db, without having disaster strike and have to reinstall, etc.? Thanks in advance.

  • Preview Shift Color on Save?

    Hi Can anyone save me from this headache of a problem! After saving a postscript file from QuarkXpress 5.0 I open it in preview. All is good. But then when I save it out of preview as a pdf the color changes as soon as the save is complete. Why is th

  • Importing data into an existing table from excel problem

    Hopefully I am posting this in the right place.. I am having trouble importing data from Excel into an oracle table using the 'import data' wizard in SQL developer. The problem is that the I want to import data into a table which all ready has data a