Center JLabels in component

Hi friends!
I have a problem in disposing some JLabels in a JPanel.
I'm using the BoxLayout to have a JLabel "per line".
  setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));I want to center the labels in horizontal and vertical axis.
To center horizontal I use
jLabel.setAlignmentX(CENTER_ALIGNMENT);I want to center in vertical axis so I wrote
jLabel.setAlignmentY(CENTER_ALIGNMENT);but this doesn't work!
Does anyone know what's the problem??
Please help!
Thanks in advance.

I try to do your suggestions but it doesn�t work.
Here http://webx.ubi.pt/~a13933 I show a screenshot of my application, as you can see the labes are in the top of cells. I want to center them. I'm doing this at the cellRender.
here is the code.
public class JLabelCellRender extends JLabelsPanel implements  TableCellRenderer {
    Border b;
    /** Creates a new instance of PLIconLabel */
    public JLabelCellRender() {
        super(); /* null indicates no layour manager */
        setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
        b=BorderFactory.createLineBorder(Color.black);
    public java.awt.Component getTableCellRendererComponent(JTable table,
            Object value,
            boolean isSelected,
            boolean hasFocus,
            int row, int column) {
        removeAll();
        setBackground(getCor());
        Vector modulos=(Vector)value;
          JLabelModuloTurmaMouseEvents me=new JLabelModuloTurmaMouseEvents();
        if(modulos.size()==0)
            return this;
        for(int i=0;i<modulos.size();i++){
            JLabelModuloTurma x=(JLabelModuloTurma)modulos.elementAt(i);
            x.addMouseListener(me);
            x.setAlignmentX(CENTER_ALIGNMENT);
            x.setAlignmentY(BOTTOM_ALIGNMENT);
            if(!x.getText().equals(""))
            x.setBorder(b);
            add(x);
        return this;
}Please help. Thanks again.

Similar Messages

  • How to center  mx:window Component in adobe air

    Hello Friends
                        i am making a simple application in adobe air 2.0 .In this application i made a seprate window on some button click.but every time it open with random positoning i just want to center that window component.if any body having any idea then please guide me.
    Thanks and regards
       Vineet Osho

    This depends on the type of server from which you are downloading the files. For example, if you are downloading the files from an HTTP server, and the server provides "Last-Modified" values in the HTTP response headers, you could use the following ActionScript code to determine those values:
    var urlReq:URLRequest = new URLRequest("http://www.example.com/");
    var urlStream:URLStream = new URLStream();
    urlStream.addEventListener(HTTPStatusEvent.HTTP_RESPONSE_STATUS, statusListener);
    urlStream.load(urlReq);
    private function statusListener(event:HTTPStatusEvent):void
        for each(var header:URLRequestHeader in event.responseHeaders)
            if(header.name == "Last-Modified")
                trace(header.value);

  • Profit Center Assignment for Component of Sub Contracting PO

    Hello all!
    I apologize in advance if this is not the correct forum to post this question in. Additionally, I am an ABAPer with a focus in SD and MM, so much of FI is foreign to me.
    To the problem...
    Currently when a MIGO 101 is processed for a Sub Contracting PO Line item, a consumption transaction (543) is generated for the component materials on the PO Line. These consumption transactions are "tied", this is how my finance co-worker described it, to a Cost Center dedicated to Sub Contracting.
    We would like to change the configuration as follows:
    When the consumption transaction posts, it "ties" to the Profit Center (and thus cost center) of the Parent SKU (actual material received on PO Line) of the transaction.
    Is this possible?
    Thank you,
    Steven Coolbaugh

    Hi Steven:
    Not sure if I understood correctly your requirement but let me try to explain:
    For consumption items (Account assignment category K in PO line), it is consumed immediately on GR and consumption is posted to a cost center attached to PO line. And that is what happening in your exising process also, right?
    Now when you said "TO Be" change as consumption ties to the profit center (and then to cost center) of parent SKU??
    It is other way round. A cost center is linked to one profit center (whereas as a profit center can have many cost centers attached to it). Also since profit center is not a TRUE cost object (it is a statistical object), PO line would need a true cost object like cost center. So based on the information you provided in your post, it is not technically possible to book consumption at profit center (And then to cost center).
    Are they two separate cost centers (one for sub contracing and one for Parent SKU)? If yes, can you attach parent SKU cost center to PO line (from business point of view) so that consumption posts directly to parent SKU and then to the attached profit center?
    Hope it helps.
    Thanks.
    Rahul

  • Plant Maintenance, work center & component.

    Hi, I have some question as below:-
    company code: 1000
    Plant A: 1100
    Plant B:1200
    Component storage location under 1100
    Q1: work center for plant B is under 1200, so if work center need the component for maintenance job, then they need do the STO to transfer component from plant 1100 to 1200?
    Q2: work center for plant B is under 1100, so they NOT need do the STO to transfer component to do the job at 1200?

    Hello Dear,
                       Can you please tell which is the Maintenance Plant,
    if the maintenance Plant is different from the main Plant then you need to do the STO for the Main Plant(B),
    if you have assigned both the Maintenance plants to the main plant then no need for the STO.
    Hope it helps
    Regards,
    Yawar Khan

  • Painting GIF images/using JLabels for GIFs... Somehow, make it work!

    Ok, I am basically making an arena for a local multiplayer game for my friends, and across the top of the screen is a title ... lets call the title "Game Title". The entire game is contained in 1 JFrame, including the title, sidebars, and the actual "game" part in the middle. I paint all of the objects in the game by painting them in the JFrame's Graphics when the paint() method is called.
    Basically, the window looks like this:
    | /\./\./\./\./\....Game Title..../\./\./\./\./\ |
    |...........______________..............|
    |...........|.--.game area.--..|..............|
    |...........|_____________|..............|
    Where the /\./\./\'s are animated flames. I have tried to just make them as ImageIcons in JLabels, but no matter what I paint() after the labels are added, the window looks like this:
    | /\./\./\./\./\ .......................... /\./\./\./\./\ |
    |.........................................................|
    |.........................................................|
    |.........................................................|
    Where the flames are animated, but the "background" is always gray. I then tried to paint them as Images (g.drawImage(new ImageIcon(url).getImage(),0,0,null), but that only leaves the first frame of the animated GIF (in other words, its not animated).
    What do I do? I have been reading around the forums, but I cannot find a case where somebody needed the GIF inside a Component that they used for painting...
    Thanks for any help that you give!

    If you're going to paint use a graphic component to do your painting in and don't add any components to it. The 'paint' method in JFrame is called by swing to draw the JFrame and its components. Using it to do custom painting is tricky. You'll need to call 'super.paint' to allow the container to paint its children. See the method detail in the JFrame api (link is in the Container section of the api). Also check the 'paintComponent' and 'paint' methods in the JComponent api method details section.
    import java.awt.*;
    import java.awt.image.BufferedImage;
    import java.io.IOException;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    public class Painting extends JPanel
        BufferedImage image;
        public Painting(BufferedImage image)
            this.image = image;
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            g.drawImage(image, 125, 175, this);
        private JPanel getTitlePanel()
            JLabel title = new JLabel("Game Title", JLabel.CENTER);
            JLabel flame1 = new JLabel("flames");
            JLabel flame2 = new JLabel("flames");
            JPanel panel = new JPanel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.weightx = 1.0;
            panel.add(flame1, gbc);
            panel.add(title, gbc);
            panel.add(flame2, gbc);
            return panel;
        public static void main(String[] args) throws IOException
            String path = "images/Bird.gif";
            BufferedImage bi = ImageIO.read(Painting.class.getResource(path));
            Painting painting = new Painting(bi);
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(painting.getTitlePanel(), "North");
            f.getContentPane().add(painting);
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
    }

  • How to print the JFrame In The Center Of The Page?

    hi there in the following code iam trying to print a JFrame
    but the frame appear in the printed page at the top left
    and i want it to appear in the top center of the page
    how to do that?
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.print.*;
    class PrintUIWindow implements Printable, ActionListener {
        JFrame frameToPrint;
        public int print(Graphics g, PageFormat pf, int page) throws
                                                            PrinterException {
            if (page > 0) {
                return NO_SUCH_PAGE;
            Graphics2D g2d = (Graphics2D)g;
            g2d.translate(pf.getImageableX(), pf.getImageableY()-55);
            frameToPrint.print(g);
            return PAGE_EXISTS;
        public void actionPerformed(ActionEvent e) {
             PrinterJob job = PrinterJob.getPrinterJob();
             job.setPrintable(this);
             boolean ok = job.printDialog();
             if (ok) {
                 try {
                      job.print();
                 } catch (PrinterException ex) {
        public PrintUIWindow(JFrame f) {
            frameToPrint = f;
        public static void main(String args[]) {
            UIManager.put("swing.boldMetal", Boolean.FALSE);
            JFrame f = new JFrame("Print UI Example");
            f.addWindowListener(new WindowAdapter() {
               public void windowClosing(WindowEvent e) {System.exit(0);}
            JLabel label1=new JLabel("Selling Bill",JLabel.CENTER);
            JLabel label2=new JLabel("Customer Name :Mahmoud Saleh       ",JLabel.LEFT);
            JLabel label3=new JLabel("Buying Date :29/8/2008             ",JLabel.LEFT);
            JLabel label4=new JLabel("Book Buyed :Java Printing          ",JLabel.LEFT);
            JLabel label5=new JLabel("Number : 6 Copies                  ",JLabel.LEFT);
            JLabel label6=new JLabel("Total Price :600 $                 ",JLabel.LEFT);
            label1.setFont(new Font("Courier New", Font.BOLD, 13));
            label2.setFont(new Font("Courier New", Font.BOLD, 13));
            label3.setFont(new Font("Courier New", Font.BOLD, 13));
            label4.setFont(new Font("Courier New", Font.BOLD, 13));
            label5.setFont(new Font("Courier New", Font.BOLD, 13));
            label6.setFont(new Font("Courier New", Font.BOLD, 13));
            JButton printButton = new JButton("Print This Window");
            printButton.addActionListener(new PrintUIWindow(f));               
            JPanel panel=new JPanel();
            panel.setLayout(new GridLayout(6,1));
            panel.add(label1);
            panel.add(label2);
            panel.add(label3);
            panel.add(label4);
            panel.add(label5);
            panel.add(label6);
            f.setSize(300,300);       
            f.setLocationRelativeTo(null);       
            f.add(panel,BorderLayout.CENTER);
            f.add(printButton,BorderLayout.SOUTH);
            panel.setBackground(Color.WHITE);
            f.setResizable(false);
            f.setVisible(true);
    }

    First_knight wrote:
    please tell me am i thinking right
    about this method: setImageableArea(.....)
    public void setImageableArea(double x, double y,  double width, double height);
    like I said, I've tried this method and it doesn't seem to do anything.
    the width=the JFrame Width,the height=the JFrame Height right?actually, when printing, 72 points (printing version of pixels) = 1 inch, so to do WYSIWYG, you need width = JFrameWidth * 72.0 / Toolkit.getToolkit().getScreenResolution. Ditto with height
    upper left beginningx(0)---------------------------200--------------------------------600-----------------------------------y(1000)upper right beginningyou need to do something like PageSetup.getImageableX and do Graphics.translate(x,y);
    also, if your page width = 720, that = 10 inches - that's a wide page (unless its in landscape)
    so if i want the JFrame To Be In The Center Of The Page I Would Choose From x=200 ,y=600 depending that frame width is 400Actually, it would be 300 - 700 in your example
    Because when i tried to use:setImageableArea(200, 600,  400, 200);like the above code
    no changes occurs in the printed paperYes. You need to offset the Graphics object

  • Using the tcode:S_ALR_87013611, no report data  for the cost center

    Hi,Friends.I need a help.
    In the tcode FB60,i entered the following data and then posted the vendor inovice sucessfully.
    data:
    ( Note: G/L acct:55020141 is also a primary cost element)
    In the tcode:S_ALR_87013611,I entered the following data and executed.
    but the result is:{Report contains no data. Check the selection log}.
    data: { Controlling Area: C999, Fiscal Year: 2010, From Period:1, To Period:12,Plan Version:0,
            Or value(s):2001}
    (Note: Cost center:2001 belongs to Controlling Area: C999) 
    please tell me how to do,so that using the tcode:S_ALR_87013611, I can see the report data  for
    the cost center 2001.
    sincerely                      WenYao Ma
    Edited by: wenyao ma on Mar 22, 2010 1:09 PM

    thank you,friends.
    I just solved it.
    Solution:
    1) Maintain Controlling Area
       path:spro>Controlling>Organization>Maintian Controlling Area>Maintain Controlling Area.   tcode:OKKP
    In the {Activate components/control indicators}cost center should be 'component active'
    2) Maintain Number Ranges for Controlling Documents
       path:spro>Controlling>Organization-->Maintain Number Ranges for Controlling Documents.   tcode:KANK
      Element { COIN CO Through-postings from FI} should be assigned to one group.

  • S_ALR_87012309 - No profit center

    Dear experts,
    When our business User executes S_ALR_87012309, for main cash G/L account, the profit centers are not being displayed in the report.
    Our company has new G/L functionality activated.
    Upon further investigation, it is found that S_ALR_87012309 report is picking up values and amounts from BSEG table instead of FAGLFLEXA table which has the profit center information.
    We know FBL3N can be used but we still want to find out if there is any solution/SAP note for this report issue.
    Regards,
    K.Y.

    thank you,friends.
    I just solved it.
    Solution:
    1) Maintain Controlling Area
       path:spro>Controlling>Organization>Maintian Controlling Area>Maintain Controlling Area.   tcode:OKKP
    In the {Activate components/control indicators}cost center should be 'component active'
    2) Maintain Number Ranges for Controlling Documents
       path:spro>Controlling>Organization-->Maintain Number Ranges for Controlling Documents.   tcode:KANK
      Element { COIN CO Through-postings from FI} should be assigned to one group.

  • Trying to center frame, but affects my Robot method

    Hi, I am using a robot to take a screen shot of the users screen, which will then display on top of the screen with a piece of text printed. This works fine, but when I try to center the frame that holds the information the background is replaced with a grey box (with my text in). Is there any way I could get around this at all? Here is the relevant code, all help is very much appreciated. Thank-you :)
        public void createPanel()
            JFrame frame = new JFrame();
            frame.setUndecorated(true);
            frame.setLayout(new BorderLayout());
            MyDisplay test = new MyDisplay(frame);
            test.setLayout(new BorderLayout());
            frame.add(test, BorderLayout.CENTER);
            JLabel label = new JLabel("This is just a test");
            test.add(label, BorderLayout.CENTER);
            frame.pack();
            frame.setSize(500, 200);
            // make sure you pack and/or set size first...
            Dimension dS = Toolkit.getDefaultToolkit().getScreenSize();
            Dimension dF = frame.getSize();
            // make sure it's not off screen
            int x = (dS.width/2)-(dF.width/2);
            int y = (dS.height/2)-(dF.height/2);
            if(x < 0) x = 0;
            if(y < 0) y = 0;
            frame.setLocation(x, y);
            frame.setVisible(true);
            startRobot();
        public void startRobot()
            try {
                robot = new Robot();
                Rectangle r = new Rectangle(500, 200);
                background = robot.createScreenCapture(r);
            catch (Exception e) {
        }

    Swing related questions should be posted in the Swing
    forum.
    If it's swing you want to use,
    I will kindly spread the news.
    Camickr's the one to ask,
    Ask him first, don't wait till last.
    You must post in proper place,
    or the egg is on your face.
    Post where swing will be discussed,
    don't be makin' such a fuss.
    If gui is what you require,
    'bout the swing you should inquire.
    "New to Java" ain't for you,
    Swing's what you should really do.

  • Component reference point in ultiboard

    The default setting for component reference point is the center of PIN 1 of the part. however, for many SMT machines, it reference to the center of the component (not a pin). 
    How doImodify it without going through every component in the database?
    Solved!
    Go to Solution.

    The PIN 1 reference point gets used for positioning the part on your layout. When you export the centroid file, you will see the coordinates for the center of the component.
    I prefer to know where that center is so I don't get surprised by oddball SMT coords. This is yet another reason why we maintain our own corporate database of footprints, with the reference point set to the center (or nozzle pick-up point) of the component. 

  • IBASE component not required  in CIC

    Hello,
    In cic0, in bp search my client does not want the Ibase component as Ibases are not used. How can i disable it.
    please help urgent matter.
    Pramod.

    Pramod,
    Here is how to go about terminating the IBASE out of your BP search.
    Use T. code :smw0
    Select the radio - HTML templates for WebRFC applications and
    execute.
    Click on execute again in the screen that appears.
    Create a new  object by copying CRM_CIC_SEARCH_DISPLAY
    Again run the transaction SMW0
    put object ZCRM_CIC_SEARCH_DISPLAY_NEW in object name
    Now go to change mode
    In the HTML code file delete or comment the following code.
      <TABLE border=1 cellPadding=0 cellSpacing=0 frame=void 
    rules=none  width=100%>
            <TR><TH align=left style="font:bold" width=28%><!--%%
    IBASE_COMPONENT%--> </TH></TR>
            <TR><TH align=left width=28%><NOBR><!--%%COMP_DEVICE_ID%
    --></NOBR> </TH>
              <TD width=72%><NOBR>
                 <INPUT maxLength=19 name=INSTANCE size=25
    maxLength=18 type=TEXT/PLAIN>
                 <INPUT maxLength=40 name=DEVICEID size=25
    maxLength=40 type=TEXT/PLAIN>
                 <INPUT onclick=LISTRELIB() src="S_B_ZOIN.GIF"
    type=image title="<%%DISPLAY_HITLIST3%>">
                 <INPUT onclick=DET_IBASE() src="s_b_detl.gif"
    type=image title="<%%DISPLAY_DETAILS3%>">
              </NOBR></TD></TR>
            <TR><TH align=left  width=28%><NOBR><!%%SHORT_TEXT%
    ></NOBR> </TH>
              <TD width=72%><INPUT readOnly name=DESCR size=40
    maxLength=40 type=TEXT/PLAIN>
              </TD></TR>
            <TR><TH align=left  width=28%><NOBR><!%%PRODUCT_ID%
    ></NOBR> </TH>
              <TD  width=72%><NOBR>
                <INPUT maxLength=40 name=PRODUCT_ID size=25
    type=TEXT/PLAIN>
                <INPUT maxLength=40 name=OBJECT_ID size=25
    type=TEXT/PLAIN>
                <INPUT name=OBJECT_FAMILY size=4 maxLength=4
    type=TEXT/PLAIN></NOBR>
              </TD></TR>
            </TABLE>
    Then save the HTML file.
    in the pop up dialog select the yes option.
    Now go to Customer Relationship Management &#61664;Interaction Center
    WinClient &#61664;Component Configuration &#61664;Visible Components&#61664;Toolbars
    (GUI Status, Active Functions) &#61664;Define Profiles for Search
    Strategies
    double click on NORM and in the HTML for BP search maintain
    ZCRM_CIC_SEARCH_DISPLAY_NEW
    Save.
    VOILA...Now in the CIC screen you can not see IBASE
    <b> <i> IceCube </i> </b>

  • Help with JLabels and JTextFields

    I'm experimenting with JLabels and JTextFields in a basic JFrame. What I am trying to accomplish (without success) is to align a JLabel above and centered on a JTextField. The tutorials are confusing me. Any help would be greatly appreciated. a Sample of code is ...
    JLabel  myTextLabel = new JLabel("Who's text Field?");
    JTextField myTextField = new JTextField("My Text Field");...after reading the tutorial I thought that I needed to assign L&F variables to the JLabel ... i.e.
    JLabel myTextLabel = new JLabel("Who's text field?:", JLabel.CENTER, JLabel.TOP); but this results in an error when compiling. (cannot find symbol), so I thought I need to assign the JLabel to the JTextField. i.e.
    myTextLabel.setLabelFor(myTextField);Then I get "identifier" expected. So now being completely confused I am here asking "How do I?" :)
    Thanks in advance!

    Most likely, you need to think a little more about using a layout manager to hlp you along the way. If memory serves, the default layout manager for a JPanel is FlowLayout and that will simply place the components you add to the panel one after another and allow each to adopt it's preferred size.
    One way to ensure that the two compoenets were sized equally, would be to use the GridLayout layout manager and create either one row with two columns, or two rows with one column on each. Then add the compoennets to each of the 'cells' so to speak and that should ensure that they are both the same size.
    As to making the text centered in each, both the JLabel and JtextField classes have amethod called setHorizontalAlignment(); it can be used to aligh the text as you require.
    Simply create an instance of the class;
    JLabel aLabel = new JLabel("Some Text");
    // Then set the alignment
    aLabel.setHorizontalAlignment(SwingConstants.CENTER);Or, do the whole operation i one step
    JLabel aLabel = new JLabel("Sone Text", SwingConstants.CENTER);and then add the componenet to the panel once you have set the layout manager.
    Remember that the label.textfield will have to be wide enought to make it obvious that the text is centered!

  • Customizing message creation in work center

    Hi all,
    we have to change the layout of the message creation window in work center (Web Dynpro Component: AGS_WORK_INCIDENT_CREATE)
    I've tested the enhancment functionality quite a bit, but i was not able to solve the problem.
    Basically we have to add fields to the layout which correspond to the fields in the support message that should be created.
    Example: The support message (ZLFN) contains a field "approver". This field has to be on the screen when creating a message and the value should transported into the created message.
    Can you please tell me the basic points of how to do that.
    Another way i thought about was linking direct to the blank ZLFN message (coressponding to crmd_order), but i could not find a way to do that. Maybe this is possible?
    Any help would be really appreciated.
    Best Regards
    Daniel

    Hello Daniel,
    Please, check the following link:
    https://websmp105.sap-ag.de/~sapidb/011000358700000601362009E/WORKCENTERCUSTGUIDEVALE_EX.PDF
    I hope that this link can help you.
    Best Regards,
    Diego Fischer,

  • Adding JLabel relative to button

    In the post given below(previous post), what need to be done, if I need to have a JLabel indicating name, exactly under that button.
    It should be something like, the name displayed under an icon
    http://forums.sun.com/thread.jspa?threadID=5322424&tstart=0
    Rony

    >
    It should be something like, the name displayed under an icon >
    import java.awt.*;
    import javax.swing.*;
    import java.net.URL;
    class LabelAlignment {
      public static void main(String[] args) throws Exception {
        final URL url = new URL(
          "http://pscode.org/media/starzoom-thumb.gif");
        Runnable r = new Runnable() {
          public void run() {
            ImageIcon ii = new ImageIcon(url);
            // one layout, that when nested in other layouts,
            // can achieve the appearance of an icon with label
            // centered below it.
            JPanel iconWithLabel = new JPanel( new BorderLayout() );
            iconWithLabel.add(new JLabel(ii), BorderLayout.CENTER);
            JLabel label = new JLabel("Zooming Stars",
              // make sure it is CENTER aligned
              SwingConstants.CENTER);
            iconWithLabel.add(label, BorderLayout.SOUTH);
            JOptionPane.showMessageDialog( null, iconWithLabel );
        EventQueue.invokeLater(r);
    }

  • Problem with JFrame and JPanel

    Okay, well I'm busy doing a lodge management program for a project and I have programmed this JFrame
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class FinalTest extends JFrame
         public JPanel contentPane;
         public JImagePanel imgPanel;
         private JLabel[] cottageIcon;
         private boolean keepMoving;
         private int selectedCottage;
         public FinalTest()
              super();
              initializeComponent();
              addActionListeners();
              this.setVisible(true);
         private void initializeComponent()
              contentPane = (JPanel)getContentPane();
              contentPane.setLayout(null);
              imgPanel = new JImagePanel("back.png");
               imgPanel.setLayout(null);
              imgPanel.setBackground(new Color(1, 0, 0));
                   addComponent(contentPane, imgPanel, 10,10,imgPanel.getImageWidth(),imgPanel.getImageHeight());
              cottageIcon = new JLabel[6];
              keepMoving = true;
              selectedCottage = 0;
              cottageIcon[0] =  new JLabel();
              //This component will never be added or shown, but needs to be there to cover for no cottage selected
              for(int a = 1; a < cottageIcon.length; a++)
                   cottageIcon[a] = new JLabel("C" + (a));
                   cottageIcon[a].setBackground(new Color(255, 0, 0));
                    cottageIcon[a].setHorizontalAlignment(SwingConstants.CENTER);
                    cottageIcon[a].setHorizontalTextPosition(SwingConstants.LEADING);
                    cottageIcon[a].setForeground(new Color(255, 255, 255));
                    cottageIcon[a].setOpaque(true);
                    addComponent(imgPanel,cottageIcon[a],12,(a-1)*35 + 12,30,30);
                this.setTitle("Cottage Chooser");
                this.setLocationRelativeTo(null);
              this.setSize(new Dimension(540, 430));
         private void addActionListeners()
              imgPanel.addMouseListener(new MouseAdapter()
                   public void mousePressed(MouseEvent e)
                        imgPanel_mousePressed(e);
                   public void mouseReleased(MouseEvent e)
                        imgPanel_mouseReleased(e);
                   public void mouseEntered(MouseEvent e)
                        imgPanel_mouseEntered(e);
              imgPanel.addMouseMotionListener(new MouseMotionAdapter()
                   public void mouseDragged(MouseEvent e)
                        imgPanel_mouseDragged(e);
         private void addComponent(Container container,Component c,int x,int y,int width,int height)
              c.setBounds(x,y,width,height);
              container.add(c);
         private void imgPanel_mousePressed(MouseEvent e)
              for(int a = 1; a < cottageIcon.length; a++)
                   if(withinBounds(e.getX(),e.getY(),cottageIcon[a].getBounds()))
                        System.out.println("B" + withinBounds(e.getX(),e.getY(),cottageIcon[a].getBounds()));
                        selectedCottage = a;
                        keepMoving = true;
         private void imgPanel_mouseReleased(MouseEvent e)
              System.out.println("called");
              selectedCottage = 0;
              keepMoving = false;
         private void imgPanel_mouseDragged(MouseEvent e)
               System.out.println("XXX" + Math.random() * 100);
              if(keepMoving)
                   int x = e.getX();
                    int y = e.getY();
                    if(selectedCottage!= 0)
                         cottageIcon[selectedCottage].setBounds(x-(30/2),y-(30/2),30,30);
                    if(!legalBounds(imgPanel,cottageIcon[selectedCottage]))
                        keepMoving = false;
                        cottageIcon[selectedCottage].setBounds(imgPanel.getWidth()/2,imgPanel.getHeight()/2,30,30);
              System.out.println(cottageIcon[selectedCottage].getBounds());
         private void imgPanel_mouseEntered(MouseEvent e)
               System.out.println("entered");
         private void but1_actionPerformed(ActionEvent e)
              String input = JOptionPane.showInputDialog(null,"Enter selected cottage");
              selectedCottage = Integer.parseInt(input) - 1;
         public boolean legalBounds(Component containerComponent, Component subComponent)
              int contWidth = containerComponent.getWidth();
              int contHeight = containerComponent.getHeight();
              int subComponentX = subComponent.getX();
              int subComponentY = subComponent.getY();
              int subComponentWidth = subComponent.getWidth();
              int subComponentHeight = subComponent.getHeight();
              if((subComponentX < 0) || (subComponentY < 0) || (subComponentX > contWidth) || (subComponentY > contHeight))
                   return false;
              return true;
         public boolean withinBounds(int mouseX, int mouseY, Rectangle componentRectangle)
              int componentX = (int)componentRectangle.getX();
              int componentY = (int)componentRectangle.getY();
              int componentHeight = (int)componentRectangle.getHeight();
              int componentWidth = (int)componentRectangle.getWidth();
              if((mouseX >= componentX) && (mouseX <= (componentX + componentWidth)) && (mouseY >= componentY) && (mouseY <= (componentY + componentWidth)))
                   return true;
              return false;
         public static void main(String[] args)
              JFrame.setDefaultLookAndFeelDecorated(true);
              //JDialog.setDefaultLookAndFeelDecorated(true);
              try
                   UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
              catch (Exception ex)
                   System.out.println("Failed loading L&F: ");
                   System.out.println(ex);
              FinalTest ft = new FinalTest();
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Image;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class JImagePanel extends JPanel
      private Image image;
      public JImagePanel(String imgFileName)
           image = new ImageIcon(imgFileName).getImage();
        setLayout(null);
      public void paintComponent(Graphics g)
        g.drawImage(image, 0, 0, null);
      public Dimension getImageSize()
                Dimension size = new Dimension(image.getWidth(null), image.getHeight(null));
             return size;
      public int getImageWidth()
                int width = image.getWidth(null);
                return width;
      public int getImageHeight()
              int height = image.getHeight(null);
              return height;
    }Now the problem I'm having is changing that class to a JFrame, it seems simple but I keep having problems like when it runs from another JFrame nothing pops up. I can do it like this:
    FinalTest ft = new FinalTest();
    ft.setVisible(false);
    JPanel example = ft.contentPanehowever I will probably be marked down on this for bad code. I'm not asking for the work to be done for me, but I'm really stuck on this and just need some pointers so I can carry on with the project. Thanks,
    Steve

    CeciNEstPasUnProgrammeur wrote:
    I'd actually consider your GUI being a JPanel instead of a JFrame quite good design - makes it easy to put the stuff into an applet when necessary...
    Anyway, you should set setVisible() to true to make it appear, not to false. Otherwise, I don't seem to understand your problem.That is actually my problem. I am trying to convert this JFrame to a JPanel

Maybe you are looking for

  • MouseClicked event = enter key doesnt work

    Hello, when I make some JButoon and add to it MouseClicked event (witch handles some code) everything works fine. But when I mark it with TAB then press ENTER button wont "doClick". So I found out that actionPerformed might be the right handler, but

  • How do I backup my iPhoto database?

    I have about 2,500 photos in iPhoto. Although I use Time Machine to backup my entire Mac to an external drive, I'd also like to backup my photos to a DVD just to have a super safe archive copy. When I go to the Picture folder, I see the iPhoto librar

  • BATCH SELECTION DURING ISSUE

    Hi...i have to issue raw material which is in batch in my storage location with charachterstics of expiration date. NoW i have to issue against prodcutionorder. How and where i can see the all batch depends on date at the time of issue. How can i mak

  • I want to purchase a TV show for a season that starts next week, but the new season isn't posted yet, when will it be?

    I know the episodes wil not be available yet, but the option to buy hasn't appeared yet. When do new seasons tend to be come available for purchase? Is it day of, or should it already be there?

  • SSL Server Certificate

    Hi All, I am configuring Maintenance Optimizer in SAP Solution Manager 7.1 SP3. Is it mandatory to have SSL Server Certificate ? And if yes why SSL Server Certificate is needed? And if no can i proceed with the Configuration of Maintenance Optimizer?