Center the JLabels in a GridLayout

Hi!
I do have one problem: I want two JLabel objects to be centered in a JPane (with GridLayout).
How do I do this? Do I have to use a different layout, and if so wich one?
JPanel jilettersPanel = new JPanel();
          jilettersPanel.setBackground(color);
          jilettersPanel.setLayout( new GridLayout(2,0) );
// Doesn't work the way I expect -----------------------------------------------------------------
          jilettersPanel.setAlignmentX(JComponent.CENTER_ALIGNMENT);
          JLabel jiletters = new JLabel("JILetters - help children learn the alphabet");
          jiletters.setFont( new Font("Arial", Font.BOLD, 16) );
          //The version
          JLabel version = new JLabel();
          version.setText( getVersion() );
          version.setFont( new Font("sans serif", Font.BOLD, 16) );
          jilettersPanel.add(jiletters);
          jilettersPanel.add(version);
          aboutPanel.add(jilettersPanel);
Thanks in advance

Are you trying to center the two JLabels in the same place in the center of the pane (on top of each other) or center them in two consecutive grid locations in a grid layout?
Can you briefly describe what you are getting and how it's different from what you want to get?

Similar Messages

  • How to center the text in JLabel without image?

    I need to center the text inside JLabel, how do i do it?
    Also I need some advise, what is the best way to mark a clicked card (I'm making a card game)?

    I found this method that controls that text alignment:you can try few more:
    label.setVerticalAlignment(JLabel.CENTER);    //these two would  center the label contents
    label.setHorizontalAlignment(JLabel.CENTER);
    label.setHorizontalTextPosition(JLabel.CENTER);Thanks!

  • How to align the JLabel to the center

    Hi,
    I made a JFrame and a JLabel, I want to put the JLabel to the center of the North position. But it doesn't work, it's just placed in the upper left corner. I tried to use html code, such as:
    JLabel l = new JLabel("<html><h1><center>Hello</h1></html>");
    And then put it in the JFrame's north position, but it doesn't work either. What should I do?
    Thx
    Adrian

    Oh, sorry,
    I just found out the function on how to align it to the center, it's
    JLable.setHorizontalAlignment(JLabel.CENTER);
    Please forget about this question.

  • How do i center the text of a JLabel?

    How do i center the text of a JLabel?

    http://java.sun.com/j2se/1.4/docs/api/javax/swing/JLabel.html#setHorizontalTextPosition(int)

  • How to center the text displayed in a JList

    Hi,
    The width of the JList display area is wider than the text displayed. I tried to center the text displayed to make it look nicer. I had tried using "setAlignmentX(Component.CENTER_ALIGNMENT)" in my own ListCellRenderer class but did not work. Any idea how to center the text?
    Fai.

    Yes, I am using JLabels in my renderer and the following is the code:
    public class MyCellRenderer extends JLabel implements ListCellRenderer {
         private static final Color HIGHLIGHT_COLOR = new Color(0, 0, 128);
         public MyCellRenderer() {
              setOpaque(true);
              setIconTextGap(12);
         public Component getListCellRendererComponent(
              JList list,
              Object value,
              int index,
              boolean isSelected,
              boolean cellHasFocus)
              String entry = (String)value;
              setText(entry);
              setFont(new Font("Ariel", Font.BOLD, 18));
              setAlignmentX(Component.CENTER_ALIGNMENT);
              if(isSelected) {
                   setBackground(HIGHLIGHT_COLOR);
                   setForeground(Color.white);
              } else {
                   setBackground(Color.white);
                   setForeground(Color.black);
              return this;
    Can you point out where to implement the centering logic?
    Thanks,
    Fai.

  • Can anyone help in resizing the JLabel object

    Hi,
    can anyone help me in resizing the JLabel object after being dropped onto the DropContainer. I'm providing the code below
    import javax.swing.*;
    import java.awt.*;
    import java.awt.datatransfer.DataFlavor;
    import java.awt.datatransfer.Transferable;
    import java.awt.datatransfer.UnsupportedFlavorException;
    import java.awt.dnd.*;
    import java.io.File;
    import java.io.Serializable;
    import java.awt.event.*;
    import java.awt.Insets;
    import java.awt.Dimension;
    public class project2 extends JApplet implements Runnable{
    private DragContainer dragcontainer;
    private DropContainer dropcontainer;
    private DefaultListModel listModel,listModel1;
    public void start() {
    Thread kicker = new Thread(this);
    kicker.start();
    public void run() {
    project2 dndapplet = new project2();
    dndapplet.init();
    public void init() {
    try {
    getContentPane().setLayout(new BorderLayout());
    listModel = new DefaultListModel();
    dragcontainer = new DragContainer(listModel);
    getContentPane().add(BorderLayout.WEST, new JScrollPane(dragcontainer));
    listModel1=new DefaultListModel();
    dropcontainer = new DropContainer(listModel1);
    getContentPane().add(BorderLayout.CENTER,new JScrollPane(dropcontainer));
    catch (Exception e) {
    System.out.println("error");
    fillUpList("images");
    setSize(700, 300);
    public static void main(String[] args) {
    Frame f = new Frame("dndframe");
    project2 dndapplet = new project2();
    //Point pos=new Point();
    f.add(dndapplet);
    dndapplet.init();
    dndapplet.start();
    f.show();
    private void fillUpList(String directory) {
    File dir = new File(directory);
    File[] files = dir.listFiles();
    for (int i = 0; i < 11; i++) {
    listModel.addElement(new ImageIcon(directory + "\\" + files.getName()));
    class Cursor extends Object implements Serializable
    public static final int SE_RESIZE_CURSOR=0;
    int cursor;
    public Cursor(int SE_RESIZE_CURSOR)
    cursor=SE_RESIZE_CURSOR;
    class ImageTransferable implements Transferable, Serializable
    ImageIcon imageIcon;
    public static final DataFlavor IMAGE_FLAVOR = DataFlavor.imageFlavor;
    public DataFlavor[] getTransferDataFlavors()
    return new DataFlavor[] {IMAGE_FLAVOR};
    public ImageTransferable(ImageIcon imageIcon)
    this.imageIcon = imageIcon;
    public Object getTransferData(DataFlavor f) throws UnsupportedFlavorException
    if (!isDataFlavorSupported(f))
    throw new UnsupportedFlavorException(f);
    return imageIcon;
    public boolean isDataFlavorSupported(DataFlavor aFlavor)
    return IMAGE_FLAVOR.equals(aFlavor);
    class DragContainer extends JList implements DragGestureListener, DragSourceListener
    private DragSource iDragSource = null;
    public DragContainer(ListModel lm)
    super(lm);
    iDragSource = new DragSource();
    iDragSource.createDefaultDragGestureRecognizer(this,DnDConstants.ACTION_COPY_OR_MOVE, this);
    public void dragGestureRecognized(DragGestureEvent aEvt)
    ImageIcon imageSelected = (ImageIcon) getSelectedValue();
    ImageTransferable imsel = new ImageTransferable(imageSelected);
    if (imageSelected != null)
    System.out.println("startdrag...");
    iDragSource.startDrag(aEvt, DragSource.DefaultCopyNoDrop, imsel, this);
    else
    System.out.println("Nothing Selected");
    public void dropActionChanged(DropTargetDragEvent event)
    public void dropActionChanged(DragSourceDragEvent event)
    public void dragDropEnd(DragSourceDropEvent event)
    public void dragEnter(DragSourceDragEvent event)
    public void dragExit(DragSourceEvent event)
    public void dragOver(DragSourceDragEvent event)
    DragSourceContext context = event.getDragSourceContext();
    context.setCursor(null);
    context.setCursor(DragSource.DefaultCopyDrop);
    class DropContainer extends JList implements DropTargetListener,MouseListener
    private DropTarget iDropTarget = null;
    private int acceptableActions = DnDConstants.ACTION_COPY_OR_MOVE;
    JLabel imgLabel=null;
    public int dropX;
    public int dropY;
    public int x;
    public int y;
    public DropContainer(ListModel lm1)
    super(lm1);
    iDropTarget = new DropTarget(this, this);
    setBackground(Color.white);
    public void drop(DropTargetDropEvent aEvt)
    Point location=null;
    ImageIcon icon=null;
    Transferable transferable=null;
    //int dropX=0;
    //int dropY=0;
    try
    transferable = aEvt.getTransferable();
    location=new Point();
    if(transferable.isDataFlavorSupported(ImageTransferable.IMAGE_FLAVOR))
    aEvt.acceptDrop(acceptableActions);
    icon = (ImageIcon)
    transferable.getTransferData(ImageTransferable.IMAGE_FLAVOR);
    setLayout(null);
    imgLabel=new JLabel();
    imgLabel.setIcon(icon);
    imgLabel.addMouseListener(this);
    location=aEvt.getLocation();
    dropX=location.x;
    dropY=location.y;
    imgLabel.setBounds(dropX,dropY,icon.getIconWidth(),icon.getIconHeight());
    this.add(imgLabel);
    SwingUtilities.updateComponentTreeUI(this.getRootPane());
    aEvt.getDropTargetContext().dropComplete(true);
    else
    System.out.println("rejecting drop");
    aEvt.rejectDrop();
    aEvt.getDropTargetContext().dropComplete(false);
    catch (Exception exc)
    exc.printStackTrace();
    aEvt.rejectDrop();
    aEvt.getDropTargetContext().dropComplete(false);
    finally
    location=null;
    transferable=null;
    icon=null;
    imgLabel=null;
    public void mousePressed(MouseEvent e)
    x=e.getX();
    y=e.getY();
    public void mouseReleased(MouseEvent e)
    int temp1,temp2;
    temp1=y;
    temp2=x;
    imgLabel.setSize(temp1,temp2);
    public void mouseEntered(MouseEvent e) {}
    public void mouseExited(MouseEvent e) {}
    public void mouseClicked(MouseEvent e) {}
    public void dragEnter(DropTargetDragEvent event)
    System.out.println("dragenter");
    event.acceptDrag(acceptableActions);
    public void dragExit(DropTargetEvent event)
    System.out.println("dragexit");
    public void dragOver(DropTargetDragEvent event)
    System.out.println("dragover");
    event.acceptDrag(acceptableActions);
    public void dropActionChanged(DropTargetDragEvent event)
    System.out.println("dropactionchanged");
    event.acceptDrag(acceptableActions);
    }//class DropContainer

    Hi all,
    I have two classes, say 1st and 2nd.
    I have created an object of the second class in the first class and also i have invoked a method of the second class using it's object from the first class.
    but when i compile the first class i'm getting an error that "cannot access the second class".
    can anyone help me in fixing this problem
    thanks in advance
    murali

  • Images in the full screen lightbox are not centered horizontally on the screen. Is there a way to center the images?

    I have tried it in different screen sizes but teh result is all same. Horizontally images are slightly on the right. How can I center the images?

    Hi,
    Thanks for your answer. It is ok when using the lightbox without full screen option. When I use the fullscreen option, the container of the image is centered but the image in the container is not. I do center everything but when it comes to full scren there is nothing like centering.
    Here is what happens when I view in the browser:

  • How to center the content of GridViewColumn in code behind?

    Hi all,
    This seems pretty simple to do in xml but I can find a way to do this in code. I'm using this to write to a FixedPage in an xps document and I need the content of the columns centered. Is this even possible?
    Thanks
    ListView myListView = new ListView();
    GridView myGridView = new GridView();
    GridViewColumn gvc1 = new GridViewColumn();
    gvc1.DisplayMemberBinding = new Binding("FirstName");
    gvc1.Header = "First Name";
    gvc1.Width = 100;
    // I need to center the column content!
    myGridView.Columns.Add(gvc1);
    List<DataItem1> xcv = new List<DataItem1>(5);
    xcv.Add(new DataItem1 { FirstName = "John" });
    myListView.ItemsSource = xcv;
    myListView.View = myGridView;

    Just create an ListViewItem style with the HorizontalContentAlignment property set to Center and set the ItemContainerStyle property of the ListView to this one:
    ListView myListView = new ListView();
    ListViewItem lbi = new ListViewItem();
    Style ics = new Style(typeof(ListViewItem));
    ics.Setters.Add(new Setter(ListViewItem.HorizontalContentAlignmentProperty, System.Windows.HorizontalAlignment.Center));
    myListView.ItemContainerStyle = ics;
    GridView myGridView = new GridView();
    GridViewColumn gvc1 = new GridViewColumn();
    gvc1.DisplayMemberBinding = new Binding("FirstName");
    gvc1.Header = "First Name";
    gvc1.Width = 100;
    myGridView.Columns.Add(gvc1);
    List<DataItem1> xcv = new List<DataItem1>(5);
    xcv.Add(new DataItem1 { FirstName = "John" });
    myListView.ItemsSource = xcv;
    myListView.View = myGridView;
    Please remember to close your threads by marking helpful posts as answer and then start a new thread if you have a new question. Please don't ask several questions in the same thread.

  • Why my epson 3800pro doesn't center the print

    Hi,
    I have a interesting and very annoying problem. Why my epson 3800 doesn't center the prints on the paper anymore?
    Using this printer for more than two years now and all of the sudden regardless the paper size and the settings the i
    mages are centerd for an 8 1/2 x 11 ratio. Spent nearly 2 hours on the phone talking to Epson support repairing
    disk permission, uninstalling and reinstalling the printer, reconfiguring and so fort. Still, every print is off center.
    In the printer dialog everything seems fine; when seting up the printer and paper size the image on the screen
    adjust's accordingly but the print still comes out wrong. The technician on the phone suggested - maybe just wanted
    to get rid of me - that it's something to do with Photoshop.
    Anybody has  an idea what could be wrong?
    Thanks, Janos

    monkeyfighterz wrote:
    Anyhow, here are the images in question. As you can see from the settings am about to print on a Canson 11x14 paper.
    Which paper is it? I did a search on the Canson range and could not find an 11x14 paper. The closest I could find is 11x17, like the other paper makers. Did you cut the paper down to 11x14 yourself? If so, Tai Lao has a good question about whether the measurement dimensions of the cut paper are correct, it would be good to double-check.
    monkeyfighterz wrote:
    It made me think if there is a paper sensor (is there such thing?) in the printer not functioning?
    There is a paper sensor in the 3800 (I use a 3800 too, with no problems centering). The paper sensor is optical, and can be misled by existing ink on the paper. Especially black. Is your paper blank, or something already printed on it? If your paper is already printed with a significant dark area near the edge, the sensor might assume that the paper doesn't actually begin until it finds white. If this causes the printer to change where the print head starts on the paper, this can cause alignment problems.
    Tai Lao wrote:
    "Canson" (Canon?) paper
    I'm assuming it's Canson. Canson is one of the traditional European paper makers who have adapted some of their fine art papers for modern inkjet printing. Their product line has been around for about half a millenium.

  • Center the cursor on the Waveform Graph?

    I have a waveform graph where the user can adjust the scale on both the X and Y axes.  The "problem" that I am having is that if the scale's range is set too far from where the cursor is at, the cursor will be off screen and not selectable.  So, I am trying to center the cursor to the scale when the scale is changed or via a button.  Here is the code that I have written for one of the Cursor plots:
    Select Case setBlueCursor
    Case 1
    blueCursorPt.Plot = plotInlineTorque
    inlineTorqueMax = yAxisInlineTorque.Range.Maximum
    inlineTorqueMin = yAxisInlineTorque.Range.Minimum
    blueCursorStartY = (inlineTorqueMax + inlineTorqueMin) / 2
    blueCursorStartX = (XAxis.Range.Maximum + XAxis.Range.Minimum) / 2
    blueCursorPt.YPosition = blueCursorStartY
    blueCursorPt.XPosition = blueCursorStartX
     This code will center the cursor like I want but then I can't move the cursor after that as it is "stuck" at the position that I have coded it.  The problem appears to be with the last two lines of code here.   I do not know of any other way to do this though.  I have tried the "moveCursor" method but the end result ends the same way, with the cursor stuck in the center and can't move.  Any help on a solution?  Is there a better, easier way to do this?  I'm new to Measurement Studio and .NET. 
    Thank you

    This code works.  It appears that I was calling the subroutine that this code is located in over and over in another part of my program. 

  • Center the component without resize in JPanel

    Hi, I have a JPanel in a JFrame. I put in this JPanel objects that extends from a JPanel. It works all ok, but I want to center the components that I include. I use the BorderLayout.CENTER , but the components automaticly have resize it and this is verry bad.
    How can I make the center position of the components witchout to resize it?
    Thanks verry much!
    Nikolay

    BoxLayout is good. We use that almost exclusively for our GUI layouts.
    To centre both horizontally and vertically you can do this:panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS);
    panel.add(Box.createGlue());
    panel.add(component);
    panel.add(Box.createGlue());Regards,
    Tim

  • Qosmio x500 and media center - the mouse arrow disappears

    When opening media center the mouse arrow disappears and makes media center impossible to use, my computer is only a few weeks old and everything else works great
    Can anyone help ?

    Hi
    This is not a problem!
    This is a feature of Media Center!!!
    All features and buttons in Windows Media Center are accessible to you by using the keyboard *only*
    Check this!
    http://windows.microsoft.com/en-US/windows-vista/Windows-Media-Center-keyboard-shortcuts
    Greets

  • Center the box

    Hi,
    I wanna center the panelBox within the page. Any advice?
    <?xml version='1.0' encoding='UTF-8'?>
    <jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.1"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:af="http://xmlns.oracle.com/adf/faces/rich">
    <jsp:directive.page contentType="text/html;charset=UTF-8"/>
    <f:view>
    <af:document id="d1" binding="#{backingBeanScope.backing_my.d1}">
    <af:form id="f1" binding="#{backingBeanScope.backing_my.f1}">
    <af:spacer width="100" height="10" id="s4"/>
    <af:panelStretchLayout id="psl1"
    binding="#{backingBeanScope.backing_my.psl1}"
    startWidth="150px" endWidth="150px"
    topHeight="300px" bottomHeight="150px">
    <f:facet name="top"></f:facet>
    <f:facet name="center">
    <af:panelBox text="Login"
    binding="#{backingBeanScope.backing_my.pb1}"
    id="pb1" inlineStyle="background-color:#649374;"
    showHeader="always">
    </af:panelBox>
    <!-- id="af_one_column_stretched" -->
    </f:facet>
    <f:facet name="start">
    <af:inlineFrame id="if7"/>
    </f:facet>
    <f:facet name="end">
    <af:inlineFrame id="if6"/>
    </f:facet>
    <f:facet name="bottom">
    <af:inlineFrame id="if3"/>
    </f:facet>
    </af:panelStretchLayout>
    </af:form>
    </af:document>
    </f:view>
    <!--oracle-jdev-comment:auto-binding-backing-bean-name:backing_my-->
    </jsp:root>

    Hi,
    To which component dou you want to set background image check following samples
    1)back ground image <af:panelStretchLayout
    <?xml version='1.0' encoding='UTF-8'?>
    <jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.1"
              xmlns:f="http://java.sun.com/jsf/core"
              xmlns:h="http://java.sun.com/jsf/html"
              xmlns:af="http://xmlns.oracle.com/adf/faces/rich">
      <jsp:directive.page contentType="text/html;charset=UTF-8"/>
      <f:view>
        <af:document id="d1" >
          <af:form id="f1" >
            <af:panelStretchLayout id="psl1"
                                   inlineStyle="background-image: url(images/sky_c.jpg)"
                                   startWidth="404px" endWidth="510px"
                                   topHeight="301px" bottomHeight="287px">
              <f:facet name="top">
                <af:inlineFrame id="if1"/>
              </f:facet>
              <f:facet name="center">
                <af:panelBox text="Login"
                             inlineStyle="background-color:#649374;"
                             showHeader="always">...</af:panelBox>
                <!-- id="af_one_column_stretched" -->
              </f:facet>
              <f:facet name="start">
                <af:inlineFrame id="if7"/>
              </f:facet>
              <f:facet name="end">
                <af:inlineFrame id="if6"/>
              </f:facet>
              <f:facet name="bottom">
                <af:inlineFrame id="if3"/>
              </f:facet>
            </af:panelStretchLayout>
          </af:form>
        </af:document>
      </f:view>
      <!--oracle-jdev-comment:auto-binding-backing-bean-name:backing_my-->
    </jsp:root>2)back ground image for panel box
    Note:To appear back ground image set disclosed="false" for PanelBox
    <?xml version='1.0' encoding='UTF-8'?>
    <jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.1"
              xmlns:f="http://java.sun.com/jsf/core"
              xmlns:h="http://java.sun.com/jsf/html"
              xmlns:af="http://xmlns.oracle.com/adf/faces/rich">
      <jsp:directive.page contentType="text/html;charset=UTF-8"/>
      <f:view>
        <af:document id="d1" >
          <af:form id="f1" >
            <af:panelStretchLayout id="psl1"
                                   startWidth="404px" endWidth="510px"
                                   topHeight="301px" bottomHeight="287px">
              <f:facet name="top">
                <af:inlineFrame id="if1"/>
              </f:facet>
              <f:facet name="center">
                <af:panelBox text="Login" disclosed="false"
                             inlineStyle="background-color:#649374;background-image: url(images/sky_c.jpg)"
                             showHeader="always">...</af:panelBox>
                <!-- id="af_one_column_stretched" -->
              </f:facet>
              <f:facet name="start">
                <af:inlineFrame id="if7"/>
              </f:facet>
              <f:facet name="end">
                <af:inlineFrame id="if6"/>
              </f:facet>
              <f:facet name="bottom">
                <af:inlineFrame id="if3"/>
              </f:facet>
            </af:panelStretchLayout>
          </af:form>
        </af:document>
      </f:view>
      <!--oracle-jdev-comment:auto-binding-backing-bean-name:backing_my-->
    </jsp:root>-Suresh

  • [SOLVED] How to center the splash background image

    Hi,
    My question is about the Frank Nimphius code example:
    http://www.oracle.com/technology/products/jdev/tips/fnimphius/custom_splash_screen/index.html
    It's really a great-easy-usefull article ;)
    It works very well, but I can't center the imatge of splash (not the progress bar, just splash image). I try with text-align, position, etc. css properties, without luck.
    Can anybody help me, please?
    JVN

    Hi Simon,
    Using firebug I can solve the problem. I change the value of 'top' and 'left' attributes of 'af|document::splash-screen-content' and now it appears centered :)
    Thanks!
    JVN
    P.S: using a css class, like 'af|document.globalDocument::splash-screen' and then in jspx page: '<af:document styleClass="globalDocument">', it doesn't work.

  • Regarding resizing the JLabel dynamically

    hi all, again, some question in JLabel
    i have created an simple applet which have many JLabel on it, my question are:
    1. those JLabel just can't show on the applet, where i have set the location and the text on it, but still...can't
    2. how can i dynamically set the location where the JLabel should located at? i mean, the JLabel should follow exactly just in a straight row like below
    Jlabel1 - Jlabel2 - Jlabel3 -... JlabelN
    thank you for reply

    hi, i have done the creation of Jlabel and have the layout of NULL, because i have to fit the Jlabel into a larger panel in only 1 single row, no choice but have to use NULL. but the real problem is that the display of Jlabel just won't show, i have to manually set the length by using Jlabel.setSize(..., ...), why? isn't any other way to resize and make it fit the character in the Jlabel? how?

Maybe you are looking for

  • Changing the Today highlight color

    I was wondering if there is a way to change that color. Today is highlighted with a very faint blue, and for a person with bad color blindness it's very difficult to see and tell apart from the rest of the white boxes of the dates around. So i can't

  • Information about configuration parameters

    Does anybody know where to find information about these parameters in SXMB_ADM - Integration Engine Configuration? - BPE - DISPATCHER - MIN_DURATION_PROCESSING - BPE - DISPATCHER - PACKAGES_PER_COMMIT Thanks!

  • 1gb file problems

    Can someone please explain why the aebs with the hard drive plugged in cannot handle files larger than 1gb?? I've seen many people comment on this, and it really blows. I've got a drive formatted hfs+, so the max file size should be something like 16

  • Problems since upgrading to Mavericks

    I am experiencing problems with CC applications since upgrading to Mavericks. Mostly Screen and display issues. In Photoshop, the top menu bar where the red, yellow , green window buttons normally sit has disappeared and it seems I cannot drag the wi

  • Trouble with Photoshop CS.5.1 activation

    A few weeks ago I installed my old copy of Photoshop CS5.1 onto my new computer, entered in my code and it was working just fine. Then on Saturday it stopped working, saying it needed to be "activated". Every time I tried to get it to activate itself