Aligning text in a JPanel/JLabel

Hi guyz,
I have two text strings. One needs to be on the left edge and the other needs to be on the right edge. I created two JLabels and added these texts to them. Then, i used a FlowLayout to create a JPanel. But, all the time, they are being centered. I have mentioned the sizes of the labels also. Still, both the texts are being centered side by side. Here is the snippet of code. "increment" is an integer which identifies the Y position. This code is looped through for a particular no. of times.
       String conditionName = "";
       String conditionValue = "";
       conditionName = "<html>"+condition+"</html>";
       conditionValue = "<html>"+condValue+"</html>";
        JLabel conditionLabel = new JLabel();
        conditionLabel.setText(conditionName);
        conditionLabel.setBounds(5,increment,350,20);
        JLabel conditionValueLabel = new JLabel();
        conditionValueLabel.setText(conditionValue);
        conditionValueLabel.setBounds(360,increment,40,20);
        JPanel conditionsPanel = new JPanel();
        conditionsPanel.setBounds(5,increment,400,300);
        conditionsPanel.setLayout(new FlowLayout());
        conditionsPanel.add(conditionLabel);
        conditionsPanel.add(conditionValueLabel);Can anyone help?

Hey Michael_Dunn,
I have one more question. Though, the logic you gave worked, there is a small problem. I am actually looping through a number of times depending on the input list. So, if it is more than 5 times, then i get more than 5 pairs which is good enough to place them in a ScrollPane nicely. Where as if it is 2 or 3, then the whole scroll pane is being divided equally between those to place them which i don't want. I want to increment and place them one below other. That's why i used and increment variable whose initial value is "55". And each increment step is "25". But, it is not working. Can you tell me why? Here is the code i have used.
        JPanel panel = new JPanel(new GridLayout(1,2));
        JPanel p1 = new JPanel(new FlowLayout(FlowLayout.LEFT));
        JPanel p2 = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        p1.setBounds(5,increment,350,20);
        p1.setBounds(360,increment,40,20);
        p1.add(new JLabel("Hello",JLabel.LEFT));
        p2.add(new JLabel("World",JLabel.RIGHT));
        panel.setBounds(5,increment,400,300);
        panel.add(p1);
        panel.add(p2);

Similar Messages

  • JTable text alignment issues when using JPanel as custom TableCellRenderer

    Hi there,
    I'm having some difficulty with text alignment/border issues when using a custom TableCellRenderer. I'm using a JPanel with GroupLayout (although I've also tried others like FlowLayout), and I can't seem to get label text within the JPanel to align properly with the other cells in the table. The text inside my 'panel' cell is shifted downward. If I use the code from the DefaultTableCellRenderer to set the border when the cell receives focus, the problem gets worse as the text shifts when the new border is applied to the panel upon cell selection. Here's an SSCCE to demonstrate:
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.EventQueue;
    import javax.swing.GroupLayout;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTable;
    import javax.swing.border.Border;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableColumn;
    import sun.swing.DefaultLookup;
    public class TableCellPanelTest extends JFrame {
      private class PanelRenderer extends JPanel implements TableCellRenderer {
        private JLabel label = new JLabel();
        public PanelRenderer() {
          GroupLayout layout = new GroupLayout(this);
          layout.setHorizontalGroup(layout.createParallelGroup().addComponent(label));
          layout.setVerticalGroup(layout.createParallelGroup().addComponent(label));
          setLayout(layout);
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
          if (isSelected) {
            setBackground(table.getSelectionBackground());
          } else {
            setBackground(table.getBackground());
          // Border section taken from DefaultTableCellRenderer
          if (hasFocus) {
            Border border = null;
            if (isSelected) {
              border = DefaultLookup.getBorder(this, ui, "Table.focusSelectedCellHighlightBorder");
            if (border == null) {
              border = DefaultLookup.getBorder(this, ui, "Table.focusCellHighlightBorder");
            setBorder(border);
            if (!isSelected && table.isCellEditable(row, column)) {
              Color col;
              col = DefaultLookup.getColor(this, ui, "Table.focusCellForeground");
              if (col != null) {
                super.setForeground(col);
              col = DefaultLookup.getColor(this, ui, "Table.focusCellBackground");
              if (col != null) {
                super.setBackground(col);
          } else {
            setBorder(null /*getNoFocusBorder()*/);
          // Set up our label
          label.setText(value.toString());
          label.setFont(table.getFont());
          return this;
      public TableCellPanelTest() {
        JTable table = new JTable(new Integer[][]{{1, 2, 3}, {4, 5, 6}}, new String[]{"A", "B", "C"});
        // set up a custom renderer on the first column
        TableColumn firstColumn = table.getColumnModel().getColumn(0);
        firstColumn.setCellRenderer(new PanelRenderer());
        getContentPane().add(table);
        pack();
      public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
          public void run() {
            new TableCellPanelTest().setVisible(true);
    }There are basically two problems:
    1) When first run, the text in the custom renderer column is shifted downward slightly.
    2) Once a cell in the column is selected, it shifts down even farther.
    I'd really appreciate any help in figuring out what's up!
    Thanks!

    1) LayoutManagers need to take the border into account so the label is placed at (1,1) while labels just start at (0,0) of the cell rect. Also the layout manager tend not to shrink component below their minimum size. Setting the labels minimum size to (0,0) seems to get the same effect in your example. Doing the same for maximum size helps if you set the row height for the JTable larger. Easier might be to use BorderLayout which ignores min/max for center (and min/max height for west/east, etc).
    2) DefaultTableCellRenderer uses a 1px border if the UI no focus border is null, you don't.
    3) Include a setDefaultCloseOperation is a SSCCE please. I think I've got a hunderd test programs running now :P.

  • Aligning text in JLabel

    Hi all,
    I'm simply trying to align text in a JLabel.
    I've been trying to use HTML formatting inside the JLabel, e.g:
    label = new JLabel (" <HTML><CENTER><P>Line one</P> <P>Line two</P></CENTER> </HTML>" );but when I try to use the <CENTER> tag it seems to be ignored?
    Why?
    How do I get around this?
    Many thanks.

    You can use the following code segment:
    JLabel ab = new JLabel("GG" ,  SwingConstants.CENTER);Hope it helps.
    --DM                                                                                                                                                                                                                                                                       

  • Aligning text in JTextArea

    Hi,
    Does anyone know how to set the point at which text in displayed in a JTextArea using the setText() method. I am trying to align text in the centre of a JTextArea. Is there a way one can find the pixel at the centre of the textarea and then somehow set the cursor point to the centre and to align the string correspondingly?

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class PlacingText {
      static int hInset = 20;
      public static void main(String[] args) {
        String text = "public class JTextPane \n" +
          "extends JEditorPane \n\n " +
          "A text component that can be marked up with attributes that are represented " +
          "graphically. You can find how-to information and examples of using text panes " +
          "in Using Text Components, a section in The Java Tutorial. \n\n" +
          "This component models paragraphs that are composed of runs of character level " +
          "attributes. Each paragraph may have a logical style attached to it which " +
          "contains the default attributes to use if not overridden by attributes set on " +
          "the paragraph or character run. Components and images may be embedded in the " +
          "flow of text.";
        final JTextArea ta = new JTextArea(10,40);
        ta.setMargin(new Insets(10,hInset,10,hInset));
        ta.setLineWrap(true);
        ta.setWrapStyleWord(true);
        ta.setText(text);
        JPanel panel = new JPanel();
        panel.add(new JScrollPane(ta));
        final JButton moreButton = new JButton("more");
        final JButton lessButton = new JButton("less");
        ActionListener l = new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            JButton button = (JButton)e.getSource();
            if(button == moreButton)
              hInset += 10;
            if(button == lessButton)
              hInset -= 10;
            ta.setMargin(new Insets(10,hInset,10,hInset));
            ta.repaint();
        moreButton.addActionListener(l);
        lessButton.addActionListener(l);
        JPanel southPanel = new JPanel();
        southPanel.add(new JLabel("horizontal margin:"));
        southPanel.add(moreButton);
        southPanel.add(lessButton);
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().add(panel);
        f.getContentPane().add(southPanel, "South");
        f.pack();
        f.setLocation(300,300);
        f.setVisible(true);
    }

  • Aligning text in a text area

    Is it possible to align text in a JTextArea?

    also not sure what you're after, but try this
    import javax.swing.*;
    import java.awt.*;
    class Testing extends JFrame
      public Testing()
        setLocation(300,200);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        String[] name = {"joe","christopher","fred","robert","al","josephine","mary"};
        String[] income = {"100","100000","10000","1","88888","50000","200000"};
        JPanel jp = new JPanel();
        JTextArea ta = new JTextArea(20,30);
        JScrollPane sp = new JScrollPane(ta);
        sp.setPreferredSize(new Dimension(175,150));
        jp.add(sp);
        getContentPane().add(jp);
        pack();
        String pad = "                    ";
        ta.setFont(new Font("monospaced",Font.PLAIN,12));//comment out this line to see difference
        for(int x = 0; x < name.length; x++)
          ta.append(name[x]+(pad+income[x]).substring(name[x].length()+income[x].length())+"\n");
      public static void main(String[] args){new Testing().setVisible(true);}
    }

  • How can I align text in Acrobat 8.1 Professional?

    Okay this is quite silly, but seriously how can I align text in adobe acrobat? I could not find a way other than creating a new document file which allows me to use alignment options automatically (example below), however does not allow me that when I reopen the same file (alignment and text options just dissapear on the bars, funny). Help anyone please? =/
    http://img152.imageshack.us/my.php?image=examplemo2.jpg

    Not that silly; but you ideally shouldn't be trying. Although there are some rudimentary (and sometimes unpredictable) editing tools in Acrobat, (I presume you are trying with the TouchUp Object tool as well as the TouchUp Text ?) much better to get it right in the source application and think of the pdf as what it basically is...a print.
    For whatever reason, v5 could edit text positioning rather more easily than the later versions.

  • Problems Aligning Text in Headers and Footers

    I have tried to add headers and footers to documents and the  alignment is wrong.  The center footer/header should be center-aligned  and the right header/footer should be right-aligned.  Unfortunately,  they are both left-aligned.
    The preview shows the headers and footers aligned correctly, but when  the headers/footers are inserted in the document, the alignment reverts  to left aligned, although it is centered and on the right side of the  page, as appropriate.
    This is not a problem in Acrobat 7.
    Please advise if this is a bug and is awaiting an update, or if there is  something that I need to do to fix this problem.
    This is a screen shot of the preview windowindicating the proper alignment as indicated in the ovals:
    Here is the actual document once the header and footer are added.  Notice how the alignment switches to flush left:
    Any guidance is appreciated.
    Thanks.
    - James

    Nope.  The good folks at Adobe have neither addressed this issue (and I have
    heard from others that it is a problem for them as well) nor have they been
    very good about maintaining my account to be able to log in and follow up on
    it.
    The truth of the matter is that it appears to be a glitch in some, but not
    all, versions of this product and clearly it is not a big enough problem for
    them to want to fix it.
    I wind up using Acrobat 7 when I need properly formatted headers and footers
    or ‹ and this ought to get the attention of the folks at Adobe and maybe
    prompt someone (anyone!) to take a look and fix this glitch ‹ you should
    check out PDFPen.  It does much of what Adobe can do including headers and
    footers.
    If I didn't already have Acrobat 7 (and 8 and now 9), I would ditch Acrobat
    and just use Preview or PDFPen.
    - James
    From:  superfluities1 <[email protected]>
    Reply-To:  <[email protected]>
    Date:  Tue, 04 Jan 2011 12:11:19 -0700
    To:  "James A. Sarna, Esq." <[email protected]>
    Subject:  Problems Aligning Text in Headers and Footers
    Anybody ever solve this problem? I just started using(trying too, that is)
    Acrobat Pro for writing letters and starting at the top I ran right into
    this problem. Seems like a deal killer.

  • How to align text at the top and bottom of a cell?

    I'm making a periodic table and need help with aligning text at the top and bottom of a cell. I'll have a picture in the middle of the cell with text above and below the pic. Thank you in advance for any kind of suggestions you can give me.

    It sounds as though you want to have 3 separate items inside of a single cell; text at the top of the cell, text at the bottom of the cell, and then a picture in the middle of the cell.  I am no expert, but to my knowledge that is not possible (someone please correct me if I am wrong.)  I also cannot figure out how to put a picture inside of a cell itself.
    I do have a way to accomplish the end result so long as what you need is the final look and not a useable table in numbers.
    Create 2-3 cells for each element.  (The middle cell, unless you can put pictures in a cell and I don't know, would just be there for peace of mind, but would hold the picture if you can, I would just do two if the pictures are to be in front of the cell anyway.)  The top cell align text to top on the Text tab of the inspector.  The bottom cell, align text to bottom on the same tab.  Then place the picture in the middle.  Now, you have what you want except there is one or two lines dividing the cells.  To get rid of this, either click the middle cell if you have one, or the top or bottom cell.  Click on the Cell tab of the inspector.  Select the bottom border and/or top border button and select "No Border" under border styles.  To make this fast, select a full row at a time, or use command click to select all of the same type of rows (middle, top, or bottom) and change all cells at once.
    I hope this helps.  Best of luck!
    ~Bret

  • How to align text to another text box

    I am very new to Indesign and I am signed up to Lynda.com so watching few a lot of tutorials, that said I need help with aligning text.
    I have a text box that is 100mm across. It has text centered. "£5"
    then above this I have in a smaller font saying "from"
    from
    £5
    I need to get the "f" of from to line up with the beginning of the £ sign? So that If I change the price to £500 the from sticks to the "£" Sign.
    To explain again the from needs to align to the left of the centred text.?
    Hope that make sense?
    Matt

    This can be done by putting the "from" text into a custom positioned anchored object just before the £ sign. You'll need to set the X coordinate relative to the anchor, and adjust the offset on both x and y to get the positioning where you want it.
    I'm sure there are lessons on Anchored Objects on Lynda.com.

  • How to align text(left, right or center) on a button?

    I can not figure out how to align text on a button,
    could someone help me out?
    Thanks in advance

    JButton btn=new JButton("hi");
    btn.setHorizontalAlignment(int i)
    i=0 center
    i=2 left
    i=4 right

  • How to Align Text in the TextArea

    How to Align text in the TextArea. My purpose is that I want to post the records after retrieving from database. All the records in each fields should keep aligned like Oracle WorkSheet.
    I want this way
    Code Name Place City
    a01 nilopher swiss street japan
    a02 rozina lovely street aus
    a03 benazir king's camp pitsburg
    and the out put should not look like this :-
    Code Name Place City
    a01 nilopher swiss street japan
    a02 rozina lovely street aus
    a03 benazir king's camp pitsburg
    here place and city records are getting disturbed accordingly the length of name.

    Well, first off (if it's not default, that is) you must set a monospaced font on the TextArea, unless you want to count pixelwidth of each and every string and then do an estimate on how many fill blanks you want...
    If you have the each string as a line, you use a StringTokenizer on it, extract each token, put all the tokens for that line into an array of strings.
    When every line is done, you compare the length of the nth String of each array and save the highest numbers.
    Then you reassemble each line from the arrays and pad in spaces where the tokens are too short.
    HTH,
    Fredrik

  • Cannot Align text in cell

    Greetings,
    I am having issues when trying to format my spreadsheet.  First of all, I have "Wrap Text in Cell" option turned on.  So when I have text that can fit into the cell, its fine.  But when I have long text in the cell, it wraps the text in the cell so it can fit inside, which I'm fine with.... but for some reason, it is not aligning it in the cell properly, so now part of the text it cut off.  I try to center align the text, but no use. I hit the button for "Align text in the middle of the table cell", and still does not align the text so that its centered, not cut off. I have included an image of what im talking about. Help please?

    Hello
    Here is what I get with Times New Roman under 10.6.8
    May you try to
    quit Pages
    trash the preferences file :
    <startupVolume>:Users:<yourAccount>:Library:Preferences:com.apple.iWork.Pages.pl ist
    restart Pages
    It it changes nothing, try to :
    quit Pages
    trash the preferences file :
    <startupVolume>:Users:<yourAccount>:Library:Caches:com.apple.iWork.fonts
    restart Pages
    Yvan KOENIG (VALLAURIS, France) mercredi 24 août 2011 21:24:52
    iMac 21”5, i7, 2.8 GHz, 4 Gbytes, 1 Tbytes, mac OS X 10.6.8 and 10.7.0
    My iDisk is : <http://public.me.com/koenigyvan>
    Please : Search for questions similar to your own before submitting them to the community
    To be the AW6 successor, iWork MUST integrate a TRUE DB, not a list organizer !

  • Is it possible to use tabs to right align text in Muse, as you can in InDesign?

    Can I use tabs to right align text in Muse, as you can in InDesign?
    I have a beauty treatment followed by a price and I want to right align the price, keeping the treatment on the left of the text box.
    Thank you!

    For what would typically be a two column tab stop layout, I'd generally use inline text frames and the Wrap panel.
    Put the price in it's own text frame. Then cut and paste the text frame BEFORE the item name so it's an inline text frame within the text frame containing the descriptions.Using the Wrap panel set it to float to the right. Then select it and set the right offset so it floats outside the right side of the original text frame.
    Start with this.
    Cut and paste the text frame at the start of the item paragraph.
    Choose the third icon in the Wrap panel to cause the item to float to the right of the text frame.
    Turn off the lock for the 4 wrap offset values.
    Adjust the right offset to a negative value so the item is outside the text frame to the right (to wherever you want it).
    Repeat the same steps above for the other items.
    Note that once it's set up this way you can freely edit the descriptions or change the width of the original text frame and the prices will adjust accordingly. This will also result in things lining up in the browser even if the text layout engine of a specific browser line breaks the text differently.
    This approach is tedious, but the end result will continue to line up as you make changes in Design view and will line up in every browser/OS/device.
    Someday Muse will support tables, which would be the more natural way to achieve this style of layout on the web. Until then, inline items with wrap is usually the best approach for this type of two column layout.

  • Align text between columns with space after paragraphs.

    I am creating a proposal with a ton of text. I used to align everything to a baseline grid with justified type and indented paragraphs. Recently, however, I was asked to change the style to left aligned text with spaces between the paragraphs. The text flows into two columns per page, but I'll be damned if I can get the text to line up. I've tried different baseline grids as well as before and after spacing. I think my issue might be trying to keep paragraph spacing as half the leading. If my copy text leading and baseline are 14 or 7 pt, will a 7 pt paragraph space after work?
    My leading and pt size is below, if anyone can point me to a solution.
    Body copy: 9 pt font/14 pt leadingSpace before/after: 3.5/3.5
    Subheaders: 10 pt font/ 14 pt leadingSpace before/after: 7/3.5
    Baseline: tried both 14 pt and 7 pt

    That's what I thought. I was taught to either have an indented second paragraph or to separate the paragraphs by half the leading of the type. Seems like it's impossible to align the text that way. A full leading separation (14 pt) between paragraphs seems excessive though.

  • Aligning Text in Center of JTextArea

    This is a part of my previous question.
    Is there a way of aligning text, left-center-right in the JTextArea.
    Someone had mentioned JTextPane for aligning Text in the center. What is the code for this?
    Thanks again for your help.

    I'm sorry. I am new at Java so some of these concepts that may be clear to you aren't as obvious to me.
    I inserted the code as you instructed. However, I am not sure if I have to include something else.
    Please advise:
    import javax.swing.*;
    public class HelloClassTwoLine
    public static void main(String args[])
    JTextArea outputTextArea = new JTextArea(); //Create listbox object
    JScrollPane scroll= new JScrollPane(outputTextArea); //create vertical scroll object
    ===> added to original code JTextField textField=new JTextField();
    ===> added to original code textField.setHorizontalAlignment(textField.CENTER);
    outputTextArea.setText("Hello, This is Java 374\n" + //set text in list box
    "This is Java 374 with Ravi");
    JOptionPane.showMessageDialog(null, scroll, //text is argument in JScrollPane object
    "Java Program #2", JOptionPane.INFORMATION_MESSAGE);
    System.exit(0);
    thank you again for your help
    }

Maybe you are looking for

  • I am having problems syncing my iTunes music to iTunes Match. ITunes shuts down after the 2nd step every time. Does anyone know how to fix?

    Every time iTunes Match starts up, it gets to Step 2, almost makes it to Step 3, and then crashes and shuts down iTunes. I've restarted the computer, and reinstalled iTunes for Windows. Anyone have any idea what I should do next? There are songs that

  • Access denied to a security provider on a signed applet

    Hi, I'm having permissions problems to work with a security provider. The security provider is already installed at java.security. In fact, at Netbeans when debbuging the app it's working perfectly. If I'm working the provider in an signed applet, th

  • Y510P Flickering screen still after two repair jobs

    Hello, The screen on my y510p began flickering severely just a few months after I purchased it.  The flicker is present on the right third of the screen, and happens on BIOS boot as well as in Windows 8 and ubuntu.  Here is a video of the flicker:  h

  • Tolerance limit -Payment

    hi We are setting configuration for electronic bank statement inbound file.When forex payments are made..due to change in exchange rate there is forex difference.We wanted to set tolerance group so that the difference to some extent will allowed and

  • How to hide the Slidelite close button [X]

    I'm using Captivate 4. I would like to know how to hide this ugly close button [X] when a slidlet is displayed on a slide ? I understand that this is usefull when the option Stick Slidelet is selected but i think the [X] makes little sens otherwise.