How To: Keeping component in bounds

Hi,
I am working on creating a Container which allows components to be dragged around inside of it. This is similar to JDesktopPane which has JInternalFrames which can be moved around inside it...
Anyhow, I want to prevent a component from being dragged out of bounds. What I would like is the same affect as the JDesktopPane...where if a frame is dragged to the edge, it will just move around the edge, it wont go out...no what I mean? What I have implemented prevents the component from being dragged out of bounds, but when the component gets to the edge it just stops moving instead of sliding around the edge.
Any suggestions on what to do to improve this or make it like JDesktopPane (i have tried looking for the code in JDesktopPane and DefaultDesktopManager..but couldnt find it)..
here is what i currently do:
in the mouseDragged method i set the new location of the component according to the MouseEvent that occurred...
then i check to see if the 4 points (the top left, top right, bottom left, bottom right) of the component are contained within the container (i.e. myContainer.contains(top_leftPoint), etc)...
if all 4 points are in, then i do,
container.repaint()
else
component.setLocation(oldX, oldY)
container.repaint()
...any ideas?
Thanks...duke dollars are offered as well

Sorry again. Its not my best day today (influenza is coming up).
I don't know why I took JFrame as the container instead of the parent container.
Here is the improved version :
import java.awt.*;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JPanel;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
public class Plate extends JPanel {
    private String name;
    private Container c;
    private Point top_leftPoint, top_rightPoint, bottom_leftPoint, bottom_rightPoint ;
    private Point top_leftPointC, top_rightPointC, bottom_leftPointC, bottom_rightPointC ;
    private int w,h,wC,hC;
    public Plate(String name) {
        this.name = name;
        init();
    private void init() {
        setPreferredSize(new Dimension(100, 100));
        setBorder(new TitledBorder(new LineBorder(Color.BLACK), name));
    private boolean isInContainer(){
        c = getParent();
        Rectangle r = new Rectangle( c.getWidth(), c.getHeight() );
        wC = (int)r.getWidth();
        hC = (int)r.getHeight();
        top_leftPointC = r.getLocation();
        top_rightPointC = new Point( (int)top_leftPointC.getX()+wC, (int)top_leftPointC.getY() );
        bottom_leftPointC = new Point( (int)top_leftPointC.getX(), (int)top_leftPointC.getY()+hC );
        bottom_rightPointC = new Point( (int)top_leftPointC.getX()+wC, (int)top_leftPointC.getY()+hC );
        w = getWidth();
        h = getHeight();
        top_leftPoint = getLocation();
        top_rightPoint = new Point( (int)top_leftPoint.getX()+w, (int)top_leftPoint.getY() );
        bottom_leftPoint = new Point( (int)top_leftPoint.getX(), (int)top_leftPoint.getY()+h );
        bottom_rightPoint = new Point( (int)top_leftPoint.getX()+w, (int)top_leftPoint.getY()+h );
        if( !r.contains(top_leftPoint) ) return false;
        if( !r.contains(top_rightPoint) ) return false;
        if( !r.contains(bottom_leftPoint) ) return false;
        if( !r.contains(bottom_rightPoint) ) return false;
        return true;
    public void stayInContainer(){
        /* if the plate goes is too far in right-direction, shift it back*/
        if( !isInContainer() ){   
            double x = top_rightPoint.getX();
            double xC = top_rightPointC.getX();
            if( x > xC ){
                setLocation( (int)(top_leftPoint.getX()+xC-x), (int)top_leftPoint.getY());
        /* if the plate goes is too far in left-direction, shift it back */
        if( !isInContainer() ){
            double x = top_leftPoint.getX();
            double xC = top_leftPointC.getX();
            if( x < xC ){
                setLocation( (int)(top_leftPoint.getX()+xC-x), (int)top_leftPoint.getY());
        /* if the plate goes is too far in top-direction, shift it back */
        if( !isInContainer() ){
            double y = top_leftPoint.getY();
            double yC = top_leftPointC.getY();
            if( y < yC ){
                setLocation( (int)top_leftPoint.getX(), (int)(top_leftPoint.getY()+yC-y));
        /* if the plate goes is too far in bottom-direction, shift it back */
        if( !isInContainer() ){
            double y = bottom_leftPoint.getY();
            double yC = bottom_leftPointC.getY();
            if( y > yC ){
                setLocation( (int)top_leftPoint.getX(), (int)( top_leftPoint.getY()+yC-y) );
import java.awt.*;
import java.awt.Component;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JPanel;
public class PlateCanvas extends JPanel implements MouseListener, MouseMotionListener {
    private Plate hitPlate;
    private double deltaX;
    private double deltaY;
    Point previousLocation;
    boolean first = true;
    public PlateCanvas() {
        init();
    private void init() {
        addMouseListener(this);
        addMouseMotionListener(this);
    public void mouseClicked(MouseEvent e) {
    public void mouseEntered(MouseEvent e) {
    public void mouseExited(MouseEvent e) {
    public void mousePressed(MouseEvent e) {
        Component c = getComponentAt(e.getPoint());
        if (c instanceof Plate) {
            hitPlate = (Plate) c;
            deltaX = e.getX() - hitPlate.getX();
            deltaY = e.getY() - hitPlate.getY();
    public void mouseReleased(MouseEvent e) {
        hitPlate = null;
    int max,newX,newY;
    public void mouseDragged(MouseEvent e) {
        if (hitPlate != null) {
            int x = (int) (e.getX() - deltaX);
            int y =     (int) (e.getY() - deltaY);
            hitPlate.setLocation(x, y);
            hitPlate.stayInContainer();
            repaint();
    public void mouseMoved(MouseEvent e) {
import javax.swing.JFrame;
public class TestPlates {
    public static void main(String[] args) {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        PlateCanvas mainPanel = new PlateCanvas();
        Plate p1 = new Plate("Plate 1");
        Plate p2 = new Plate("Plate 2");
        Plate p3 = new Plate("Plate 3");
        mainPanel.add(p1);
        mainPanel.add(p2);
        mainPanel.add(p3);
        f.getContentPane().add(mainPanel);
        f.setSize(800, 600);
        f.setVisible(true);
}

Similar Messages

  • How to keep entering data in web pages

    hi,
    i am using ADF 11g 2 release. I have remote application connect with ADF jar lib and local application. when i enter data to my local application and redirect to remote application and enter the data their also. But when I link to local app page via url view but I entered data is not there. I am not commited any page data. In remote app... alos link but there also no data. how to keep them??
    all page in taskflow and they connect with control flow case. I made Auto submit true and immediate true for text component.. but no any change.
    can not use any setting changes? Need java coding for both application??
    hoping chance..
    thanks.

    hi,
    I have developed ADF 3 web applications. 2 of them are connect as ADF jar lib files in other application. That application name is local application and other 2 mentioned as remote application(jar lib files). those are in taskflowcall. IN my Local Application which has Application Module. so I selected remote application's Application modules as Application Module Instances. Then in my Local Application DataControl which include that added Application Modules inside the local application DataControl. which are in nested. Remote application DataControl also appear in the local app DataControl.
    Problem is I want to save all applications data through my local application. therefore I link to first remote app and enter data but not commit ,then come back to local app.. and enter data and again goto first remote app again, BUT entered data Not there. so I want to keep them and save all 2 remote app data and local app data.
    DCDataControl dc = bc.findDataControl("TestRemoteAppDataControl"); // *<-- this is one of my remote application Data control name..*
    ApplicationModule am = (ApplicationModule)dc.getDataProvider();
    am.getTransaction().commit();
    dc.commitTransaction();
    this code is not worked. BUT local app data only saved using below code...
    BindingContext bc =BindingContext.getCurrent();
    DataControlFrame dcf= bc.findDataControlFrame(bc.getCurrentDataControlFrame());
    Collection<DCDataControl> dcCol =dcf.datacontrols();
    for(DCDataControl dCDataControl : dcCol) {
    if(dCDataControl.isTransactionDirty()){
    try{
    dCDataControl.commitTransaction();
    catch(Exception e) {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), null));
    e.printStackTrace();
    thanks ,hopping chance.
    any who know this??
    thanks.

  • How to keep lead selections in alv table...

    Hi experts.
    I made a alv.
    A logic  in wdmodifyview is following..
    METHOD wddomodifyview .
      IF first_time EQ abap_true.
        wd_comp_controller->set_alv_config( ).
      ENDIF.
      wd_this->set_maktx( ).  "<- for displaying maktx
    ENDMETHOD.
    When I want to select a line, do not selected.
    I know because of "wd_this->set_maktx( )." sentence.
    But I want to select multi lines in above condition...
    How to keep selected lines in alv?
    Help me please.
    Thanks.
    Regards.

    What logic is taking place in wd_this->set_maktx( )?  It is pretty difficult to say what is causing the issue without knowing what code you are executing?  If you are resetting the context bound to the ALV, that would explain why you are losing your selections.

  • How to keep track of what I've previously draw

    They said:
    Everytime the paint method is called, everything that was drawn before must be redrawn. The paint method has no way to keep track of what you've previously drawn, it is your responsibility as the programmer to keep track of such things.
    Is this right?
    How can keep track of my random shades of random amounts?
    Is there a simple way to do that?
    In a example, I must use getGraphics to get JPanel's graphics, then I use it to random draw something in the JPanel.
    I just want to keep them in my JPanel when it resizes.I haven't get the answer yet.
    Can you help me?

    Ok I haven't got time to write the code for you, but here's the idea:
    //User drags mouse around to draw on screen
    //use mouseActionListener to catch MouseDragged event
    int x = mouseEvent.getX();
    int y = mouseEvent.getY();
    Point p = new Point(x,y);
    arrayListOfPoints.add(p);
    // end mouse action capture
    //override paint method of component
    public void paint(Graphics g){
        super(g);
        Iterator it = arrayListOfPoints.iterator();
        while(it.hasNext()){
            Point p = (Point)it.next();
            g.drawLine(p.getX(),p.getY(),p.getX(),p.getY())   

  • Portlet:namespace val changes on server restart. How to keep it constant?

    Hi -
    I want to generate WinRunner test script, and want to know the IDs of a couple of UI components on a JSF JSP.
    But JSF prefixes each component id with <portlet:namespace/> value. So, I tried to prefix the same value (got it using view source of the actual screen to test) to the components in my test script.
    This works just fine, the way I want it to, but until the server is not restarted.
    Once the server is restarted the value of the <portlet:namespace/> changes (for the same view in same jsp), thus my test script doesn't work.
    Is this expected behavior that for the same view in jsp, the value of <portlet:namespace/> changes after server restart?
    Is there a way to keep the value of <portlet:namespace/> constant for the same view even after server restart?
    Expecting prompt feedback and will highly appreciate it.
    Thanks
    Gagan

    The problem is still there if the jsp file is about inserting a new record
    into the database.
    If these parameters are gotten from the session, mutliple insertings will be
    attempted when the portlet is refresh.
    Maybe we can put some control flags in the session to judge the correct
    behavior, but the method results the session full of parameters(control
    flags).
    Or is there any better design?
    Alan.
    "travis wissink" <[email protected]> ¼¶¼g©ó¶l¥ó
    news:3cc71962$[email protected]..
    >
    Alan,
    You could use the session to put your parameters in instead of letting itride completely
    on the request object. Although, your question is more than just makingthe content
    reappear, it’s about holding state. The project that I am working on, theusers
    decided that they want the page portlets to go back to the "normal" state,not the
    "Maximized" view. So, I put a processor in between the internal.refreshwildcard
    and the Preprocessor input processor so that all the portlets would beseen in their
    "normal" state.
    Good Luck
    -Travis
    "Alan Liu" <[email protected]> wrote:
    Hi All,
    When I click page tabs in WLP, it will trigger a refresh event.
    The portlet has a webflow with a refresh event whose destination is
    lastContentUrl(referent-namespace is portal, cloned from portlet2.wf).
    The question is when the page changed, the jsp files which use
    request.getParameter() to get parameters will fail to fulfill what they
    need because the event provide none parameter.
    So that everytime page changed, these portlets will have quite strange
    contents.
    How to keep these content constant when page changed?
    Sincerely,
    Alan.

  • How to keep multiple function modules under one Web service

    Hi Experts,
    I have Three RFC function modules and i need to create one web service for these three RFC function modules. I know How to crearte a web service for one function module.
    please suggest me How to keep multiple function modules under one Web service.
    Thanks in advance
    Lakshminarayana

    Hi Lakshmi,
    The best way to do it is to assign all the three RFC Enabled FM's to one function group. Later on the top menu in Utilities you get an option to Create a Webservice from a Function Group.
    You can create one single Webservice using all the the 3 FM's.
    I hope this helps.
    Thanks,
    Manu

  • How to keep FI posting period (OB52) closed but keep CO posting periods (OK

    Hi SAP Guru's,
    how to keep FI posting period (OB52) closed but keep CO posting periods (OKP1) open.
    I.e. on Oct 21th the FI posting period 10 should be open but FI posting period 09 should be closed. But on Oct 21th the CO posting period 09 should be open.
    Thanks in Advance.
    RV

    You've already activeted. You can check in IMG-Financial Accounting Global Settings (New) ® Ledgers ® Real-Time Integration of Controlling with Financial Accounting
    Check this for more info http://help.sap.com/saphelp_dimp50/helpdata/en/22/c2cf4031288131e10000000a1550b0/content.htm

  • How to keep file name in print queue when printing crystal report

    We are using VB .Net 2003 + Crystal Report 2008 SP2 up to Fix Pack 2.6
    When the VB program spools crystal report files to print queue, the print queue only shows "Crystal Report" for each document.  How to keep the original file name?  In the past when we were using Crystal Report 11, the original file name can be shown in the print queue.
    Please help because it's so important for operation to see which report is failed in printing when reports are printed in batch.
    Thanks

    Hello,
    Set the PrintOption.JobTitle value for the print job. Here's C# code on how to:
                   System.Drawing.Printing.PrintDocument pDoc = new System.Drawing.Printing.PrintDocument();
                CrystalDecisions.ReportAppServer.Controllers.PrintReportOptions rasPROpts = new CrystalDecisions.ReportAppServer.Controllers.PrintReportOptionsClass();
                CrystalDecisions.ReportAppServer.ReportDefModel.PrintOptions newOpts = new PrintOptionsClass();
                   pDoc.PrinterSettings.PrinterName = cboCurrentPrinters.Text;          
                   rasPROpts.PrinterName = cboCurrentPrinters.Text;               
                   rasPROpts.PaperSize = (CrPaperSizeEnum)
                        pDoc.PrinterSettings.PaperSizes[cboCurrentPaperSizes.SelectedIndex].Kind;
                // this sets the name of the print job
                rasPROpts.JobTitle = "MYPrintJob";
                   rptClientDoc.PrintOutputController.PrintReport(rasPROpts);
                   MessageBox.Show("Printing report.", "RAS", MessageBoxButtons.OK,MessageBoxIcon.Information );
    Thank you
    Don

  • Macbook Pro - How to keep a low cycle count

    hey everyone,
    Basically I purchased a new macbook pro 11 days ago, and My current cycle count is also 11. I am eager to keep my cycle count down this time round as my last macbook's battery died at around the 700 mark (the laptop was around 15 months old at the time) which I am told was very high. The average apparently being around 300 for a computer that old.
    I have also read on other forums that people have managed to keep their cycle counts much much lower than 300 even for laptops over 15 months old.
    So to maintain my battery's life this time round I was wondering if anyone had any tips on how to keep the cycle count down this time round?
    Many thanks,
    Josh

    I should point out that the batteries that seem to survive the longest are those that get used--i.e. relatively high cycle counts. They are like muscles--use them or lose them. I tried keeping cycles down on my first battery and the results were that it made it only 11 months. Most of the "my battery failed..." posts we see here show a low cycle count.
    Also, you've posted a question about a new MBP in the forum for older ones made in Early 2008 and before. As the battery technology in your new MBP is different (and apparently better) and you have other hardware improvement made since 2008, you should use the forum for the current-generation MBPs here:
    http://discussions.apple.com/category.jspa?categoryID=251
    Not to worry. It's not your fault you found the wrong forum. "Original MacBook Pro" is a pretty non-intuitive label! About a dozen people a day with new MBPs end up here and sometimes get inappropriate advise if responders either don't notice of can't tell that the OP is asking about a newer Mac.

  • How to keep all text and formats the same on multiple computers?

    I'm creating a file in InDesign CS6 on my Windows computer. I keep everything on my flash drive. When I go to school, I bring my flash drive with me and open it up on the Mac computer, but then there are are compatibility issues. There seems to be missing fonts and formats but the school uses the same version of InDesign I do. Now I was told a lot of things of how to keep the fonts and formats the same (embed the links, package the files, outline the text, save as IDML). However, it is not clear to me what each of those options do, so I don't know when or why to use them. So I just want to make sure that when I bring in my file in next Monday, I won't have any missing fonts or formats. What would you suggest is the proper things to do to keep everything the same on multiple computers? And could you please explain why?

    If you want cross-paltform comaptibility limit the fonts to OpenType or Windows TrueType formats, both of which work on both Mac and PC. To avoid missing font warnings the fonts must either be installed on each computer, or they must be in a folder named Document Fonts in the same location as the .indd file they are to work with. Packaging the file will build taht folder for you.
    the rest of the stuff in your list won't help you. .idml would allow you to open on an older version, but does nothing for your situation. Embedding the links will keep you from having missing links, but so will packaging, and embedded links will make the file much larger and harder to work with.
    For goodness sake, don't even think about outlining the text. It stops being text when you do that and you can no longer edit it.
    And finally. do yourself a big favor and don't attempt to actually work on your file directly from the flash drive. Copy the whole package folder to the hard drive, work on it, then copy back. You don't want to know how many files are fatally damaged by write errors on flash drives.

  • Does anyone know how to keep all songs in the same album when they say featuring someone?

    Each time I load a CD onto Itunes that has an artist who features another artist on that particular song, it puts it in my library as a separate CD even though it will have the same album listed.  For instance Lady Gaga's song just dance features Colby O'Donnis that song is in its own spot while the rest of the cd is together that one song is separate and I don't know how to keep them all together.  Someone help.

    Get the Informations for that song and have a look in the "Sorting" area if there is something different. The data inserted there is just for how iTunes will order the songs.
    If the Interpret in the general informations is "Lady Gaga" and in the sorting area is "Lady Gaga feat. xxxx" than you'll see Lady Gaga as the interpret but it's sort to a second entry "Lady Gaga feat. xxxx".

  • How to keep songs on iphone, work computer and home computer the same?

    How to keep songs on iphone, work computer and home computer the same?
    This seems like something everyone would want to do. I don't know why Apple won't give us a simple solution. They could even charge us for it. I would pay!
    Has anyone solved this? What is your solution?
    Thanks!
    [email protected]

    If you just want to be able to sync your devices to the same PC without having them get overwritten all the times, here is a free method
    http://cnettv.cnet.com/sync-your-ipod-two-computers/9742-1_53-50004835.html
    Basically, you put the same itunes database file on all the PCs. This fakes itunes into thinking it is always the same PC and the ipod is OK to sync with it. It will NOT keep your libraries truly synced, though. I've just resigned myself to always buying from one PC and manually transferring the content to other PCs I want it on.

  • How to keep track of how many times a link has been clicked?

    How to keep track of how many times a link has been clicked or accessed? Do I need to use database for this?

    Hi
    Proably something like this can work,
    1> Have a servlet/bean invoked when the link is linked
    2> have a static variable in that servlet/bean wich gets incremented before the control is passed to another desired page..
    The problem with this approach is that care has to be taken that the servlet/bean is not re-instalised, in case of which the static variable will also be instalised and the data would be lost.
    The best thing is to store the count in the database.
    Regards
    Arathi.

  • How to keep the WBS & Order in account assignment tab of SD contract item?

    Hi Experts,
    If I remove the plant from the shipping tab in the contract item (the contract type is WV), I will be able to enter the WBS or Order in accounting assignment tab. However, if I enter the plant (in order to determine the tax in pricing), the WBS and Order are disappered and there is one new settlement rule button showed up.
    Do you know any configuration could keep the WBS and order in the accounting assigment tab even the plant is there.
    Thanks in advance!
    Norman

    Hi Chandra,
    Thanks for your answer. However, I even added the plant in the WBS, the tax (we use tax jurisdiction) still could not be determined.
    The problem is that SAP changes the account assignment tab screen (it suppresses the WBS and Order fields, but addes settlement rule) with the plant in the shipping tab. Do you know how to keep the same account assignment tab screen with the plant in the shipping tab?
    Thanks,
    Norman

  • How to keep email messages on iPhone using iCloud

    I can't figure out how to keep opened email on my iPhone.  If I have previously opened message on my iMac and it is in the Inbox on my iPhone, it disappears as soon as I try to open it.    Often I want to re-read a message.   Surely there must be a way to keep them for a period of time on the iPhone.
    John

    You could just pay for backup space (if iCloud offers it). I am only familiar with MobileMe, so I am not sure. This may help.

Maybe you are looking for