Repaint in TreeSelectionListener Event

Hi all,
I am new to write a swing application which extends JFrame. I am displaying a JSplitPane object. On the top of the splitpane, I am displaying a JTree. My application is to display a table at the bottom of the splitpane according to what node user chooses in the JTree object (which invokes the TreeSelectionListener). It seems that the JFrame doesn't get update as I tried to do the following
private class ResultFrame extends JFrame {
JTree tree;
JScrollPane treeScrollPane;
JScrollPane tablePane;
JSplitPane splitPane;
public ResultFrame() {
super("Results");
init();
setSize(800,400);
centerWindow();
show();
private void init() {
/* make the tree here */
tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
tree.addTreeSelectionListener(new TreeHandler());
treeScrollPane = new JScrollPane(tree);
tablePane = new JScrollPane();
splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
splitPane.setTopComponent(treeScrollPane);
splitPane.setBottomComponent(tablePane);
getContentPane().add(splitPane);
private class TreeHandler implements TreeSelectionListener {
public void valueChanged(TreeSelectionEvent e) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode)((JTree)e.getSource()).getLastSelectedPathComponent();
/* method makeTable() will make the table */
JTable resultTable = makeTable();
tablePane.removeAll();
tablePane.add(resultTable);
tablePane.setVisible(true);
tablePane.doLayout();
tablePane.revalidate();
tablePane.repaint();
this.doLayout();
this.revalidate();
this.repaint();
Thanks for the help!!!

Hello!
Are you able to compile the code? Probably, you can't because
this.doLayout();
this.revalidate();
this.repaint();and the compiler treats the this keyword as the instance of the the inner class & will throw few errors instead replace the code with the following, hope this helps you,
ResultFrame.this.doLayout();
ResultFrame.this.revalidate();
ResultFrame.this.repaint();I'm no expert though, hope this helps you.
regards,
Afroze

Similar Messages

  • Delaying repaint until componentMoved event processed

    I have a problem in a specialised browser application I have written.
    The main display consists of a JPanel with JComponents added to it at absolute locations (Layout manager is set null). A Link object represents the link between two JComponents and holds a start and end location. In the 'Panel' class; the paintComponent method is overridden to render the link objects i.e. iterates thru link object list and draws a line from start to end point for each one.
    The Link object also implements the componentListener interface and listens for movement/resizing of its origin and destination JComponent. i.e. will dynamically change as JComponets are moved.
    Scenario- JComponent is moved to a different location: I believe this results in an automatic call to repaint the JComponent and consequentially the parent JPanel but will also cause a componentMoved event, which is then processed in the Link object,updating its start or end point.
    However the repaint is carried out before the componentMoved event , causing the links to be 'one move behind' the JComponent.
    How can I delay the repaint() on the event dispatching thread until the componentMoved event is processed.
    (I originally got round the problem by calling repaint()on the Panel at the end of the componentMoved method. But this means the whole display is painted twice for each user action. Since there are alot of scaled images and high definition images rendered, this is slow and jerky!)
    I am only starting to investigate use of different threads so any advice from experienced users appreciated
    thanks

    All repaing calls are delegated to the RepaintManager for that component and scheduled for painting.
    The RepaintManager is a convenient way to collapse fast occuring paints. In the end, the paint requests will be called from a SwingUtilities.invokeLater anyway, so just adding one more might not be the solution.
    Another, more obscure use of the RepaintManager, is exactly stopping unwanted paints. You can see this in the case of a JScrollPane. The viewport manages the movement of the view by changing its location. That calls repaint on the whole view component, event if the viewport size is very small. There are still a lot more things that the viewport does with the RepaintManager, but there is no need for that right now.
    In your case you can implement something like this:
    -- since your component is moved through the setLocation method you can override it with something like this:
    private Rectangle rectDirtyRegion;
    public void setLocation(int x, int y) {
        //call the actual moving operation
        super.setLocation(x, y);
        // get the RepaintManager for your component
        RepaintManager manager = RepaintManager.currentManager(this);
        // save the dirty region for your component
        rectDirtyRegion = manager.getDirtyRegion(this);
        // mark the component as clean so that no paint will take place.
        manager.markCompletelyClean(this);
    }Now, when you finally draw your link, you have to take care of marking the dirty regions again:
        RepaintManager.currentManager(this).addDirtyRegion(this, rectDirtyRegion.x, rectDirtyRegion.y, rectDirtyRegion.width, rectDirtyRegion.height);It is probably more work to it than in this simple example, but I am sure it can be accomplished. Study the RepaintManager behaviour and you might come with an even better solution.

  • Repaint during an event with no effect

    Hello, I'm trying to repaint a JFRame during an event that takes abot 30-60seconds, the result is that the JFrame is not repainted until the event is finished. There is any solution to this? Sorry I'm a newbie with swing.

    I just had a similar problem. So I quote Camickr who pointed out why this is happening:
    All code in in an event listener is executed in the GUI Event Thread ... [Only] When the thread finishes [your painting] is executed.The solution is to put your painting code in a separate thread.
    Edited by: Joerg22 on Dec 10, 2007 9:42 PM
    There was even no need to quote him. He replied quicker than me. ;-)

  • Which events should I listen for in JTree

    OK I'm using TreeSelectionListener/Event to handle when someone selects a node, but I'd like to also create a JPopupMenu when someone right-clicks a node. How should I handle that?

    Ok nevermind... After doing some more intensive searching I found this thread:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=274387&tstart=0&trange=15

  • Unable to call method repaint()

    A problem occured to me when I tried to call the method repaint() within an event method. Here is a simple applet, showing a button with an attached ActionListener.
    On pressing the button, an array with the digits from 1 to 0 should be shown at a starting position 50,100. This is done with the help of a boolean variable initialized at false. When the button is clicked the System.out.println method throws the "Action" string at the console, meaning that b has changed its value to true, but the next line doesn't seem to be executing. The array is displayed when an occasional repaint is called by the GUI thread (resizing the applet, hiding the applet behind a window and then showing it back again or minimizing and maximizing the applet).
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.*;
    public class ActionEventsTest extends Applet {
    int[] a={1,2,3,4,5,6,7,8,9,0};
    boolean b=false;
    public void init() {
    add(new Button("Check")     {
    addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ev)     {
    b=true;
    System.out.println("Action");
    repaint();
    public void paint(Graphics g) {
    if(b)
    for(int i=0;i<a.length;i++)
    g.drawString(""+a,50+i*5,100);

    No, I think it's executing. You're probably just doing it wrong. Try something else. For instance, try drawing a big x through your applet (2 lines, 1 going from 0,0 to width,height, the other going from width, 0 to 0, height)

  • Exception catching in event processing thread

    Hello!
    How to catch exceptions occurring in event processing thread during repaints, mouse & keyboard event processing etc.? All uncatched exceptions displayed in screen but I need to write them in logfile.
    Anton

    Yes - push your own event processor on to the AWT event queue. See my replies at
    http://forum.java.sun.com/thread.jsp?forum=57&thread=484167
    and
    http://forum.java.sun.com/thread.jsp?forum=57&thread=163020
    Although for two completely different purposes, this technique will also allow you to put your own try/catch around super.dispatchEvent()
    Hope that helps
    Tom

  • My manual repainting gets erased by SWING!

    Greetings JAVA Guru's!
    I am writing a JAVA APP that extends JFrame. My App has a menu bar that opens both a JDialog and a JFileChooser. My Problem is I need to use "Custom repainting" and I cannot get this to work right. This is the first time I have mixed a menu bar, Jdailog,and Jfile Choosers with "Custom repainting".
    Swing already handles the painting for the Jmenu, Jdailog, Jfilechooser and I would like to manually update the remainder of the JFrame. Currently, I directly call PaintComponent(g) or Repaint() and my Image objects are drawn correctly on the JFrame (can be seen with rreeeaalllllyyy long delay). Except, Swing automatically updates the JFrame and erases all my "Custom Painting" once the delay ends.
    Should I be calling Repaint() from the event Displatching thread? If so, how do I do this? How do I make this work without fighting against the Automatic Swing Painting Model?
    Any Ideas or Suggestions will be greatly Appreciated!
    -Chibi_neko

    I call the paintComponent(g) Method as follows:
    g=getGraphics();
    paintComponent(g);
    AND I override paintComponent as Follows:
    public void paintComponent(Graphics g) {
    if (tileSetImage !=null){
    g.drawImage(tileSetImage, 0, 0, contentPane);
    // My delay is below.... I pop up an Option Pain
    JOptionPane.showMessageDialog(contentPane, "Repaint OK", "Repaint OK",OptionPane.PLAIN_MESSAGE);
    }else{
    JOptionPane.showMessageDialog(contentPane, "Error Repaint ", "Error Repaint",JOptionPane.ERROR_MESSAGE);
    }

  • Is there any way to animate a JSlider and a JProgressBar?

    Hi all,
    I'm working on an assignment using JSliders and JProgressBars in a Java application. I've been trying to let my JSlider and JProgressBar move by itself i.e. reset the slider's current value to a new one after a specific period of time...Tried using a timer and thread but just can't seem to get it moving. Is there any way to set the JSlider to update itself after a specified time period? Same goes for JProgressBar?
    At my wits' end, really appreciate if anyone can offer me some advice and help...Thanks.

    Hmm...use a timertask that resets the value and triggers a repaint in the event thread? That should work at least in theory.

  • Help needed in creating a simple paint application

    I want to create a simple paint application using swings in java, i am able to draw different shapes using mouse but the problem is when i select some other shape it simply replaces the already drawn object with the new one but i want the already drawn object also, like appending, what should be done for this, any logic missing here or i should use some other approach?
    Please help me
    package test;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class bmp extends JFrame implements MouseListener, MouseMotionListener,
              ActionListener {
         int w, h;
         int xstart, ystart, xend, yend;
         JButton elipse = new JButton("--Elipse--");
         JButton rect = new JButton  ("Rectangle");
         JPanel mainframe = new JPanel();
         JPanel buttons = new JPanel();
         String selected="no";
         public void init() {
              //super("Bitmap Functions");
              // display.setLayout(new FlowLayout());
              buttons.setLayout(new BoxLayout(buttons,BoxLayout.Y_AXIS));
              buttons.add(Box.createRigidArea(new Dimension(15,15)));
              buttons.add(elipse);
              buttons.add(Box.createRigidArea(new Dimension(0,15)));
              buttons.add(rect);
              Container contentpane = getContentPane();
              contentpane.add(buttons, BorderLayout.WEST);
              //getContentPane().add(display, BorderLayout.WEST);
              addMouseListener(this); // listens for own mouse and
              addMouseMotionListener(this); // mouse-motion events
              setSize(1152, 834);
              elipse.addActionListener(this);
              rect.addActionListener(this);
              setVisible(true);
         public void mousePressed(MouseEvent event) {
              xstart = event.getX();
              ystart = event.getY();
         public void mouseReleased(MouseEvent event) {
              xend = event.getX();
              yend = event.getY();
              repaint();
         public void mouseEntered(MouseEvent event) {
              //repaint();
         public void mouseExited(MouseEvent event) {
              //repaint();
         public void mouseDragged(MouseEvent event) {
              xend = event.getX();
              yend = event.getY();
              repaint();
         public void mouseMoved(MouseEvent event) {
              //repaint();
         public static void main(String args[]) {
              bmp application = new bmp();
              application.init();
              application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         public void mouseClicked(MouseEvent arg0) {
         public void actionPerformed(ActionEvent event) {
              if (event.getSource() == elipse) {
                   selected = "elipse";
                   repaint();
              else if(event.getSource() == rect)
                   selected = "rectangle";
                   repaint();
         public void paint(Graphics g) {
              System.out.println(selected);
              super.paint(g); // clear the frame surface
              bmp b=new bmp();
              if (selected.equals("elipse"))
                   w = xend - xstart;
                   h = yend - ystart;
                   if (w < 0)
                        w = w * -1;
                   if (h < 0)
                        h = h * -1;
                   g.drawOval(xstart, ystart, w, h);
              if (selected.equals("rectangle"))
                   w = xend - xstart;
              h = yend - ystart;
              if (w < 0)
                   w = w * -1;
              if (h < 0)
                   h = h * -1;
              g.drawRect(xstart, ystart, w, h);
    }

    bvivek wrote:
    ..With this code, when i draw an elipse or line the image doesnt start from the point where i click the mouse. It added the MouseListener to the wrong thing.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.BufferedImage;
    import javax.swing.*;
    public class test_bmp extends JPanel implements MouseListener,MouseMotionListener,ActionListener
           static BufferedImage image;
           Color color;
           Point start=new Point();
           Point end =new Point();
           JButton elipse=new JButton("Elipse");
           JButton rectangle=new JButton("Rectangle");
           JButton line=new JButton("Line");
           String selected;
           public test_bmp()
                   color = Color.black;
                   setBorder(BorderFactory.createLineBorder(Color.black));
           public void paintComponent(Graphics g)
                   //super.paintComponent(g);
                   g.drawImage(image, 0, 0, this);
                   Graphics2D g2 = (Graphics2D)g;
                   g2.setPaint(Color.black);
           if(selected=="elipse")
                   g2.drawOval(start.x, start.y, (end.x-start.x),(end.y-start.y));
                   System.out.println("paintComponent() "+start.getX()+","+start.getY()+","+(end.getX()-start.getX())+","+(end.getY()-start.getY()));
                   System.out.println("Start : "+start.x+","+start.y);
                   System.out.println("End   : "+end.x+","+end.y);
           if(selected=="line")
                   g2.drawLine(start.x,start.y,end.x,end.y);
           //Draw on Buffered image
           public void draw()
           Graphics2D g2 = image.createGraphics();
           g2.setPaint(color);
                   System.out.println("draw");
           if(selected=="line")
                   g2.drawLine(start.x, start.y, end.x, end.y);
           if(selected=="elipse")
                   g2.drawOval(start.x, start.y, (end.x-start.x),(end.y-start.y));
                   System.out.println("draw() "+start.getX()+","+start.getY()+","+(end.getX()-start.getX())+","+(end.getY()-start.getY()));
                   System.out.println("Start : "+start.x+","+start.y);
                   System.out.println("End   : "+end.x+","+end.y);
           repaint();
           g2.dispose();
           public JPanel addButtons()
                   JPanel buttonpanel=new JPanel();
                   buttonpanel.setBackground(color.lightGray);
                   buttonpanel.setLayout(new BoxLayout(buttonpanel,BoxLayout.Y_AXIS));
                   elipse.addActionListener(this);
                   rectangle.addActionListener(this);
                   line.addActionListener(this);
                   buttonpanel.add(elipse);
                   buttonpanel.add(Box.createRigidArea(new Dimension(15,15)));
                   buttonpanel.add(rectangle);
                   buttonpanel.add(Box.createRigidArea(new Dimension(15,15)));
                   buttonpanel.add(line);
                   return buttonpanel;
           public static void main(String args[])
                    test_bmp application=new test_bmp();
                    //Main window
                    JFrame frame=new JFrame("Whiteboard");
                    frame.setLayout(new BorderLayout());
                    frame.add(application.addButtons(),BorderLayout.WEST);
                    frame.add(application);
                    application.addMouseListener(application);
                    application.addMouseMotionListener(application);
                    //size of the window
                    frame.setSize(600,400);
                    frame.setLocation(0,0);
                    frame.setVisible(true);
                    int w = frame.getWidth();
                int h = frame.getHeight();
                image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
                Graphics2D g2 = image.createGraphics();
                g2.setPaint(Color.white);
                g2.fillRect(0,0,w,h);
                g2.dispose();
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
           @Override
           public void mouseClicked(MouseEvent arg0) {
                   // TODO Auto-generated method stub
           @Override
           public void mouseEntered(MouseEvent arg0) {
                   // TODO Auto-generated method stub
           @Override
           public void mouseExited(MouseEvent arg0) {
                   // TODO Auto-generated method stub
           @Override
           public void mousePressed(MouseEvent event)
                   start = event.getPoint();
           @Override
           public void mouseReleased(MouseEvent event)
                   end = event.getPoint();
                   draw();
           @Override
           public void mouseDragged(MouseEvent e)
                   end=e.getPoint();
                   repaint();
           @Override
           public void mouseMoved(MouseEvent arg0) {
                   // TODO Auto-generated method stub
           @Override
           public void actionPerformed(ActionEvent e)
                   if(e.getSource()==elipse)
                           selected="elipse";
                   if(e.getSource()==line)
                           selected="line";
                   draw();
    }

  • Null pointer exception with inner class

    Hi everyone,
    I've written an applet that is an animation of a wheel turning. The animation is drawn on a customised JPanel which is an inner class called animateArea. The main class is called Rotary. It runs fine when I run it from JBuilder in the Applet Viewer. However when I try to open the html in internet explorer it gives me null pointer exceptions like the following:
    java.lang.NullPointerException      
    at sun.java2d.SunGraphics2D.drawImage(SunGraphics2D.java:2761)      
    at sun.java2d.SunGraphics2D.drawImage(SunGraphics2D.java:2722)      
    at Rotary$animateArea.paintComponent(Rotary.java:251)      
    at javax.swing.JComponent.paint(JComponent.java:808)      
    at javax.swing.JComponent.paintWithOffscreenBuffer(JComponent.java:4771)      
    at javax.swing.JComponent.paintDoubleBuffered(JComponent.java:4724)      
    at javax.swing.JComponent._paintImmediately(JComponent.java:4668)      
    at javax.swing.JComponent.paintImmediately(JComponent.java:4477)      
    at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:410)      
    at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(SystemEventQueueUtilities.java:117)      
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:178)      
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:448)      
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:197)      
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)      
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:144)      
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:136)      
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:99)
    Do inner classes have to be compiled seperately or anything?
    Thanks a million for you time,
    CurtinR

    I think that I am using the Java plugin ( Its a computer in college so I'm not certain but I just tried running an applet from the Swing tutorial and it worked)
    Its an image of a rotating wheel and in each sector of the wheel is the name of a person - when you click on the sector it goes red and the email window should come up (that doesn't work yet though). The stop and play buttons stop or start the animation. It is started by default.
    This is the code for the applet:
    import java.applet.*;
    import javax.swing.JApplet;
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.*;
    import java.awt.geom.*;
    import javax.swing.*;
    import java.awt.image.*;
    import java.util.StringTokenizer;
    import java.net.*;
    public class Rotary extends JApplet implements ActionListener, MouseListener
    public boolean rotating;
    private Timer timer;
    private int delay = 1000;
    private AffineTransform transform;
    private JTextArea txtTest; //temp
    private Container c;
    private animateArea wheelPanel;
    private JButton btPlay, btStop;
    private BoxLayout layout;
    private JPanel btPanel;
    public Image wheel;
    public int currentSector;
    public String members[];
    public int [][]coordsX, coordsY; //stores sector no. and x or y coordinates for that point
    final int TOTAL_SECTORS= 48;
    //creates polygon array - each polygon represents a sector on wheel
    public Polygon polySector1,polySector2,polySector3, polySector4, polySector5,polySector6,polySector7,polySector8,polySector9,polySector10,
    polySector11,polySector12,polySector13,polySector14,polySector15,polySector16,polySector17,polySector18,polySector19,polySector20,
    polySector21,polySector22,polySector23,polySector24,polySector25,polySector26,polySector27,polySector28,polySector29,polySector30,
    polySector31,polySector32,polySector33,polySector34,polySector35,polySector36,polySector37,polySector38,polySector39,polySector40,
    polySector41,polySector42,polySector43,polySector44,polySector45,polySector46,polySector47,polySector48;
    public Polygon polySectors[]={polySector1,polySector2,polySector3, polySector4, polySector5,polySector6,polySector7,polySector8,polySector9,polySector10,
                      polySector11,polySector12,polySector13,polySector14,polySector15,polySector16,polySector17,polySector18,polySector19,polySector20,
                      polySector21,polySector22,polySector23,polySector24,polySector25,polySector26,polySector27,polySector28,polySector29,polySector30,
                      polySector31,polySector32,polySector33,polySector34,polySector35,polySector36,polySector37,polySector38,polySector39,polySector40,
                      polySector41,polySector42,polySector43,polySector44,polySector45,polySector46,polySector47,polySector48};
    public void init()
    members = new String[TOTAL_SECTORS];
    coordsX= new int[TOTAL_SECTORS][4];
    coordsY= new int[TOTAL_SECTORS][4];
    currentSector = -1;
    rotating = true;
    transform = new AffineTransform();
    //***********************************Create GUI**************************
    wheelPanel = new animateArea(); //create a canvas where the animation will be displayed
    wheelPanel.setSize(600,580);
    wheelPanel.setBackground(Color.yellow);
    btPanel = new JPanel(); //create a panel for the buttons
    btPanel.setLayout(new BoxLayout(btPanel,BoxLayout.Y_AXIS));
    btPanel.setBackground(Color.blue);
    btPanel.setMaximumSize(new Dimension(30,580));
    btPanel.setMinimumSize(new Dimension(30,580));
    btPlay = new JButton("Play");
    btStop = new JButton("Stop");
    //txtTest = new JTextArea(5,5); //temp
    btPanel.add(btPlay);
    btPanel.add(btStop);
    // btPanel.add(txtTest); //temp
    c = getContentPane();
    layout = new BoxLayout(c,layout.X_AXIS);
    c.setLayout(layout);
    c.add(wheelPanel); //add panel and animate canvas to the applet
    c.add(btPanel);
    wheel = getImage(getDocumentBase(),"rotary2.gif");
    getParameters();
    for(int k = 0; k <TOTAL_SECTORS; k++)
    polySectors[k] = new Polygon();
    for(int n= 0; n<4; n++)
    polySectors[k].addPoint(coordsX[k][n],coordsY[k][n]);
    btPlay.addActionListener(this);
    btStop.addActionListener(this);
    wheelPanel.addMouseListener(this);
    startAnimation();
    public void mouseClicked(MouseEvent e)
    if (rotating == false) //user can only hightlight a sector when wheel is not rotating
    for(int h= 0; h<TOTAL_SECTORS; h++)
    if(polySectors[h].contains(e.getX(),e.getY()))
    currentSector = h;
    wheelPanel.repaint();
    email();
    public void mouseExited(MouseEvent e){}
    public void mouseEntered(MouseEvent e){}
    public void mouseReleased(MouseEvent e){}
    public void mousePressed(MouseEvent e){}
    public void email()
    try
    URL rotaryMail = new URL("mailto:[email protected]");
    getAppletContext().showDocument(rotaryMail);
    catch(MalformedURLException mue)
    System.out.println("bad url!");
    public void getParameters()
    StringTokenizer stSector;
    String parCoords;
    for(int i = 0; i <TOTAL_SECTORS; i++)
    {               //put member names in applet parameter list into an array
    members[i] = getParameter("member"+i);
    //separate coordinate string and store coordinates in 2 arrays
    parCoords=getParameter("sector"+i);
    stSector = new StringTokenizer(parCoords, ",");
    for(int j = 0; j<4; j++)
    coordsX[i][j] = Integer.parseInt(stSector.nextToken());
    coordsY[i][j] = Integer.parseInt(stSector.nextToken());
    public void actionPerformed(ActionEvent e)
    wheelPanel.repaint(); //repaint when timer event occurs
    if (e.getActionCommand()=="Stop")
    stopAnimation();
    else if(e.getActionCommand()=="Play")
    startAnimation();
    public void startAnimation()
    if(timer == null)
    timer = new Timer(delay,this);
    timer.start();
    else if(!timer.isRunning())
    timer.restart();
    Thanks so much for your help!

  • How to dynamically resize JOptionPane

    Hi All.
    I have a JOptionPane that contains a JPanel as the message (BorderLayout). The JPanel has a JComboBox on the north part and another JPanel in the center. When the combo changes selection the panel in the center is changed. Basically the combo represents some sort of selection and the panel is changed based on the selection to enter some specific search criteria.
    The problem I have is the search criteria panels are of different sizes. Therefore I want to resize the JOptionPane every time a combo selection is made.
    Does anybody know how to do this?
    nes

    Hi ICE,
    Here is some example code explaining my problem. Sorry it is a bit long but it explains my exact requirement.
    < 74philip the problem with calling JOptionPane.createInternalFrame is that it does not block until the Ok button is pressed. That is why I cannot use this solution >
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    public class TestFrame3
        extends JFrame
        implements ActionListener
        protected JPanel m_panel = new JPanel( new BorderLayout() );
        protected JPanel m_propertyPanel1 = new JPanel();
        protected JPanel m_propertyPanel2 = new JPanel();
        protected JPanel m_propertyPanel3 = new JPanel();
        protected JDesktopPane m_desktopPane = new JDesktopPane();
        protected JComboBox m_combo;
        protected JButton m_button;
        protected JOptionPane m_pane;
        public TestFrame3()
            initGUI();
        public void actionPerformed( ActionEvent event )
            if ( event.getSource() == m_combo )
                switch ( m_combo.getSelectedIndex() )
                    case ( 1 ):
                        m_panel.remove( m_propertyPanel1 );
                        m_panel.remove( m_propertyPanel3 );
                        m_panel.add( m_propertyPanel2, BorderLayout.CENTER );
                        break;
                    case ( 2 ):
                        m_panel.remove( m_propertyPanel1 );
                        m_panel.remove( m_propertyPanel2 );
                        m_panel.add( m_propertyPanel3, BorderLayout.CENTER );
                        break;
                    default:
                        m_panel.remove( m_propertyPanel2 );
                        m_panel.remove( m_propertyPanel3 );
                        m_panel.add( m_propertyPanel1, BorderLayout.CENTER );
                        break;
                //  THIS IS WHERE I WOULD LIKE TO RESIZE/PACK THE OPTION PANE
                //       m_pane.???????
                //  BUT HOW??
                m_panel.validate();
                m_panel.repaint();
            else if ( event.getSource() == m_button )
                m_pane = new JOptionPane();
                m_pane.showInternalConfirmDialog( m_desktopPane, m_panel,
                                                  "Test",
                                                  JOptionPane.OK_CANCEL_OPTION );
        private void initGUI()
            initSelectionCombo();
            initPropertyPanels();
            m_button = new JButton( "Go For It..." );
            m_button.addActionListener( this );
            getContentPane().setLayout( new BorderLayout() );
            getContentPane().add( m_desktopPane, BorderLayout.CENTER );
            getContentPane().add( m_button, BorderLayout.SOUTH );
            setSize( 800, 900 );
            show();
        private void initSelectionCombo()
            Vector v = new Vector();
            v.addElement( "Property Panel 1" );
            v.addElement( "Property Panel 2" );
            v.addElement( "Property Panel 3" );
            m_combo = new JComboBox( v );
            m_panel.add( m_combo, BorderLayout.NORTH );
            m_combo.addActionListener( this );
        private void initPropertyPanels()
            JLabel property1 = new JLabel( "Property 1" );
            JLabel property2 = new JLabel( "Property 2" );
            JLabel property3 = new JLabel( "Property 3" );
            m_propertyPanel1.setLayout( new GridBagLayout() );
            m_propertyPanel1.setBorder( BorderFactory.createLineBorder( Color.RED ) );
            m_propertyPanel1.add( property1,
                                  new GridBagConstraints( 1, 2, 1, 1, 1, 1,
                GridBagConstraints.EAST, GridBagConstraints.REMAINDER,
                new Insets( 3, 3, 3, 3 ), 0, 0 ) );
            m_propertyPanel1.add( property2,
                                  new GridBagConstraints( 2, 1, 1, 1, 1, 1,
                GridBagConstraints.EAST, GridBagConstraints.BOTH,
                new Insets( 3, 3, 3, 3 ), 0, 0 ) );
            m_propertyPanel1.add( property3,
                                  new GridBagConstraints( 6, 5, 1, 1, 1, 1,
                GridBagConstraints.EAST, GridBagConstraints.BOTH,
                new Insets( 3, 3, 3, 3 ), 0, 0 ) );
            JLabel property4 = new JLabel( "Property 4" );
            property4.setBounds( 10, 10, 100, 20 );
            JButton property5 = new JButton( "Property 5" );
            property5.setBounds( 40, 60, 190, 40 );
            m_propertyPanel2.setBorder( BorderFactory.createLineBorder( Color.GREEN ) );
            m_propertyPanel2.setLayout( null );
            m_propertyPanel2.add( property4 );
            m_propertyPanel2.add( property5 );
            m_propertyPanel3.setLayout( new FlowLayout( FlowLayout.CENTER, 10, 10 ) );
            m_propertyPanel3.setBorder( BorderFactory.createLineBorder( Color.BLUE ) );
            JButton property6 = new JButton( "Property 6" );
            JButton property7 = new JButton( "Property 7" );
            JButton property8 = new JButton( "Property 8" );
            JButton property9 = new JButton( "Property 9" );
            m_propertyPanel3.add( property6 );
            m_propertyPanel3.add( property7 );
            m_propertyPanel3.add( property8 );
            m_propertyPanel3.add( property9 );
            m_panel.add( m_propertyPanel1, BorderLayout.CENTER );
        public static void main( String args[] )
            SwingUtilities.invokeLater( new Runnable()
                public void run()
                    new TestFrame3();
    }nes

  • Application Paint() Help

    Hi, I am making a game, but sometimes when I activate it, I will get a nullpointerexception (varies greatly). Also, when I try to have the About class paint, it only works the second time through. I would greatly appriciate any help!
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    public class RPGMain extends Frame implements ActionListener, KeyListener, WindowListener, WindowStateListener, WindowFocusListener
         Image back;
         Graphics draw;
         MenuItem New, Open, Save, Quit, ttl, Directions, About;
         String gameState;
         Toolkit toolkit = Toolkit.getDefaultToolkit();
         newGame newGame;
         loadGame loadGame;
         saveGame saveGame;
         Directions dir;
         About about;
         Chara hero = new Chara();
         public static void main(String args[])
              System.out.println(" ");
              System.out.println("|        Cowboy  Bebop        |");
              System.out.println("|            Naruto           |");
              System.out.println("|            Trigun           |");
              System.out.println("|   Neon Genesis Evangelion   |");
              System.out.println("|           Inuyasha          |");
              System.out.println(" ");
              new RPGMain();
         public RPGMain()
              setTitle("RPG Main");
              setLayout(new FlowLayout());
              setSize(500, 500);
              setResizable(false);//This makes it so that the frame is always 500 x 500 pixels
              MenuBar menu = new MenuBar();
              Menu file = new Menu("File");
              Menu help = new Menu("Help");
              New = new MenuItem("New");
              Open = new MenuItem("Open");
              Save = new MenuItem("Save");
              Quit = new MenuItem("Quit");
              Directions = new MenuItem("Directions");
              About = new MenuItem("About");
              New.addActionListener(this);
              Open.addActionListener(this);
              Save.addActionListener(this);
              Quit.addActionListener(this);
              Directions.addActionListener(this);
              About.addActionListener(this);
              addWindowListener(this);
              addWindowStateListener(this);
              addWindowFocusListener(this);
              file.add(New);
              file.add(Open);
              file.add(Save);
              file.addSeparator();
              file.add(Quit);
              help.add(Directions);
              help.add(About);
              menu.add(file);
              menu.add(help);
              setMenuBar(menu);
              setVisible(true);
              back = createImage(500, 500);
              if (back == null)
                   System.out.println("\n|       Back is null...       |\n");
              draw = back.getGraphics();//The frame (or whatever) must be visible for this to work!!!
              newGame = new newGame();//creates an instance of *** and then gives it the varibles it needs
              newGame.set(back, draw, toolkit);
              loadGame = new loadGame();
              loadGame.set(back, draw, toolkit);
              saveGame = new saveGame();
              saveGame.set(back, draw, toolkit);
              about = new About();
              about.set(back, draw, toolkit);
              dir = new Directions();
              dir.set(back, draw, toolkit);
              gameState = "Title Screen";
              repaint();
         public void paint(Graphics g){}//leave empty to negate flashes
         public void update(Graphics g)
              if(gameState == "Title Screen"){draw.drawImage((toolkit.getImage("images/titleScreen.gif")), 0, 0, this);}
              else if(gameState == "New Game"){newGame.draw();}
              else if(gameState == "Load Game"){loadGame.draw();}
              else if(gameState == "Save Game"){saveGame.draw();}
              else if(gameState == "Dir"){dir.draw();}
              else if(gameState == "About"){about.draw();}
              try
                   g.drawImage(back,0,0,this);
              catch(NullPointerException e)
                   System.out.println("\n|NullPointerException in Paint|\n");
                   repaint();
    //Begin Window Event Block
         public void windowClosing(WindowEvent e)
              System.out.println("|       Window  Closing       |");
              System.exit(0);
         public void windowActivated(WindowEvent e)
              repaint();
              System.out.println("|      Window  Activated      |");
         public void windowDeactivated(WindowEvent e){System.out.println("|     Window  Deactivated     |");}
         public void windowOpened(WindowEvent e)
              repaint();
              System.out.println("|        Window Opened        |");
         public void windowClosed(WindowEvent e){System.out.println("|        Window Closed        |");}
         public void windowDeiconified(WindowEvent e)
              repaint();
              System.out.println("|     Window  Deiconified     |");
         public void windowIconified(WindowEvent e){System.out.println("|      Window  Iconified      |");}
         public void windowGainedFocus(WindowEvent e)
              repaint();
              System.out.println("|     Window Gained Focus     |");
         public void windowLostFocus(WindowEvent e){System.out.println("|      Window Lost Focus      |");}
         public void windowStateChanged(WindowEvent e)
              repaint();
              System.out.println("|     Window State Change     |");
    //End Window Event Block
    //Begin Action Performed Block
         public void actionPerformed(ActionEvent e)
              if(e.getSource() == New)
                   gameState = "New Game";
                   repaint();
              if(e.getSource() == Open)
                   gameState = "Load Game";
                   repaint();
              if(e.getSource() == Save)
                   gameState = "Save Game";
                   repaint();
              if(e.getSource() == Quit)
                   System.out.println("|     User closing window     |\n");
                   System.exit(0);
              if(e.getSource() == Directions)
                   gameState = "Dir";
                   repaint();
              if(e.getSource() == About)
                   gameState = "About";
                   repaint();
    //End Action Performed Block
    //Begin Key Input Block
         public void keyTyped(KeyEvent e)
         public void keyPressed(KeyEvent e)
         public void keyReleased(KeyEvent e)
    //End Key Input Block
    import java.awt.*;
    import java.awt.event.*;
    public class About extends Panel
         Graphics draw;
         Image back;
         Toolkit toolkit;
         public void set(Image a, Graphics b, Toolkit tool)
              back = a;
              draw = b;
              toolkit = tool;
         public void draw()
              System.out.println("|            About            |");
              draw.setColor(Color.black);
              draw.fillRect(0,0,500,500);
              draw.setColor(Color.white);
              draw.drawImage(toolkit.getImage("images/chaos.gif"), 205, 150, this);
              Font foo = new Font("Courier", Font.PLAIN, 24);
              draw.setFont(foo);
              draw.drawString("Choas Programming", 125, 300);
              draw.drawString("-----------------", 125, 320);
              draw.drawString("Head Programmer", 140, 340);
              foo = new Font("Arial", Font.PLAIN, 12);
              draw.setFont(foo);
    public class Chara
         String name;//Character's name
         String property;//Character's elemental property
         String race;//Character's type
         String job;//Character's job
         String status;//Character's status
         String equipe[];//Character's equipement
         String items[][];//Character's items {Useables, Equipes, Other}
         int hp[];//Min/Max HP
         int mp[];//Min/Max SP
         int strength[];//Current/Normal/Race Bonus
         int agility[];//Current/Normal/Race Bonus
         int vitality[];//Current/Normal/Race Bonus
         int intelligence[];//Current/Normal/Race Bonus
         int dexterity[];//Current/Normal/Race Bonus
         int luck[];//Current/Normal/Race Bonus
    import java.awt.*;
    import java.awt.event.*;
    public class Directions extends Panel
         Graphics draw;
         Image back;
         Toolkit toolkit;
         public void set(Image a, Graphics b, Toolkit tool)
              back = a;
              draw = b;
              toolkit = tool;
         public void draw()
              System.out.println("|          Direction          |");
              draw.setColor(Color.green);
              draw.fillRect(0,0,500,500);
              draw.setColor(Color.black);
              draw.drawString("|        Directions           |", 100, 150);
    import java.awt.*;
    import java.awt.event.*;
    public class loadGame extends Panel
         Graphics draw;
         Image back;
         Toolkit toolkit;
         public void set(Image a, Graphics b, Toolkit tool)
              back = a;
              draw = b;
              toolkit = tool;
         public void draw()
              System.out.println("|     User loading a game     |");
              draw.setColor(Color.black);
              draw.fillRect(0,0,500,500);
              draw.setColor(Color.green);
              draw.drawString("|     User loading a game     |", 100, 150);
    import java.awt.*;
    import java.awt.event.*;
    public class newGame extends Panel
         Graphics draw;
         Image back;
         Toolkit toolkit;
         public void set(Image a, Graphics b, Toolkit tool)
              back = a;
              draw = b;
              toolkit = tool;
         public void draw()
              System.out.println("|     User starting a game    |");
              draw.setColor(Color.white);
              draw.fillRect(0,0,500,500);
              draw.setColor(Color.black);
              draw.drawString("|   User starting a new game  |", 100, 150);
    import java.awt.*;
    import java.awt.event.*;
    public class saveGame extends Panel
         Graphics draw;
         Image back;
         Toolkit toolkit;
         public void set(Image a, Graphics b, Toolkit tool)
              back = a;
              draw = b;
              toolkit = tool;
         public void draw()
              System.out.println("|      User saving a game     |");
              draw.setColor(Color.red);
              draw.fillRect(0,0,500,500);
              draw.setColor(Color.black);
              draw.drawString("|     User saving a game      |", 100, 150);
    }

    Just a guess: instead of storing a reference to a Graphics object and using it to paint at whatever location in the code, move painting code into an object's paint() method and use the Graphics object passed into paint().
    i'm also currently writing a game, and got NullPointerExceptions galore when i tried storing a Graphics reference. Also, this approach helps separate game-state-manipulation code from display code.

  • Zooming the selected rectangle on an image

    hi,
    my problem is that once i'm able to zoom my image ,if i want to zoom it further either on mouse click or selecting a rectangle again on mousedrag,it throws an exception coz i'm not able to get either size or bofferedimage from the once zoomed image.
    do u have any suggestions:
    i'm sending my latest code
    private Graphics2D createGraphics2D(int w, int h) {
    Graphics2D g2 = null;
    if (bimg == null || bimg.getWidth() != w || bimg.getHeight() != h) {
    bimg = (java.awt.image.BufferedImage) createImage(w, h);
    g2 = bimg.createGraphics();
    g2.setBackground(getBackground());
    g2.clearRect(0, 0, w, h);
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
    RenderingHints.VALUE_ANTIALIAS_ON);
    return g2;
    public void update(Graphics g) {
    paint(g);
    public void paint(Graphics g) {
    super.paint(g);
    try{
    t=new AffineTransform();
    //////added 09aug
    Dimension d = getSize();
    System.out.println(d);
    if(!first_paint){
    setScale(d.width,d.height - DRG_YPOS);
    first_paint = true;
    if(!image1)
    Graphics2D g2 = createGraphics2D(d.width, d.height -DRG_YPOS);
    g2.translate(((d.width/2) - ((zoomx*maxx + zoomx*minx)/2))
    + zoomx*scrollx,
    (((d.height-DRG_YPOS)/2))+scrolly);
    g2.scale(zoomx,zoomy);
    draw(d.width, (int)(maxy - (maxy- miny)/2) , g2);
    g.drawImage(bimg, 0, DRG_YPOS, this);
    System.out.println("image drawn for the "+counter+"time");
    counter++;
    System.out.println("counter is"+counter);
    System.out.println("image1 is"+image1);
    file://t= g2.getTransform();
    if(fzoom1)
    g.setColor(Color.red);
    g.drawRect(beginX,beginY,end1X-beginX,end1Y-beginY);
    System.out.println("drawing rect");
    if(fzoom){
    wx=beginX;
    wy=beginY;
    ww=end1X-beginX;
    wh=end1Y-beginY;
    bi = bimg.getSubimage(wx,wy,ww,wh);
    System.out.println("hello 2d");
    System.out.println(wx+","+wy+","+ww+","+wh);
    Dimension d1=getSize();
    Graphics2D g2d = bi.createGraphics();
    // g2d.setBackground(getBackground());
    int w=500;
    int h=500;
    System.out.println(w+","+h);
    System.out.println("g2d"+g2d);
    System.out.println("settransform callrd");
    // zoomFactor *=1;
    g2d.translate(100.0f, 100.0f);
    g2d.scale(zoomFactor, zoomFactor);
    System.out.println("scale called"+zoomFactor);
    file://zoomFactor++;
    g.drawImage(bi,50,50,w,h,this);
    System.out.println("w,h,bi"+w+","+h+","+bi);
    file://repaint();
    image1=true;
    file://zoomFactor++;
    file://fzoom=false;
    g2.dispose();
    }catch(Exception e)
    System.out.println("exception"+e);
    class IMS2DFrameMouseAdapter extends MouseAdapter implements MouseMotionListener{
    int mx;
    int my;
    int endx,endy;
    int X;
    int Y;
    Point point;
    public void mouseClicked( MouseEvent event ) {
    if(select)
    Dimension d = getSize();
    AffineTransform at = new AffineTransform();
    at.setToIdentity();
    at.translate(((d.width/2) - ((zoomx*maxx + zoomx*minx)/2))
    + zoomx*scrollx,
    (((d.height-DRG_YPOS)/2))+scrolly);
    at.scale(zoomx,zoomy);
    Point src = new Point(event.getX(),event.getY() - DRG_YPOS);
    Point pt = new Point();
    try{
    at.inverseTransform( src, pt);
    catch( NoninvertibleTransformException e)
    e.printStackTrace();
    pt.setLocation(pt.getX(), (maxy - (maxy- miny)/2 - pt.getY()));
    hitObject(pt);
    /*if(fence_zoom){
    fzoom2=true;
    }else
    fzoom2=false;
    public void mousePressed( MouseEvent event ) {
    if(fence_zoom)
    System.out.println("mouse Pressed");
    beginX = event.getX();
    beginY = event.getY();
    repaint();
    public void mouseReleased( MouseEvent event ) {
    end1X = event.getX();
    end1Y = event.getY();
    System.out.println("ENDX---"+endx);
    System.out.println("endy-----"+endy);
    if(translation)
    translatedrawing(endx - startx,endy - starty);
    if(fence_zoom){
    System.out.println("mouse released");
    file://end1X = event.getX();
    // end1Y = event.getY();
    fzoom=true;
    repaint(); file://updateSize(event);
    else{
    fzoom=false;
    public void mouseDragged(MouseEvent event) {
    if(fence_zoom){
    end1X = event.getX();
    end1Y = event.getY();
    fzoom1=true;
    System.out.println("mouse dragged");
    repaint();
    else {
    fzoom1=false;
    public void mouseMoved(MouseEvent event)
    thanks
    sangeeta
    "Gustavo Henrique Soares de Oliveira Lyrio" wrote:
    I think you are using the wrong drawimage method. If you have the selection retangle coordinates, you will need a method that draw this selection in a new retangle selection (your canvas or panel)
    Where goes my paintMethod:
    protected void paintComponent(Graphics g)
    g.drawImage(image, START_WINDOW_X, START_WINDOW_Y, WINDOW_X, WINDOW_Y, px1, py1, px2, py2, this);
    Take a look in the drawimage methods in the java web page. I think it will help.
    []`s
    Gustavo
    ----- Original Message -----
    From: sangeetagarg
    To: Gustavo Henrique Soares de Oliveira Lyrio
    Sent: Thursday, August 16, 2001 9:14 AM
    Subject: Re: Re: re:zoom in 2d
    i'm sending u the paint method.but still i'm not able to select the desired area .it zooms the while image.tell me if there is any error in the code.
    file://if(fence_zoom)
    if(fzoom1 )
    if (currentRect != null) {
    System.out.println("hello");
    g.setColor(Color.white);
    g.drawRect(rectToDraw.x, rectToDraw.y,
    rectToDraw.width - 1, rectToDraw.height - 1);
    System.out.println("drawing rectangle");
    fzoom1=false;
    if(fzoom)
    bi = bimg.getSubimage(rectToDraw.x, rectToDraw.y, rectToDraw.width, rectToDraw.height);
    System.out.println(rectToDraw.x+","+ rectToDraw.y+","+rectToDraw.width+","+ rectToDraw.height);
    Graphics2D g2d = bi.createGraphics();
    g2d.setBackground(getBackground());
    g2d.clearRect(0, 0,0,0 );
    file://ZoomIn();
    file://t= g2d.getTransform();
    file://g2d.setTransform(t);
    System.out.println("settransform callrd");
    // zoomFactor *=1;
    g2d.translate(100.0f, 0.0f);
    g2d.scale(zoomx, zoomy);
    System.out.println("scale called"+zoomFactor);
    zoomx += ZOOMSTEP;
    zoomy += ZOOMSTEP;
    file://zoomFactor+=zoomFactorupdate;
    g.drawImage(bi, 0, 0, this);
    // g.drawImage(bi,10,10,this);
    repaint();
    fzoom=false;
    thanks
    sangeeta

    Display first your image on an invisible label. Once displayed you can get the size of the image and you can redimension it as you want.
    Bye Alessio

  • Class final project need help

    I have this final project due Monday for my java class. I'm having some trouble with this zoom slider which gives me 2 errors about "cannot find symbol". I've tried just about eveything i can think of and i cant come up with the solution... Here is my code:
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JFrame;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.event.*;
    import javax.swing.*;
    import java.util.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.io.*;
    public class MenuExp extends JFrame implements MouseMotionListener,MouseListener,ActionListener
    /* creates the file menus and submenus */
         JMenu fileMenu = new JMenu("File");
        JMenu plotMenu = new JMenu("Plotting");
        JMenu helpMenu = new JMenu("Help");
        JMenuItem loadAction = new JMenuItem("Load");
        JMenuItem saveAction = new JMenuItem("Save");
        JMenuItem quitAction = new JMenuItem("Quit");
        JMenuItem colorAction = new JMenuItem("Segment Colors");
        JMenuItem helpAction = new JMenuItem("Instructions");
        JButton button;
         Cursor previousCursor = new Cursor(Cursor.DEFAULT_CURSOR);
        JLabel cLabel;
        JPanel cPanel;
        private String filename = null;  // set by "Open" or "Save As"
        double scale = 1.0;
        public MenuExp(File f)
            setTitle("PlotVac");
            Container pane = getContentPane();
            ImageIcon chartImage = new ImageIcon(f.getName());
              ChartDisplay chartLabel = new ChartDisplay(chartImage);
              JScrollPane scpane = new JScrollPane(chartLabel);
              pane.add(scpane, BorderLayout.CENTER);
              chartLabel.addMouseListener(this);  //change cursor
              chartLabel.addMouseMotionListener(this); //handle mouse movement
              JPanel cPanel = new JPanel();
              cLabel= new JLabel("cursor outside chart");
              cPanel.add(cLabel);
              pane.add(cPanel, BorderLayout.NORTH);
              button = new JButton("Clear Route");
            button.setAlignmentX(Component.LEFT_ALIGNMENT);
            button.setFont(new Font("serif", Font.PLAIN, 14));
              cPanel.add(button);
              getContentPane().add(getSlider(), "Last");
    /* Creates a menubar for a JFrame */
            JMenuBar menuBar = new JMenuBar();
    /* Add the menubar to the frame */
            setJMenuBar(menuBar);
    /* Define and add three drop down menu to the menubar */
            menuBar.add(fileMenu);
            menuBar.add(plotMenu);
            menuBar.add(helpMenu);
    /* Create and add simple menu item to the drop down menu */
            fileMenu.add(loadAction);
            fileMenu.add(saveAction);
            fileMenu.addSeparator();
            fileMenu.add(quitAction);
            plotMenu.add(colorAction);
            helpMenu.add(helpAction);
             loadAction.addActionListener(this);
             saveAction.addActionListener(this);
             quitAction.addActionListener(this);
        private JSlider getSlider()
            JSlider slider = new JSlider(25, 200, 100);
            slider.setMinorTickSpacing(5);
            slider.setMajorTickSpacing(25);
            slider.setPaintTicks(true);
            slider.setPaintLabels(true);
            slider.addChangeListener(new ChangeListener()
                public void stateChanged(ChangeEvent e)
                     int value = ((JSlider)e.getSource()).getValue();
                     cPanel.zoom(value/100.0);
            return slider;
        private void zoom(double scale)
            this.scale = scale;
            cPanel.setToScale(scale, scale);
            repaint();
    /* Handle menu events. */
           public void actionPerformed(ActionEvent e)
              if (e.getSource() == loadAction)
                   loadFile();
             else if (e.getSource() == saveAction)
                    saveFile(filename);
             else if (e.getSource() == quitAction)
                   System.exit(0);
    /** Prompt user to enter filename and load file.  Allow user to cancel. */
    /* If file is not found, pop up an error and leave screen contents
    /* and filename unchanged. */
           private void loadFile()
             JFileChooser fc = new JFileChooser();
             String name = null;
             if (fc.showOpenDialog(null) != JFileChooser.CANCEL_OPTION)
                    name = fc.getSelectedFile().getAbsolutePath();
             else
                    return;  // user cancelled
             try
                    Scanner in = new Scanner(new File(name));  // might fail
                    filename = name;
                    while (in.hasNext())
                    in.close();
             catch (FileNotFoundException e)
                    JOptionPane.showMessageDialog(null, "File not found: " + name,
                     "Error", JOptionPane.ERROR_MESSAGE);
    /* Save named file.  If name is null, prompt user and assign to filename.
    /* Allow user to cancel, leaving filename null.  Tell user if save is
    /* successful. */
           private void saveFile(String name)
             if (name == null)
                    JFileChooser fc = new JFileChooser();
                    if (fc.showSaveDialog(null) != JFileChooser.CANCEL_OPTION)
                      name = fc.getSelectedFile().getAbsolutePath();
             if (name != null)
                  try
                      Formatter out = new Formatter(new File(name));  // might fail
                        filename = name;
                      out.close();
                      JOptionPane.showMessageDialog(null, "Saved to " + filename,
                        "Save File", JOptionPane.PLAIN_MESSAGE);
                    catch (FileNotFoundException e)
                      JOptionPane.showMessageDialog(null, "Cannot write to file: " + name,
                       "Error", JOptionPane.ERROR_MESSAGE);
    /* implement MouseMotionListener methods */     
         public void mouseDragged(MouseEvent arg0)
         public void mouseMoved(MouseEvent arg0)
              int x = arg0.getX();
              int y = arg0.getY();
              cLabel.setText("X pixel coordiate: " + x + "     Y pixel coordinate: " + y);
    /*      implement MouseListener methods */
         public void mouseClicked(MouseEvent arg0)
         public void mouseEntered(MouseEvent arg0)
             previousCursor = getCursor();
             setCursor(new Cursor (Cursor.CROSSHAIR_CURSOR) );
         public void mouseExited(MouseEvent arg0)
             setCursor(previousCursor);
             cLabel.setText("cursor outside chart");
         public void mousePressed(MouseEvent arg0)
         public void mouseReleased(MouseEvent arg0)
    /* main method to execute demo */          
        public static void main(String[] args)
             File chart = new File("teritory-map.gif");
            MenuExp me = new MenuExp(chart);
            me.setSize(1000,1000);
            me.setLocationRelativeTo(null);
            me.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            me.setVisible(true);
    }and this is the other part:
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.BasicStroke;
    import java.awt.Color;
    import java.awt.geom.Line2D;
    import javax.swing.Icon;
    import javax.swing.JLabel;
    public class ChartDisplay extends JLabel
    /* line at 45 degrees from horizontal */
         private int x1=884, y1=290, x2=1084, y2=490;
    /* horizontal line - x3 same as x2 */
         private int x3=1084, y3=490, x4=1384, y4=490;
         public ChartDisplay(Icon arg0)
              super(arg0);
    /* This overrides inherited method to draw on image */
         protected void paintComponent(Graphics arg0)
              super.paintComponent(arg0);
    /* Utility method to draw a "dot" at line ends */
         private void drawDot(Graphics g, Color c, int xDot, int yDot, int sizeDot)
              Color previousColor = g.getColor();
              g.setColor(c);
                g.fillOval(xDot-(sizeDot/2), yDot-(sizeDot/2), sizeDot, sizeDot);
                g.setColor(previousColor);   
    /* Utility method to draw a wider line */
         private void drawLine(Graphics g, Color c, int lineWidth, int xStart, int yStart, int xEnd, int yEnd)
              Color previousColor = g.getColor(); // save previous color
              Graphics2D g2 = (Graphics2D) g;  // access 2D properties
                g2.setPaint(c);  // use color provided as parameter
             g2.setStroke(new BasicStroke(lineWidth)); // line width
             g.setColor(previousColor);    // restore previous color
    }I've basically used the structure of other programs and incorporated them into my design. If anyone knows how i can fix the errors please let me know. The errors are found in line 91 and 100 which is where the zoom slider is occuring.
    **NOTE** the program isnt fully functional in the sense that there are buttons and tabs etc.. that are missing action listeners and things like that.
    Thanks for the help
    Edited by: gonzale3 on Apr 17, 2008 6:55 PM

    gonzale3 wrote:
    The code was on the forums as the person who posted it was using it as an example in a program he used... i didnt borrow the entire code im just using the way he did the zoom method and added it into my program. I wasnt aware that it was used in the JPanel class. C'mon, it's your program. If you don't know what you are doing in this program, then you shouldn't be using it.
    That is why im asking if someone can show me the right way to implement a zoom slider into my program or maybe give me an example where its used.What the fuck is a zoom slider???
    Edited by: Encephalopathic on Apr 17, 2008 8:00 PM

  • Configuring Qt creator for AI plugin development

    I tried creating AI plugin using
    - Visual Studio Premium 2010
    - Visual Studio Addin for Qt
    - QWinWidget for Qt 4.8
    - Qt 4.8 for windows
    - Windows 7 32 bit
    However,  I could not compile the plugin for 64 bit edition as the Qt addin for visual studio do not support Qt 4.8 for 64 bit compilation.
    I cannot switch to Qt 5.1 as compatible QWinWidget is not available there.
    So I decided to migrate to Qt Creator 2.8 IDE instead of visual studio and bypass the addin.
    I could migrate the VS project to a Qt project and compile it. I get a .aip file now.
    However, this AI plugin is not loaded by Illustrator.exe
    I added the following to get my aip file.
    TARGET_EXT = .aip
    TEMPLATE = lib
    CONFIG += dll embed_manifest_dll
    However,
    1. the plugin main was not exposed. So, tried
    DEF_FILE += "Definitions/PluginMain.def"
    Dependency walker now shows "PluginMain", but AI cannot load the plugin.
    Qt documentation tell, use "DEF_FILE" only with "app" template. Is this the reason for the failure ?
    What is the solution ?
    2. How to get the 64 bit target in Qt creator ?
    I tried      QMAKE_TARGET.arch = x86_64 but the target was 32 bit (checked in dependency walker).
    My OS is 32 bit win 7. Is this the reason I cannot get 64 bit target ?
    Do I need to install Qt environment on 64bit OS to get the 64 bit target ??
    Message was edited by: Dataset

    I implemented Qt as a GUI module inside an Adobe Illustrator Plugin for Mac OS X.
    Half of the time, after boot up, the button click results in successful click event delivery. Once successful, it never failed, until next application reboots. When fails, it always crashes on the first button click and crashes at the execution of QApplication::flush(); inside QAbstractButton::mousePressEvent(QMouseEvent *e) function from qabstracbutton.cpp.
    Do you handle any mouse event for button at all other than connect the button to a callback?
    The following is code I written to instantiate QApplication and Qt GUI components to reside inside an container provided by Illustrator’s API:
    GetPlatformWindow returns dlgHnd which is NSView of a GUI container.
    pEditWidget is a QWidget class containing a few QPushButton.
    SetNotifyProc calls Qt connect method to setup button click callback.
    At startup Illustrator application loads the following codes which reside in a dll module. int argc; char **argv=NULL;
    QApplication::setAttribute(Qt::AA_MacPluginApplication);
    QApplication::setAttribute(Qt::AA_ImmediateWidgetCreation);
    g->qtApp = new QApplication(argc, argv);
    AIPanelPlatformWindow dlgHnd = NULL;
    sAIPanel->GetPlatformWindow(this->fPanel, dlgHnd);
    g->pEditWidget = new qtEditWidget();
    g->pEditWidget->sMenuItem->SetNotifyProc(g->pEditWidget->normalBtn, normalBtnClick);
    g->pEditWidget->sMenuItem->SetNotifyProc(g->pEditWidget->relativeBtn, relativeBtnClick);
    //set panel to contain qt stuffs NSView* newView = (NSView*)g->pEditWidget->winId(); [dlgHnd setFrame:[newView frame]]; [dlgHnd addSubview:newView]; g->pEditWidget->show();
    After show(), the application show the buttons. When fail, always break in this mousePressEvent() function at event flush() function (Code from Qt 4.8.5 source):
    void QAbstractButton::mousePressEvent(QMouseEvent *e)
    { Q_D(QAbstractButton); if (e->button() != Qt::LeftButton) { e->ignore(); return; } if (hitButton(e->pos())) { setDown(true); d->pressed = true; repaint(); //flush paint event before invoking potentially expensive operation
    **********my note: after flush() EXE_BAD_ACCESS (code = 13, address = 0×0)**************** QApplication::flush(); d->emitPressed(); e->accept(); } else { e->ignore(); }
    Here is the dump from within Xcode 4.6 in Thread 1:
    Thread 1, Queue : com.apple.main-thread
    #0 0×000000011f68298d in QHashData::nextNode(QHashData::Node*) at /temp/qt4.8.5src/src/corelib/tools/qhash.cpp:294
    #1 0×000000011fa6f4d7 in QHash<QWidget*, QHashDummyValue>::const_iterator::operator++() at /temp/qt4.8.5src/src/gui/../../include/QtCore/../../src/corelib/tools/qhash.h:427
    #2 0×000000011fa6f510 in QSet<QWidget*>::const_iterator::operator++() at /temp/qt4.8.5src/src/gui/../../include/QtCore/../../src/corelib/tools/qset.h:155
    #3 0×000000011fa70b34 in QSet<QWidget*>::toList() const at /temp/qt4.8.5src/src/gui/../../include/QtCore/../../src/corelib/tools/qset.h:303
    #4 0×000000011fa59060 in QApplication::allWidgets() at /temp/qt4.8.5src/src/gui/kernel/qapplication.cpp:2180
    #5 0×000000011fa590a6 in QApplication::topLevelWidgets() at /temp/qt4.8.5src/src/gui/kernel/qapplication.cpp:2154
    #6 0×000000011f9b5900 in QEventDispatcherMac::flush() at /temp/qt4.8.5src/src/gui/kernel/qeventdispatcher_mac.mm:766
    #7 0×000000011f847f97 in QCoreApplication::flush() at /temp/qt4.8.5src/src/corelib/kernel/qcoreapplication.cpp:690
    #8 0×000000012029d4e4 in QAbstractButton::mousePressEvent(QMouseEvent*) at /temp/qt4.8.5src/src/gui/widgets/qabstractbutton.cpp:1097
    #9 0×000000011fb06b10 in QWidget::event(QEvent*) at /temp/qt4.8.5src/src/gui/kernel/qwidget.cpp:8385
    #10 0×000000012029d836 in QAbstractButton::event(QEvent*) at /temp/qt4.8.5src/src/gui/widgets/qabstractbutton.cpp:1082
    #11 0×00000001203f1c81 in QPushButton::event(QEvent*) at /temp/qt4.8.5src/src/gui/widgets/qpushbutton.cpp:683
    #12 0×000000011fa4fc62 in QApplicationPrivate::notify_helper(QObject*, QEvent*) at /temp/qt4.8.5src/src/gui/kernel/qapplication.cpp:4562
    #13 0×000000011fa5100a in QApplication::notify(QObject*, QEvent*) at /temp/qt4.8.5src/src/gui/kernel/qapplication.cpp:4105
    #14 0×000000011f84c9aa in QCoreApplication::notifyInternal(QObject*, QEvent*) at /temp/qt4.8.5src/src/corelib/kernel/qcoreapplication.cpp:953
    #15 0×000000011fa6f3d7 in QCoreApplication::sendSpontaneousEvent(QObject*, QEvent*) at /temp/qt4.8.5src/src/gui/../../include/QtCore/../../src/corelib/kernel/qcoreapplication.h :234
    #16 0×000000011fa61205 in QApplicationPrivate::sendMouseEvent(QWidget*, QMouseEvent*, QWidget*, QWidget*, QWidget**, QPointer<QWidget>&, bool) at /temp/qt4.8.5src/src/gui/kernel/qapplication.cpp:3171
    #17 0×000000011f9ab812 in qt_mac_handleMouseEvent(NSEvent*, QEvent::Type, Qt::MouseButton, QWidget*, bool) at /temp/qt4.8.5src/src/gui/kernel/qt_cocoa_helpers_mac.mm:1271
    #18 0×000000011f99086a in -[QCocoaView mouseDown:] at /temp/qt4.8.5src/src/gui/kernel/qcocoaview_mac.mm:555
    #19 0×00007fff9255950e in -[NSWindow sendEvent:] ()
    #20 0×0000000105bfa558 in OWLRemoveObjCExceptionCallback ()
    #21 0×0000000105bfc961 in OWLRemoveObjCExceptionCallback ()
    #22 0×00007fff92555644 in -[NSApplication sendEvent:] ()
    #23 0×000000011f9a1646 in -[QNSApplication qt_sendEvent_replacement:] at /temp/qt4.8.5src/src/gui/kernel/qcocoaapplication_mac.mm:178
    #24 0×0000000108612145 in -[DVAMacApplication sendEvent:] ()
    #25 0×0000000108e981cc in -[ExoMacApplication sendEvent:] ()
    #26 0×00007fff9246b21a in -[NSApplication run] ()
    #27 0×0000000108e96807 in exo::app::OS_AppBase::RunEventLoop() ()
    #28 0×000000010075b698 in 0×10075b698 ()
    #29 0×00000001006ff385 in 0×1006ff385 ()
    #30 0×00000001006ef5d4 in 0×1006ef5d4 ()
    #31 0×00000001001635f8 in 0×1001635f8 ()
    This problem is repeatable and happens frequently (after few application boot ups).

Maybe you are looking for