JPanel Resizes Self

This is from fairly large code so I'm trying to pull the important stuff out of two classes:
MainM.class:
    private void bPlayActionPerformed(java.awt.event.ActionEvent evt) {
        game=new Game(WD+"\\songs\\"+cmbSong.getSelectedItem(),this,settings.FPS,getWidth(),getHeight());
        JPMain.setVisible(false);
        java.awt.GridBagConstraints gc=new java.awt.GridBagConstraints();
        gc.gridx=0;gc.gridy=0;
        getContentPane().add(game,gc);
        game.animator.start();
    }Game.class:
    public Game(String SongFile, MainM JMain, int iFPS, int Width, int Height) {
        addKeyListener(this);
        setVisible(true);
        setMinimumSize(new Dimension(Width,Height));
        setSize(Width,Height);
        animator=new Thread(this);
    public void run() {
        // Remember the starting time
        long tm = System.currentTimeMillis();
        while (Thread.currentThread() == animator) {
            // Display the next frame of animation.
            manpaint();
            // Delay depending on how far we are behind.
            try {
                tm += 1000/FPS;
                Thread.sleep(Math.max(0, tm - System.currentTimeMillis()));
            } catch (InterruptedException e) {
                break;
            // Advance the frame
            CurBeat+=BPF;
    public void manpaint() {
        Graphics g=getGraphics();
        int x,y,xunit,yunit,dx,dy;
        xunit=getWidth()/ScaleX;
        yunit=getHeight()/ScaleY;
        // Now draw the image scaled.
        System.out.println(getWidth());
        g.drawImage(Pics[0],0,0,getWidth(),getHeight(),this);
        g.drawImage(Pics[1],ScaleX*(CurTrack*(ScaleX/10)),yunit*(ScaleY-7),yunit*10,yunit*4,this);
        for(x=0;x<Tracks.length;x++){
            for(y=0;y<Tracks[x].CurBeats.length;y++){
                if (Tracks[x].CurBeats[y][0]!=-1){
                    dx=xunit*(x*(ScaleX/Tracks.length))+xunit*x+xunit*3*Tracks[x].CurBeats[y][1];
                    dy=yunit*y+yunit*(-2)+(int)(yunit*(CurBeat-(int)CurBeat));
                    g.drawImage(Pics[2],dx,dy,xunit*2,yunit*2,this);
        update(g);
    }And the problem is:
In this last method there is a line "System.println.(getwidth());" for the first time it prints 400, the correct width, but after the first print it starts printing 10's, so in accordance, on the screen it draws the first frame correctly and then refreshes a tiny fram in the center of the screen 10 pixels wide and tall. There is no code to resize this panel other than when it is initialized, is there any reason it should be resizing itself?

solved the resizing problem, have to set preferred size instead of just using setsize (for the record)

Similar Messages

  • Dynamic JPanel resizing?

    Hey all,
    I'm displaying an image in a JPanel and I want the user to be able to resize the panel by dragging with the mouse as you would say in Photoshop. Obviously the image should resize to fill the panel as it's enlarged (showing resizing handles on the image/panel would also be good).
    For bonus points:
    I also have a draggable method so the image can be moved on the screen, the resizing method should only be applied when the mouse is over the edges of the image/panel.
    Thanks for your suggestions.

    For bonus points:
    I also have a draggable method so the image can be moved on Ooh bonus points! Now ur talking
    Search google for my Resizeable.java class. This should take care of resizing. As far as scaling the image, that call all be done in the paintComponent method. But actually I've got a class for this too
    You are welcome to use and modify this class, but please don't change the package or take credit for it as your own work (except where you have modified it)
    ExpandableImagePanel.java
    ======================
    package tjacobs.ui.ex;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Image;
    import java.awt.LayoutManager;
    import java.awt.Toolkit;
    import javax.swing.JPanel;
    import tjacobs.ui.fc.FileExtensionFilter;
    import tjacobs.ui.swing_ex.JFileChooser;
    import tjacobs.ui.util.WindowUtilities;
    * @deprecated use BackgroundImagePanel
    * @see BackgroundImagePanel
    * @author HP_Administrator
    public class ExpandableImagePanel extends JPanel {
         private static final long serialVersionUID = 1L;
         Image mOriginal;
         public ExpandableImagePanel() {
         public ExpandableImagePanel(Image im) {
              this();
              setImage(im);
         public ExpandableImagePanel(LayoutManager arg0) {
              super(arg0);
         public ExpandableImagePanel(boolean arg0) {
              super(arg0);
         public ExpandableImagePanel(LayoutManager arg0, boolean arg1) {
              super(arg0, arg1);
         public void setImage(Image im) {
              mOriginal = im;
         public Image getImage() {
              return mOriginal;
         public void paintComponent(Graphics g) {
              //super.paintComponent(g);
              g.clearRect(0, 0, getWidth(), getHeight());
              g.drawImage(mOriginal, 0, 0, getWidth(), getHeight(), null);
         public static void main(String[] args) {
              JFileChooser chooser = new JFileChooser();
              chooser.addChoosableFileFilter(new FileExtensionFilter.ImageFilter());
              int approve = chooser.showOpenDialog(null);
              if (approve == javax.swing.JFileChooser.APPROVE_OPTION) {
                   //BufferedImage im = new BufferedImage(chooser.getSelectedFile());
                   Image im = Toolkit.getDefaultToolkit().createImage(chooser.getSelectedFile().getAbsolutePath());
                   ExpandableImagePanel p = new ExpandableImagePanel(im);
                   p.setPreferredSize(new Dimension(300,300));
                   WindowUtilities.visualize(p);
    }

  • Weird JPanel Resizing Problem

    This program works as I want it to with one exception: sometimes when resizing the frame, the contained JPanels do not fully cover the frame's BorderLayout center region. If you run the program you'll discover that a light gray area often appears on the right and bottom edges of the frame when it's resized. Any ideas? Thanks. I'm using version 1.3.1._01 on Windows 98.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Grid extends JPanel implements ComponentListener
    private int rows, columns;
    private Block[][] block;
    public Grid()
    rows = 20;
    columns = 10;
    block = new Block[rows][columns];
    setLayout(new GridLayout(rows,columns,0,0));
    for (int i = 0; i < rows; i++)
    for (int j = 0; j < columns; j++)
    block[j] = new Block();
    if ((i % 4) >= 1)
    block[j].turnOn();
    else
    block[j].turnOff();
    add(block[j]);
    }//end inner for loop
    }//end outer for loop
    setBorder(BorderFactory.createLineBorder(Color.black,4));
    addComponentListener(this);
    }//end default constructor
    public Dimension getPreferredSize()
    int horizontalInsets = getInsets().left + getInsets().right;
    int verticalInsets = getInsets().top + getInsets().bottom;
    return new Dimension((block[0][0].getBlockWidth() * columns) + horizontalInsets,
    (block[0][0].getBlockHeight() * rows) + verticalInsets);
    }//end getPreferredSize
    public void componentHidden(ComponentEvent ce)
    //Invoked when the component has been made invisible.
    public void componentMoved(ComponentEvent ce)
    //Invoked when the component's position changes.
    public void componentResized(ComponentEvent ce)
    //Invoked when the component's size changes.
    int horizontalInsets = getInsets().left + getInsets().right;
    int verticalInsets = getInsets().top + getInsets().bottom;
    setPreferredSize(new Dimension(getWidth() + horizontalInsets,getHeight() + verticalInsets));
    setMinimumSize(new Dimension(getWidth() + horizontalInsets,getHeight() + verticalInsets));
    public void componentShown(ComponentEvent ce)
    //Invoked when the component has been made visible.
    public static void main(String[] args)
    JFrame frame = new JFrame();
    frame.getContentPane().add(new Grid(),BorderLayout.CENTER);
    frame.pack();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.show();
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Block extends JPanel implements ComponentListener
    private int blockWidth, blockHeight;
    private Color blockBackgroundColor, blockBorderColor, onColor;
    private String blockOwner;
    private boolean isOn;
    public Block()
    blockWidth = 20;
    blockHeight = 20;
    //setSize(20,20);
    //setPreferredSize(new Dimension(20,20));
    blockBackgroundColor = Color.gray;
    blockBorderColor = Color.black;
    setLayout(new BorderLayout(0,0));
    setBorder(BorderFactory.createLineBorder(blockBorderColor,1));
    setBackground(blockBackgroundColor);
    isOn = false;
    blockOwner = "1";
    onColor = Color.orange;
    addComponentListener(this);
    setVisible(true);
    }//end default constructor
    public Block(int blockWidth, int blockHeight)
    this();
    this.blockWidth = blockWidth;
    this.blockHeight = blockHeight;
    }//end two-arg constructor
    public void setBlockWidth(int blockWidth)
    this.blockWidth = blockWidth;
    public int getBlockWidth()
    return blockWidth;
    public void setBlockHeight(int blockHeight)
    this.blockHeight = blockHeight;
    public int getBlockHeight()
    return blockHeight;
    public void setBlockBorderColor(Color blockBorderColor)
    this.blockBorderColor = blockBorderColor;
    public Color getBlockBorderColor()
    return blockBorderColor;
    public void setBlockBackgroundColor(Color blockBackgroundColor)
    this.blockBackgroundColor = blockBackgroundColor;
    public Color getBlockBackgroundColor()
    return blockBackgroundColor;
    public void setOnColor(Color onColor)
    this.onColor = onColor;
    public Color getOnColor()
    return onColor;
    public void turnOn()
    setBackground(onColor);
    isOn = true;
    public void turnOff()
    setBackground(blockBackgroundColor);
    isOn = false;
    public void setBlockOwner(String blockOwner)
    this.blockOwner = blockOwner;
    public String getBlockOwner()
    return blockOwner;
    public Dimension getPreferredSize()
    int horizontalInsets = getInsets().left + getInsets().right;
    int verticalInsets = getInsets().top + getInsets().bottom;
    return new Dimension(blockWidth + horizontalInsets,
    blockHeight + verticalInsets);
    }//end getPreferredSize
    public void paintComponent(Graphics g)
    super.paintComponent(g);
    if (isOn)
    FontMetrics fm = g.getFontMetrics();
    int blockOwnerWidth = fm.stringWidth(blockOwner);
    int blockOwnerAscent = fm.getAscent();
    int x = (blockWidth / 2) - (blockOwnerWidth / 2);
    int y = (blockHeight / 2) + (blockOwnerAscent / 2);
    g.drawString(blockOwner,x,y);
    }//end paintComponent
    public void componentHidden(ComponentEvent ce)
    //Invoked when the component has been made invisible.
    public void componentMoved(ComponentEvent ce)
    //Invoked when the component's position changes.
    public void componentResized(ComponentEvent ce)
    //Invoked when the component's size changes.
    int horizontalInsets = getInsets().left + getInsets().right;
    int verticalInsets = getInsets().top + getInsets().bottom;
    blockWidth = this.getWidth();
    blockHeight = this.getHeight();
    setPreferredSize(new Dimension(blockWidth + horizontalInsets,blockHeight + verticalInsets));
    setMinimumSize(new Dimension(blockWidth + horizontalInsets,blockHeight + verticalInsets));
    public void componentShown(ComponentEvent ce)
    //Invoked when the component has been made visible.

    Your problem is due to the use of a GridLayout.
    With a GridLayout, all components must have the same dimension. And the extra space has to be divisible by the number of components to be distributed to each component :
    For example : In a component with a GridLayout, you have a line with 10 JPanels. The width of the component is initially 100. In this case, each JPanel will have a width of 10 (10*10=100).
    If you resize the main component to a width of 110, each JPanel will have a size of 11 (11*10=110).
    But in the case where the width is not divisible by the number of JPanels, there will be an extra-space :
    if the width of the component is 109, the width of each JPanel will be 10 and there will be an extra-space of 9 (10*10+9 = 109).
    I hope this helps,
    Denis

  • Jpanel, resize, borderlayout, browser, applet

    Sorry i cant find a good topic for my problem. :) I have an applet with a borderlayout, each time the browser is resize, my applet component is resize too , its ok, BUT i need to put a maximum size for my JPanel (in "Center"), is there a way to change the way that the automatic resize works? I explain why, i have a JPanel, the center one, that have a picture draw on it, when the view area of the JPanel is tiner than the size of the image, i put scrollbar, but i dont want to have the view area bigger than the picture..
    so is there a way
    sorry another time, when i have something long to explain in english, it could be not understandable :)
    thx a lot in advance

    try this, maybe works as you want,
    here component is you JPanel;
    Component component = new Component(){
    public Dimensin getMaximumSize()
    return new Dimension( 100, 100 ); // your picture size
    and as this you can overwrite
    getMinimumSize() and getPreferredSize() methods,
    Sorry i cant find a good topic for my problem. :) I
    have an applet with a borderlayout, each time the
    browser is resize, my applet component is resize too ,
    its ok, BUT i need to put a maximum size for my JPanel
    (in "Center"), is there a way to change the way that
    the automatic resize works? I explain why, i have a
    JPanel, the center one, that have a picture draw on
    it, when the view area of the JPanel is tiner than the
    size of the image, i put scrollbar, but i dont want to
    have the view area bigger than the picture..
    so is there a way
    sorry another time, when i have something long to
    explain in english, it could be not understandable :)
    thx a lot in advance

  • Nested JPanel resizing

    In one of my application there is one Jframe( BorderLayout) containing panel at the center surrounded with JScrollPane. The panel contains one more JPanel in it.
    On click of a button i need to resize both the panel.
    in the event handler method, Im caling setPreferedSize() and setSize() for both the panels.
    Only outer panel gets resized for the first click and for the second click inner panel gets resized...
    how can i solve this problem...?

    There is no way of knowing where the problem is without the code, however, you said you have called the setPreferedSize() and setSize() methods in the event handler.
    This should get called when you press the button, one thing you must do is to make sure that they are both inside the same block of code. If you are using an if statement.
    if(buttonPressed()){
    setPreferedSize();
    setSize();
    }Or you could post a simple version to help us solve the problem.

  • JSplitPane, JScrollPane, JPanel & resize

    My program has 2 nested JSplitpanes, that divide the screen in 4 parts like a cross.
    I added a JScrollPane to one of the quaters and added a JPanel to the JScrollPane. The JPanel uses a CardLayout since I want to switch the components that I show there.
    One of the components I show on the JPanel is a JTree. If I expand the tree the panel becomes scrollable to show the whole tree. This is what I want because I want to be able to view the whole tree.
    The problem is, that if I switch to another component on the panel the panel stays that large even though I just want it to have the visible size
    This is how the panel looks like before switching to the tree and expanding it:
    http://img272.imageshack.us/img272/8695/noscroll3zj.jpg
    This is how the panel looks like after switching to the tree, expanding it and switching back:
    http://img272.imageshack.us/img272/6690/scroll3ef.jpg
    I want to restore the panel to its initial state but I cannot figure out how. Please help.

    If I add a panel to the split pane (to make it card layout) I can't use it for scrolling anymoreThis simple example works for me:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class SplitPaneCard extends JFrame
         JSplitPane splitPane;
         JPanel cards;
         public SplitPaneCard()
              splitPane = new JSplitPane();
              getContentPane().add(splitPane, BorderLayout.CENTER);
              JTextArea textArea1 = new JTextArea(5, 10);
              textArea1.setText("1\n2\n3\n4\n5\n6\n7");
              textArea1.setForeground( Color.RED );
              JScrollPane scrollPane1 = new JScrollPane( textArea1 );
              JTextArea textArea2 = new JTextArea(5, 10);
              textArea2.setText("1234567");
              textArea2.setForeground( Color.BLUE );
              JScrollPane scrollPane2 = new JScrollPane( textArea2 );
            cards = new JPanel( new CardLayout() );
            cards.add(scrollPane1, "red");
            cards.add(scrollPane2, "blue");
            splitPane.setRightComponent( cards );
              JPanel buttonPanel = new JPanel();
              getContentPane().add(buttonPanel, BorderLayout.SOUTH);
              JButton red = new JButton("Show Red Text Area");
              red.addActionListener( new ActionListener()
                   public void actionPerformed(ActionEvent e)
                      CardLayout cl = (CardLayout)(cards.getLayout());
                      cl.show(cards, "red");
              buttonPanel.add(red);
              JButton blue = new JButton("Show Blue Text Area");
              blue.addActionListener( new ActionListener()
                   public void actionPerformed(ActionEvent e)
                      CardLayout cl = (CardLayout)(cards.getLayout());
                      cl.show(cards, "blue");
              buttonPanel.add(blue);
         public static void main(String[] args)
              final SplitPaneCard frame = new SplitPaneCard();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setLocationRelativeTo( null );
              frame.setVisible(true);
    }

  • Auto-resizing JPanel  on mouseEntered

    Hello,
    I am looking for a little advice. I want to try and make a JPanel resize on mouseEntered. I want the JPanel to be be almost hidden until the mouse is over and I want it to grow in size gradually rather than appear instantly. The Panel will share space with a JEditorpane which will occupy the majority of the space but resize to allow to the JPanel to grow in size.
    --Hidden
    ///////////////////////////////////////////////////////////////////////////////////// - Base panel
    ////////////////////////////////////////////////////////////////////////////////////// - JPanel almost hidden
    /                               JEditorPane                                             /
    ////////////////////////////////////////////////////////////////////////////////////// - Base panel
    --On Mouse Over
    /////////////////////////////////////////////////////////////////////////////////////// - Base panel
    /                          JPanel now showing                                 /
    /                         JEditorPane                                                  /
    //////////////////////////////////////////////////////////////////////////////////////// - Base panelThe JPanel will start of with a height of say 5 and when the mousentered event is fired it will grow over the space of half a second or so to a height of about 80. When the Mouse exists I want to to go back to it's original position.
    I have seen this technique used on some desktop applications I have used in the past and I would like some advice on how best to accomplish this in Swing.
    Has anyone done this before, or if not which way might it be possible?
    I am not expecting code, just some ideas on an approach. I am not really that good when it comes to Swing.
    BTW, I have tried already with a JPanel as the base panel and a JLayeredPane but the JPanel I wish to resize ignore the calls to setSize, possible becuase it has various components embedded on to it.
    Cheers.

    BTW, I have tried already with a JPanel as the base panel and a JLayeredPane but the JPanel I wish to resize ignore the calls to setSize, possible becuase it has various components embedded on to it. When using JLayeredPane, the trick would be to use setBounds( ) instead.
    Basically to achieve this you would need a simple javax.swing.Timer and the necessary MouseListeners. Consider creating a subclass of JPanel where you will attach the listener code. Once, the mouseEnters, you'll probably need to set a boolean which indicates that the panel should grow, and fire the Timer. The Timer's actionPerformed method should check the boolean to determine whether to grow the panel or shrink it. The changes to the panel should be done through setPreferredSize( ).
    Consider removing all the items in the Panel before shrinking and re-adding them only when the Panel is fully grown. This may help improve performance.
    This feature may cause your application to suffer a bit in terms of appearance when the panel growing or shrinking unless a suitable LayoutManager is choosen. Cant suggest any unless I try it my self.
    ICE

  • JPanel inside a JFrame

    How do you make a JPanel resize automatically with its parent JFrame?
    Thanks,
    -Zom.

    Use BorderLayout for the JFrame and set the JPanel at centre like this:myJFrame.getContentPane().setLayout(new BorderLayout());
    myJFrame.getContentPane().add(myPanel,  JFrame.CENTER);

  • Canvas3D resize issue in JSplitPane

    Hi,
    I have a JSplitPane which has been split vertically. Now, this JSplitPane has 2 JSplitPanes on the left and right half. The left JSplitPane has 2 Canvas3Ds and the right JSplitPane has a bottom Canvas3D and a top Chart (extends JPanel).
    All the Canvas3Ds are attached to JPanels which in turn are attached to the JSplitPanes and not directly. Whenever, i render the Canvas3Ds, the right bottom Canvas3D attached to the Chart JPanel resizes and expands vertically (even though the Divider positions for the SplitPanes are set to 0.5).
    This is happening for JDK 1.4 version and above. Previously, i was using JDK 1.2.2 and this was not happening. The Java3D version used is 1.3.1.
    Is there any way to stop the right bottom Canvas3D from resizing beyond the divider position.
    Thanks,
    Raghav

    I suppose you put the Canvas3D into the CENTER location of the BorderLayout panel... that's why the canvas resizes at the same time as the panel does. Try replacing BorderLayout with FlowLayout, that should work.
    When I said "null layout", I meant a panel WITHOUT layout manager: you create it with new JPanel(null)... this way lets you locate and size the children as you wish. But of course, if you want some 'layout-like' functionnalities (I mean, if you want the children to change location/size depending on the panel), you have to write them by your own.
    Hope this helped,
    Regards.

  • JFRAME background jpeg image

    Hi,
    I am trying to add a jpeg as a packground to my JFrame. I have read quite a few posts on how to do it in here, but none seem to work . Has anybody tried this and goit it working? If so some tips would be good.
    Thanks

    With some changes, the JPanel resize to the image size:
    import javax.swing.*;
    import java.awt.*;
    import java.net.URL;
    / A <code>JFrame</code> with a background image */
    public class BackgroundImage extends JFrame
         final ImageIcon icon;
         final boolean isRedimensionable;
         public BackgroundImage(URL url, boolean isRedimensionable) {
              icon = new ImageIcon(url.getFile());
              this.isRedimensionable = isRedimensionable;
              JPanel panel = new JPanel()
                   protected void paintComponent(Graphics g)
                        if (BackgroundImage.this.isRedimensionable) {
                             //  Scale image to size of component
                             Dimension d = getSize();
                             g.drawImage(icon.getImage(), 0, 0, d.width, d.height, null);
                        } else  {
                             //  Dispaly image at at full size
                             g.drawImage(icon.getImage(), 0, 0, null);
                        super.paintComponent(g);
              panel.setOpaque( false );
              getContentPane().add( panel );
              Dimension dim = new Dimension(icon.getIconWidth()  +getInsets().left+  getInsets().right, icon.getIconHeight()  +getInsets().top+  getInsets().bottom) ;
              panel.setPreferredSize(dim);
              setResizable(isRedimensionable);
              pack();
              JButton button = new JButton( "Hello" );
              panel.add( button );
         public static void main(String [] args)
              BackgroundImage frame = new BackgroundImage(BackgroundImage.class.getResource("loginDialogBackground.png"), true);
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setLocationRelativeTo( null );
              frame.setVisible(true);
    }

  • Creating an own textviewer-component - How to start?

    Hello,
    I'm going to write a program for comparing two texts for speed typing. For this I need a component which shows the text, shows for each line the character count and can highlight words (to show the mistakes).
    E. g.:
    Lorem ipsum dolor sit amet, consectetuer sadipscing elitr,   |  59
    sed diam nonumy eirmod tempor invidunt ut labore et dolore   | 118
    magna aliquyam erat, sed diam voluptua. At vero eos et       | 174How can I start?
    Taking a JPanel and self-draw everything in paint()-method?
    Using for every word a own JLabel?
    Customizing a JTextArea?
    Any ideas? :-)
    Edited by: franz_s on 15.05.2009 10:53

    Yes, that is the best approach. A text area provides everything your need:
    Using a JTable is probably not a valid approach.Well, I am unsure of the OP's requirements, but his description suggests that characters (and maybe errors) are counted by line, thus leading to a rendering where one row in the GUI displays several information (columns) on one entity (which is "a line of text") - remember RowBasedTableModel?
    Furthermore, quoting the OP (highlighing is mine): "I need a component which +shows+ the text, +shows for each line the character count+ and can highlight words (to show the mistakes)"
    I interpreted it as if he enters text in some component (for which TextArea makes most sense), but the program then performs some analysis on the whole text, and only displays the result, line by line, in some other component.
    It is not designed for entering multilined text.If the OP needs to both enter the text and display the result of the analysis in the same component (e.g. for real time analysis), JTable is certainly a wrong choice. I just did not read his post that way.
    Highliting of errors will be difficult.During edition, yes, but at rendering time, no more than using a TextArea.

  • ScrollPane problems

    i have a scrollPane in a frame, and the scrollPane contains JPanels. The first JPanel appears and no scrollbar appears due to the JPanel fitting within the frame size..that's fine. Then upon a JButton click, a second JPanel appears in the first JPanel's place, this time the scrollbar appears because the JPanel size is larger then the frame size.
    The problem is that upon JButton click back to the original JPanel the scrollbar stays and the first JPanel resizes to the size of second JPanel? Behaviour should be for the scrollbar to disappear and the original JPanel to use it's original size??
    Anyone any ideas?

    You can try to work with the following methods:
    setMaximumSize(Dimension d)
    setPreferredSize(Dimension d)
    setMinimumSize(Dimension d)
    Perhaps it works when you set the first panels maximumsize.
    Djamal

  • Dealing with AffineTransform mouse driven rotation

    Hi there,
    I'm implementing the mouse control to navigate through an image representing a map. Pan and zoom where trivial operations, but I'm getting in trouble when trying to rotate the BufferedImage.
    I actually can perform the rotation, but because the map coordinate system gets rotated too. I have applied a trigonometric correction when performing a pan after a rotation. This was the hard part... my problem is that I have inverted the axis when panning, so dragging the mouse to the bottom of the canvas becomes a horizontal translation if we had a rotation by PI rads.
    Because original Java code is pretty big, I have coded a simple example that pans, zooms or rotates a square.
    The magic happens here:
    def performPan(self,diff):
            xa = diff.x*lang.Math.cos(self.theta)+diff.y*lang.Math.sin(self.theta)
            ya = -diff.x*lang.Math.sin(self.theta)+diff.y*lang.Math.cos(self.theta)
            diff.x -= (diff.x - xa)
            diff.y -= (diff.y - ya)
            center = self.canvas.squareCenter()
            # if self.theta != 0: self.transform.rotate(-self.theta, center.x, center.y)       
            self.transform.translate(diff.x, diff.y)
            #if self.theta != 0: self.transform.rotate(self.theta, center.x, center.y)
        def performZoom(self,diff):     
              zoomLevel = 1.0+0.01*diff.y;
              if zoomLevel <= 0:
                  zoomLevel = 0
              center = self.canvas.windowCenter()          
              self.transform.scale(zoomLevel, zoomLevel)
        def performRotation(self,diff):
             angleStep = diff.y * 0.1
             self.theta += diff.y
             self.theta %= 2*lang.Math.PI
             center = self.canvas.squareCenter()
             self.transform.rotate(angleStep, center.x, center.y)
        def toWindowCoordinates(self,diff):
            try:
                self.transform.inverseTransform(diff,diff)
            except:
                print "error en window coordinates"I have already tried changing diff.x and diff.x sign, and commenting that trigonometric correction and uncommeting the lines concatenating two rotations surrounding the translation without sucess.
    Please, I'd appreciate some feedback. Brainstorms are welcome. :-)
    Thanks, Vicente.
    The full code:
    from javax import swing
    from java import awt, lang;
    class Listener(swing.event.MouseInputAdapter):
        def __init__(self,subject):
            self.offset = awt.geom.Point2D.Double()
            self.anchor = awt.geom.Point2D.Double()
            self.canvas = subject
            self.transform = subject.transform
            self.rectangle = subject.rectangle
            self.theta = 0.0
        def mousePressed(self,e):
            self.anchor.x = e.getX()
            self.anchor.y = e.getY()
            self.offset.x = e.getX()
            self.offset.y = e.getY()
        def mouseDragged(self,e):
            self.offset.x = e.getX()
            self.offset.y = e.getY()
            diff = awt.geom.Point2D.Double()   
            tx = self.offset.x - self.anchor.x
            ty = self.offset.y - self.anchor.y
            diff.x = tx
            diff.y = ty      
            self.anchor.x = self.offset.x
            self.anchor.y = self.offset.y
            class Painter(lang.Runnable):
                def __init__(self,canvas, listener):
                    self.canvas = canvas
                    self.listener = listener
                def run(self):
                    if e.isControlDown():
                        self.listener.performRotation(diff)
                    elif swing.SwingUtilities.isLeftMouseButton(e):       
                        self.listener.performPan(diff)       
                    if swing.SwingUtilities.isRightMouseButton(e):
                        self.listener.performZoom(diff)
                    self.canvas.repaint()
            work = Painter(self.canvas, self)
            swing.SwingUtilities.invokeLater(work)
        def mouseReleased(self,e):
            self.color = awt.Color.red
            self.canvas.repaint()
        def performPan(self,diff):
            xa = diff.x*lang.Math.cos(self.theta)+diff.y*lang.Math.sin(self.theta)
            ya = -diff.x*lang.Math.sin(self.theta)+diff.y*lang.Math.cos(self.theta)
            diff.x -= (diff.x - xa)
            diff.y -= (diff.y - ya)
            center = self.canvas.squareCenter()
            if self.theta != 0: self.transform.rotate(-self.theta, center.x, center.y)       
            self.transform.translate(diff.x, diff.y)
            if self.theta != 0: self.transform.rotate(self.theta, center.x, center.y)
        def performZoom(self,diff):     
              zoomLevel = 1.0+0.01*diff.y;
              if zoomLevel <= 0:
                  zoomLevel = 0
              center = self.canvas.windowCenter()          
              self.transform.scale(zoomLevel, zoomLevel)
        def performRotation(self,diff):
             angleStep = diff.y * 0.1
             self.theta += diff.y
             self.theta %= 2*lang.Math.PI
             center = self.canvas.squareCenter()
             self.transform.rotate(angleStep, center.x, center.y)
        def toWindowCoordinates(self,diff):
            try:
                self.transform.inverseTransform(diff,diff)
            except:
                print "error en window coordinates"
    class Canvas(swing.JPanel):
        def __init__(self):
            self.rectangle = awt.geom.Rectangle2D.Double(0,0,50,50)
            self.transform = awt.geom.AffineTransform()   
            self.wcenter = awt.geom.Point2D.Double()
            self.rcenter = awt.geom.Point2D.Double()
            listener = Listener(self)
            swing.JPanel.addMouseMotionListener(self,listener)
            swing.JPanel.addMouseListener(self,listener)
        def paintComponent(self,g2d):
            self.super__paintComponent(g2d)
            g2d.setTransform(self.transform)
            g2d.fill(self.rectangle)
        def windowCenter(self):
            if self.wcenter.x == 0 or self.wcenter.y == 0:
                self.wcenter.x = self.getHeight()/2.0
                self.wcenter.y = self.getWidth()/2.0     
            return self.wcenter
        def squareCenter(self):
            if self.rcenter.x == 0 or self.rcenter.y == 0:
                self.rcenter.x = self.rectangle.getBounds2D().height/2.0
                self.rcenter.y = self.rectangle.getBounds2D().width/2.0       
            return self.rcenter
    frame = swing.JFrame(   title="test",
                            visible=1,
                            defaultCloseOperation = swing.JFrame.EXIT_ON_CLOSE,
                           preferredSize = awt.Dimension(400,400),
                            maximumSize = awt.Dimension(800,600),
                            minimumSize = awt.Dimension(200,200),
                            size = awt.Dimension(500,500)
    frame.add(Canvas(), awt.BorderLayout.CENTER)
    frame.pack()

    I forgot to mention that the example is written in
    Jython, because the Java was pretty big, but it is
    legible bu a Java programmer. :-)It's legible, but most of us w/out a jython compiler would have to re-write the code if we wanted to try it out. That may hurt your chances of getting a useful response (as opposed to my useless responses). ... Or it might not.
    Good luck!
    /Pete

  • Gtkpacman-svn - search fails to function

    When I click the search icon and enter any word into the input dialog, nothing happens. The terminal spews out this:
    Traceback (most recent call last):
    File "/usr/lib/python2.5/site-packages/gtkPacman/gui.py", line 506, in search
    pacs = self.database.get_by_keywords(keywords)
    File "/usr/lib/python2.5/site-packages/gtkPacman/pacman.py", line 436, in get_by_keywords
    pacs.extend(self.get_by_desc(keys))
    File "/usr/lib/python2.5/site-packages/gtkPacman/pacman.py", line 400, in get_by_desc
    self.set_pac_properties(pac)
    File "/usr/lib/python2.5/site-packages/gtkPacman/pacman.py", line 205, in set_pac_properties
    self._set_summary(pac, path)
    File "/usr/lib/python2.5/site-packages/gtkPacman/pacman.py", line 215, in _set_summary
    size = self._get_size(desc_file)
    File "/usr/lib/python2.5/site-packages/gtkPacman/pacman.py", line 241, in _get_size
    end = desc.index("%", begin)
    ValueError: substring not found
    Any idea what's wrong?
    - Dave

    Hello
    I made another patch. This one is more like enhancement than a patch, oh well see it for yourself.
    Changed / fixed:
    * No more is IgnorePkg or HoldPkg ignored, when clicked on a package that is listed as ignorePkg or holdPkg window  will pop up and ask if user want to add this package to install/remove queue, same thins happens when upgrading whole system
    * Changed main window size
    * Repository list is unfolded by default
    * Removed "search" item from pop up menu, when you clicked on package, this was useless and didn't working
    * Some small fixes
    diff -uNr gtkpacman/data/gtkpacman.glade gtkpacman-2.0/data/gtkpacman.glade
    --- gtkpacman/data/gtkpacman.glade 2007-11-27 13:22:39.182008729 +0100
    +++ gtkpacman-2.0/data/gtkpacman.glade 2006-12-30 18:55:26.000000000 +0100
    @@ -10,7 +10,7 @@
    <property name="window_position">GTK_WIN_POS_NONE</property>
    <property name="modal">False</property>
    <property name="default_width">650</property>
    - <property name="default_height">500</property>
    + <property name="default_height">433</property>
    <property name="resizable">True</property>
    <property name="destroy_with_parent">False</property>
    <property name="decorated">True</property>
    @@ -891,6 +891,34 @@
    </child>
    </widget>
    </child>
    +
    + <child>
    + <widget class="GtkSeparatorMenuItem" id="separator6">
    + <property name="visible">True</property>
    + </widget>
    + </child>
    +
    + <child>
    + <widget class="GtkImageMenuItem" id="search">
    + <property name="visible">True</property>
    + <property name="label" translatable="yes">_Search</property>
    + <property name="use_underline">True</property>
    + <signal name="activate" handler="search" last_modification_time="Tue, 18 Apr 2006 11:01:36 GMT"/>
    + <accelerator key="S" modifiers="GDK_CONTROL_MASK" signal="activate"/>
    +
    + <child internal-child="image">
    + <widget class="GtkImage" id="image71">
    + <property name="visible">True</property>
    + <property name="stock">gtk-find</property>
    + <property name="icon_size">1</property>
    + <property name="xalign">0.5</property>
    + <property name="yalign">0.5</property>
    + <property name="xpad">0</property>
    + <property name="ypad">0</property>
    + </widget>
    + </child>
    + </widget>
    + </child>
    </widget>
    </glade-interface>
    diff -uNr gtkpacman/gtkPacman/dialogs.py gtkpacman-2.0/gtkPacman/dialogs.py
    --- gtkpacman/gtkPacman/dialogs.py 2007-11-30 15:54:30.883609016 +0100
    +++ gtkpacman-2.0/gtkPacman/dialogs.py 2007-01-02 00:15:51.000000000 +0100
    @@ -26,8 +26,8 @@
    from gtk import STOCK_CLOSE, STOCK_OK, STOCK_CANCEL, STOCK_GO_FORWARD
    from gtk import STOCK_APPLY, STOCK_REMOVE, STOCK_YES, STOCK_NO, STOCK_OPEN
    from gtk import DIALOG_MODAL, DIALOG_DESTROY_WITH_PARENT
    -from gtk import MESSAGE_WARNING, FILE_CHOOSER_ACTION_OPEN, MESSAGE_INFO
    -from gtk import BUTTONS_CLOSE, MESSAGE_ERROR, BUTTONS_YES_NO
    +from gtk import MESSAGE_WARNING, FILE_CHOOSER_ACTION_OPEN
    +from gtk import BUTTONS_CLOSE, MESSAGE_ERROR
    from gtk import RESPONSE_ACCEPT, RESPONSE_REJECT, RESPONSE_YES, RESPONSE_CLOSE
    from gtk import image_new_from_stock, ICON_SIZE_BUTTON, ICON_SIZE_DIALOG
    from gtk import main_iteration, expander_new_with_mnemonic
    @@ -236,17 +236,14 @@
    class do_dialog(Window):
    def __init__(self, queues, icon):
    - self.size = ()
    Window.__init__(self, WINDOW_TOPLEVEL)
    self.set_property("skip-taskbar-hint", True)
    self.set_property("destroy-with-parent", True)
    - #self.set_property("resizable", False)
    self.set_modal(True)
    self.connect("delete-event", self._stop_closing)
    self.set_position(WIN_POS_CENTER)
    +
    self.set_icon(pixbuf_new_from_file(icon))
    self._setup_trees(queues)
    self._setup_layout()
    @@ -329,11 +326,8 @@
    self.terminal.connect("child-exited", lambda _: self.close_button.show())
    self.expander = Expander(_("Terminal"))
    - self.expander.connect("notify::expanded", self.expanderCb)
    - #self.expander.add(self.terminal)
    - #self.expander.show_all()
    - self.expander.show()
    + self.expander.add(self.terminal)
    + self.expander.show_all()
    self.vbox = VBox(False, 0)
    self.vbox.show()
    @@ -353,17 +347,7 @@
    def _stop_closing(self, widget, event):
    self.stop_emission("delete-event")
    - return True
    - def expanderCb(self, widget, event, data=None):
    - if self.expander.get_expanded():
    - self.size = self.get_size()
    - self.expander.add(self.terminal)
    - self.terminal.show()
    - else:
    - self.expander.remove(self.terminal)
    - self.resize(self.size[0], self.size[1])
    - self.show_all()
    + return True
    class local_install_fchooser_dialog(FileChooserDialog):
    @@ -446,19 +430,14 @@
    self.set_property("skip-taskbar-hint", True)
    self.set_property("modal", True)
    self.set_property("destroy-with-parent", True)
    - #self.set_property("resizable", False)
    self.set_position(WIN_POS_CENTER)
    self.set_default_size (300, 300)
    - self.unrealize()
    - #self.set_resizable(True)
    self.set_icon(pixbuf_new_from_file(icon))
    self._setup_tree(to_upgrade)
    self._setup_layout()
    def _setup_layout(self):
    - self.size = ()
    self.vbox = VBox(False, 0)
    self.vbox.show()
    @@ -466,12 +445,9 @@
    self.terminal.connect("child-exited", lambda _: self.close_button.show())
    self.expander = expander_new_with_mnemonic(_("_Terminal"))
    - self.expander.connect("notify::expanded", self.expanderCb)
    self.expander.set_expanded(False)
    - #self.expander.add(self.terminal)
    - #self.expander.show_all()
    - self.expander.show()
    + self.expander.add(self.terminal)
    + self.expander.show_all()
    self.close_button = Button(stock=STOCK_CLOSE)
    self.close_button.connect("clicked", lambda _: self.destroy())
    @@ -492,16 +468,6 @@
    self.add(self.vbox)
    return
    - def expanderCb(self, widget, event, data=None):
    - if self.expander.get_expanded():
    - self.size = self.get_size()
    - self.expander.add(self.terminal)
    - self.terminal.show()
    - else:
    - self.expander.remove(self.terminal)
    - self.resize(self.size[0], self.size[1])
    - self.show_all()
    def _setup_tree(self, pacs):
    self.model = ListStore(str, str, str)
    @@ -624,16 +590,3 @@
    DIALOG_MODAL | DIALOG_DESTROY_WITH_PARENT,
    MESSAGE_ERROR, BUTTONS_CLOSE, msg)
    self.set_icon(pixbuf_new_from_file(icon))
    -class infoMessage(MessageDialog):
    - def __init__(self, type=None, buttons=None, msg=None):
    - MessageDialog.__init__(self
    - , None
    - , DIALOG_MODAL | DIALOG_DESTROY_WITH_PARENT
    - , type
    - , buttons
    - , message_format=msg)
    - self.set_position(WIN_POS_CENTER)
    \ No newline at end of file
    Binary files gtkpacman/gtkPacman/dialogs.pyc and gtkpacman-2.0/gtkPacman/dialogs.pyc differ
    diff -uNr gtkpacman/gtkPacman/gui.py gtkpacman-2.0/gtkPacman/gui.py
    --- gtkpacman/gtkPacman/gui.py 2007-12-01 05:30:42.171459702 +0100
    +++ gtkpacman-2.0/gtkPacman/gui.py 2007-01-02 00:16:03.000000000 +0100
    @@ -21,8 +21,7 @@
    from gtk import main, main_quit, TreeStore, TreeView, ListStore, Button
    from gtk import CellRendererText, CellRendererPixbuf, ScrolledWindow
    from gtk import STOCK_ADD, STOCK_GO_UP, STOCK_REMOVE, STOCK_CLOSE
    -from gtk import RESPONSE_YES, RESPONSE_ACCEPT, MESSAGE_INFO, BUTTONS_CLOSE
    -from gtk import MESSAGE_WARNING, BUTTONS_YES_NO
    +from gtk import RESPONSE_YES, RESPONSE_ACCEPT
    from gtk.gdk import pixbuf_new_from_file
    from gtk.glade import XML
    @@ -30,7 +29,7 @@
    from dialogs import confirm_dialog, search_dialog, upgrade_dialog
    from dialogs import upgrade_confirm_dialog, local_install_dialog
    from dialogs import local_install_fchooser_dialog, local_confirm_dialog
    -from dialogs import command_dialog, error_dialog, infoMessage
    +from dialogs import command_dialog, error_dialog
    from models import installed_list, all_list, whole_list, search_list, file_list
    @@ -91,7 +90,7 @@
    self.gld.get_widget("immediate").set_sensitive(False)
    self.gld.get_widget("add_install").set_sensitive(False)
    self.gld.get_widget("remove_install").set_sensitive(False)
    - self.gld.get_widget("add_remove").set_sensitive(False)
    + self.gld.get_widget("add_remove").set_sensitive(False)
    self.gld.get_widget("remove_remove").set_sensitive(False)
    self.gld.get_widget("execute").set_sensitive(False)
    self.gld.get_widget("up_sys").set_sensitive(False)
    @@ -101,7 +100,6 @@
    self.popup_gld.get_widget("popup_remove_install").set_sensitive(False)
    self.popup_gld.get_widget("popup_add_remove").set_sensitive(False)
    self.popup_gld.get_widget("popup_remove_remove").set_sensitive(False)
    - pass
    def _adjust_queues (self):
    for name in self.queues["add"]:
    @@ -185,7 +183,6 @@
    repos_tree.insert_column_with_attributes(-1, "", CellRendererText(),
    text=0)
    repos_tree.set_model(repos_model)
    - repos_tree.expand_row(0, False)
    return
    def _setup_files_tree(self):
    @@ -232,7 +229,8 @@
    except AttributeError:
    pass
    continue
    - return
    + return
    +
    def _refresh_model(self, model, submodel=None):
    if submodel:
    liststore = self.models[model][submodel]
    @@ -248,7 +246,7 @@
    row[0] = "red"
    row[3] = "-"
    continue
    - return
    + return
    def quit(self, widget, data=None):
    main_quit()
    @@ -271,10 +269,9 @@
    -1, "", CellRendererText(), text=5
    if not self.inst_ver_col:
    - #self.inst_ver_col = pacs_tree.insert_column_with_atrributes(
    - # -1, "", CellRendererText(), text=4
    - pass
    + self.inst_ver_col = pacs_tree.insert_column_with_atrributes(
    + -1, "", CellRendererText(), text=4
    + )
    elif selected == _("foreigners"):
    if self.repo_col:
    @@ -326,27 +323,10 @@
    def add_to_install_queue(self, widget, data=None):
    tree = self.gld.get_widget("pacs_tree")
    model, l_iter = tree.get_selection().get_selected()
    - if not l_iter:
    - return
    +
    name = model.get_value(l_iter, 2)
    if name in self.queues["add"]:
    return
    - if name in self.database.options['IgnorePkg']:
    - dlg = infoMessage(type=MESSAGE_WARNING
    - , buttons= BUTTONS_YES_NO
    - , msg='\"%s\" is in IgnorePkg list.\nAdd it to install queue anyway?' % name)
    - dlg.set_title("Warning...")
    - if dlg.run() == RESPONSE_YES:
    - pass
    - else:
    - dlg.destroy()
    - return
    - dlg.destroy()
    if name in self.queues["remove"]:
    self.queues["remove"].remove(name)
    @@ -362,9 +342,6 @@
    def remove_from_install_queue(self, widget, data=None):
    tree = self.gld.get_widget("pacs_tree")
    model, l_iter = tree.get_selection().get_selected()
    - if not l_iter:
    - return
    name = model.get_value(l_iter, 2)
    if not (name in self.queues["add"]):
    @@ -377,25 +354,8 @@
    def add_to_remove_queue(self, widget, data=None):
    tree = self.gld.get_widget("pacs_tree")
    model, l_iter = tree.get_selection().get_selected()
    - if not l_iter:
    - return
    name = model.get_value(l_iter, 2)
    - if name in self.database.options['HoldPkg']:
    - dlg = infoMessage(type=MESSAGE_WARNING
    - , buttons= BUTTONS_YES_NO
    - , msg='\"%s\" is designated as HoldPkg.\nAdd it to remove queue anyway?' % name)
    - dlg.set_title("Warning...")
    - if dlg.run() == RESPONSE_YES:
    - pass
    - else:
    - dlg.destroy()
    - return
    - dlg.destroy()
    if name in self.queues["remove"]:
    return
    @@ -414,12 +374,8 @@
    def remove_from_remove_queue(self, widget, data=None):
    tree = self.gld.get_widget("pacs_tree")
    model, l_iter = tree.get_selection().get_selected()
    - if not l_iter:
    - return
    name = model.get_value(l_iter, 2)
    if not (name in self.queues["remove"]):
    return
    @@ -428,19 +384,8 @@
    return
    def execute(self, widget, data=None):
    - check = True
    pacs_queues = { "add": [], "remove": [] }
    - if not (self.queues["add"] or self.queues["remove"]):
    - dlg = infoMessage(type=MESSAGE_INFO
    - , buttons= BUTTONS_CLOSE
    - , msg='Nothing to do.\nAdd package to queue list first.')
    - dlg.set_title("Info...")
    - dlg.run()
    - dlg.destroy()
    - #self._refresh_trees_and_queues()
    - return
    for name in self.queues["add"]:
    try:
    pac = self.database.get_by_name(name)
    @@ -454,11 +399,12 @@
    self.database.set_pac_properties(pac)
    pacs_queues["add"].append(pac)
    - if pac.dependencies:
    - deps = pac.dependencies.split(", ")
    - for dep in deps:
    - if dep.count(">="):
    - dep = dep.split(">=")[0]
    +
    + deps = pac.dependencies.split(", ")
    + for dep in deps:
    + if dep.count(">="):
    + dep = dep.split(">=")[0]
    +
    try:
    dep_pac = self.database.get_by_name(dep)
    except NameError:
    @@ -466,22 +412,20 @@
    _("%(dep)s is not in the database. %(dep)s is required by %(pkg)s.\nThis maybe either an error in %(pkg)s packaging or a gtkpacman's bug.\nIf you think it's the first, contact the %(pkg)s maintainer, else fill a bug report for gtkpacman, please.") %{'dep': dep, "pkg": name}, self.icon)
    dlg.run()
    dlg.destroy()
    pacs_queues["add"].remove(pac)
    self.queues["add"].remove(name)
    break
    if not dep_pac.installed:
    pacs_queues["add"].append(dep_pac)
    - continue
    + continue
    for name in self.queues["remove"]:
    pac = self.database.get_by_name(name)
    if not pac.prop_setted:
    - self.database.set_pac_properties(pac)
    + self.database.set_pac_properties(pac)
    +
    pacs_queues["remove"].append(pac)
    - if pac.req_by: #********************************************
    - retcode = False
    + if pac.req_by:
    req_pacs = []
    for req in pac.req_by.split(", "):
    if not (req in self.queues["remove"]):
    @@ -496,13 +440,14 @@
    else:
    self.queues["remove"].remove(name)
    pacs_queues["remove"].remove(pac)
    - check = False
    dlg.destroy()
    - continue #**********************************************
    - if check:
    - retcode = self._confirm(pacs_queues)
    + continue
    +
    + if not (pacs_queues["add"] or pacs_queues["remove"]):
    + self._refresh_trees_and_queues()
    + return
    +
    + retcode = self._confirm(pacs_queues)
    if retcode:
    stat_bar = self.gld.get_widget("statusbar")
    stat_bar.pop(self.stat_id)
    @@ -526,20 +471,18 @@
    self._refresh_trees()
    self.queues["add"] = []
    self.queues["remove"] = []
    - if pacs_queues:
    - for pac in pacs_queues["add"]:
    - pac.installed = True
    - self.database.set_pac_properties(pac)
    - continue
    - for pac in pacs_queues["remove"]:
    - pac.installed = False
    - self.database.set_pac_properties(pac)
    - continue
    - else:
    - del(pacs_queues)
    - stat_bar = self.gld.get_widget("statusbar")
    - stat_bar.pop(self.stat_id)
    - stat_bar.push(self.stat_id, _("Done."))
    + for pac in pacs_queues["add"]:
    + pac.installed = True
    + self.database.set_pac_properties(pac)
    + continue
    + for pac in pacs_queues["remove"]:
    + pac.installed = False
    + self.database.set_pac_properties(pac)
    + continue
    + del(pacs_queues)
    + stat_bar = self.gld.get_widget("statusbar")
    + stat_bar.pop(self.stat_id)
    + stat_bar.push(self.stat_id, _("Done."))
    return
    def about(self, widget, data=None):
    @@ -555,16 +498,12 @@
    self.popup.popdown()
    def search(self, widget, data=None):
    - keywords=""
    dlg = search_dialog(self.gld.get_widget("main_win"), self.icon)
    if dlg.run() == RESPONSE_ACCEPT:
    keywords = dlg.entry.get_text()
    dlg.destroy()
    - if keywords:
    - pacs = self.database.get_by_keywords(keywords)
    - else:
    - return
    + pacs = self.database.get_by_keywords(keywords)
    repos_model = self.gld.get_widget("repos_tree").get_model()
    if self.search_iter:
    @@ -654,43 +593,15 @@
    def upgrade_system(self, widget, data=None):
    to_upgrade = []
    - blacklist ={}
    - options = self.database.options
    for repo in self.database.values():
    for pac in repo:
    if pac.isold:
    - to_upgrade.append(pac)
    + to_upgrade.append(pac)
    continue
    continue
    if to_upgrade:
    - counter = 0
    - for pack in to_upgrade:
    - counter += 1
    - if pack.name in options['IgnorePkg']:
    - blacklist[pack.name] = counter -1
    - if blacklist:
    - dlg = infoMessage(type=MESSAGE_WARNING
    - , buttons= BUTTONS_YES_NO
    - , msg='Found package(\'s) that are in IgnorePkg list.\nClick Yes to include them in to upgrade list\nClick NO to dele them from upgrade list.')
    - dlg.set_title("Warning...")
    - print '***Packages that are in IgnorePkg list***\n ', blacklist.keys()
    - if dlg.run() == RESPONSE_YES:
    - pass
    - else:
    - index = blacklist.values()
    - index.sort()
    - while index:
    - to_del = index.pop()
    - del to_upgrade[to_del]
    - dlg.destroy()
    - if to_upgrade:
    confirm = self._upgrade_confirm(to_upgrade)
    if confirm:
    Binary files gtkpacman/gtkPacman/gui.pyc and gtkpacman-2.0/gtkPacman/gui.pyc differ
    diff -uNr gtkpacman/gtkPacman/pacman.py gtkpacman-2.0/gtkPacman/pacman.py
    --- gtkpacman/gtkPacman/pacman.py 2007-11-20 15:34:00.154003528 +0100
    +++ gtkpacman-2.0/gtkPacman/pacman.py 2007-01-02 00:16:31.000000000 +0100
    @@ -76,7 +76,7 @@
    def __init__(self):
    """Init database"""
    #Get repos present on machine
    - self.repos, self.options = self._get_repos()
    + self.repos = self._get_repos()
    self.set_pacs()
    self.repos.sort()
    @@ -91,12 +91,11 @@
    conf_file_lines = conf_file.splitlines()
    repos = []
    - options = {} #********************************************************
    for line in conf_file_lines:
    if line.startswith("#"):
    continue
    - elif line.startswith("["):
    + if line.startswith("["):
    begin = line.index("[") + len("[")
    end = line.index("]")
    repo = line[begin:end]
    @@ -104,15 +103,8 @@
    continue
    else:
    repos.append(repo)
    - #continue
    - elif line.startswith("HoldPkg") or line.startswith("IgnorePkg"):
    - option = line.rstrip()
    - split = option.split()
    - del split[1]
    - options[split[0]] = split[1:]
    continue
    - return repos, options
    + return repos
    def _get_installed(self):
    installed = os.listdir("/var/lib/pacman/local")
    @@ -201,24 +193,11 @@
    def set_pac_properties(self, pac):
    """Set the properties for the given pac"""
    - from os.path import exists
    - if pac.installed: # Jump in if package is installed
    - path_old = '/var/lib/pacman/local/%s-%s'%(pac.name,pac.version)
    - if pac.isold and exists(path_old):
    - version = pac.version # After Upgrading, package use this
    - repo = 'local'
    - elif pac.isold:
    - version = pac.inst_ver # Is installed but is old, (newer package is available)
    - repo = "local"
    - elif not pac.inst_ver == '-':
    - version = pac.inst_ver # Is Installed (no more no less)
    - repo = "local"
    - elif pac.installed:
    - version = pac.version # After package is installed, It uses this
    - repo = 'local'
    + if pac.installed:
    + version = pac.inst_ver
    + repo = "local"
    else:
    - version = pac.version # Package not installed
    + version = pac.version
    repo = pac.repo
    pack_dir = "-".join((pac.name, version))
    @@ -259,7 +238,7 @@
    except ValueError:
    begin = desc.index("%SIZE%") + len("%SIZE%")
    - end = desc.index("\n\n", begin)
    + end = desc.index("%", begin)
    size_s = desc[begin:end].strip()
    size_int = int(size_s)
    measure = "byte(s)"
    @@ -296,12 +275,8 @@
    return installdate
    def _get_reason(self, desc):
    - reason_int = ''
    - try:
    - begin = desc.index("%REASON%") + len("%REASON%")
    - reason_int = int(desc[begin:].strip())
    - except ValueError:
    - pass
    + begin = desc.index("%REASON%") + len("%REASON%")
    + reason_int = int(desc[begin:].strip())
    if reason_int:
    reason = _("Installed as a dependency for another package")
    @@ -310,16 +285,11 @@
    return reason
    - def _get_description(self, desc):
    + def _get_description(self, desc):
    """Set description for the given pac"""
    - description = ''
    - try:
    - begin = desc.index("%DESC%") + len("%DESC%")
    - end = desc.index("\n\n", begin)
    - description = unicode(desc[begin:end].strip(), errors="ignore")
    - except ValueError:
    - pass
    + begin = desc.index("%DESC%") + len("%DESC%")
    + end = desc.index("%", begin)
    + description = unicode(desc[begin:end].strip(), errors="ignore")
    return description
    def _get_dependencies(self, path):
    @@ -330,8 +300,8 @@
    try:
    begin = deps.index("%DEPENDS%") + len("%DEPENDS%")
    except ValueError:
    - return None
    - end = deps.find("\n\n", begin) #- len("\n")
    + return ""
    + end = deps.find("%", begin) - len("%")
    dependencies = deps[begin:end].strip()
    depends = dependencies.split("\n")
    deps = ", ".join(depends)
    @@ -340,12 +310,9 @@
    def _get_req_by(self, path):
    """Set list of packages that needs given pac"""
    depends = open("%s/depends" %path).read()
    - if "%REQUIREDBY%" in depends:
    - begin = depends.find("%REQUIREDBY%") + len("%REQUIREDBY%")
    - end = depends.find("%", begin) - len("%")
    - else:
    - return
    +
    + begin = depends.find("%REQUIREDBY%") + len("%REQUIREDBY%")
    + end = depends.find("%", begin) - len("%")
    reqs = depends[begin:end].strip().split("\n")
    req_by = ", ".join(reqs)
    @@ -356,16 +323,11 @@
    if not pac.installed:
    return _("%s is not installed") %pac.name
    - try:
    - files = open("%s/files" %path).read()
    - except ValueError:
    - return
    - if files:
    - begin = files.find("%FILES%") + len("%FILES%")
    - end = files.find("\n\n", begin) - len("%")
    - filelist = files[begin:end].strip()
    - pac.filelist = filelist
    + files = open("%s/files" %path).read()
    + begin = files.index("%FILES%") + len("%FILES%")
    + end = files.find("%", begin) - len("%")
    + filelist = files[begin:end].strip()
    + pac.filelist = filelist
    return
    def set_orphans(self):
    @@ -436,7 +398,7 @@
    for pac in self[repo]:
    if not pac.prop_setted:
    self.set_pac_properties(pac)
    - if pac.description.count(desc):
    + if pac.description.count(desc):
    pacs.append(pac)
    continue
    continue
    Binary files gtkpacman/gtkPacman/pacman.pyc and gtkpacman-2.0/gtkPacman/pacman.pyc differ
    Binary files gtkpacman/gtkpacmanc and gtkpacman-2.0/gtkpacmanc differ
    If you patched gtkpacman with old patch I recomend to first reinstall gtkpacman and patch it with this patch.

  • JInternalFrame inside JInternalFrame.

    Dear All,
    I must miss something, please help me to figure out.
    I have a JFrame, JDesktoppane, several JInternalFrame.
    JFrame.getContentPane().add(JDesktopPane);
    JDesktopPane.add(JInternalFrame);
    so far so good.
    Now for Created JInternalFrame ( Named as JIF1), I want to create another JInternalFrame(Named as JIF1_1) to add to JIF1.
    MyPanel extends JPanel
    MyPanel.setLayou(new BorderLayout());
    MyPanel.add(JSCollPane);
    etc......
    MyPanel map=new MyPanel();
    JDesktopPane desktopPane1_1=new JDesktopPane();
    JIF1.getContentPane().add(desktopPane1_1);
    Problem Line:desktopPane1_1.setLayout(new BorderLayout());
    ((JLayeredPane)desktopPane1_1).setLayer(map, JLayeredPane.DEFAULT_LAYER.intValue());
    JIF1_1=new JInternalFrame();
    desktopPane1_1.add(JIF1_1, JLayeredPane.PALETTE_LAYER);
    If I don't open JIF1_1, everything is OK. my JIF1 shows up with "map" panel inside, when resize JIF1, scrollbar shows also.
    NOW Open JIF1_1, run time error: desktopPane1_1 should not setLayout.
    change my code to :
    MyPanel map=new MyPanel();
    JDesktopPane desktopPane1_1=new JDesktopPane();
    JIF1.getContentPane().add(desktopPane1_1);
    REMOVE 1://Problem Line:desktopPane1_1.setLayout(new BorderLayout());
    ((JLayeredPane)desktopPane1_1).setLayer(map, JLayeredPane.DEFAULT_LAYER.intValue());
    JIF1_1=new MYJInternalFrame();
    in JIF1_1 class put
    //this method to change "map" JPanel size correctly when resize JIF1_1;
    REMOVE 2:public void paintComponent(Graphics g)
    super.paintComponent(g);          
    Rectangle mar=map.getBounds();
    Rectangle r=this.getBounds();
    int w=(int) r.getWidth();
    int h=(int) r.getHeight();
    map.setSize(new Dimension(w,h));
    map.setPreferredSize(new Dimension(w,h));
    ma.setPreferredSize(new Dimension(w,h));
    map.invalidate();
    map.validate();               
    map.repaint();          
    map.revalidate();
    map.repaint();
    desktopPane1_1.add(JIF1_1, JLayeredPane.PALETTE_LAYER);
    NOW, when I resize JIF1_1, "map" JPanel resize correctly, but my scrollbar does not show up correctly.
    If I remove REMOVE 2, put back REMOVE 1, don't open JIF1_1(Because setLayout runtime error), Scrollbar on "map" JPanel shows up when resize JIF1_1
    Since I need to open JIF1_1, revome REMOVE 1(setLayout to null instead of borderLayout), don't remove REMOVE 2, call open JIF1_1, but scrollbar on "map" JPanel does not show when resize JIF1_1.
    Please help me with this. Thank you!
    Xinman

    Never Mind, found the error!!!!! :)
    In paintComponent , need to get desktop size instead of JIF1_1 size
    Xinman

Maybe you are looking for