Right justify AWT.TextField

Hey,
Can anybody tell me how to right justify text in an awt.texfield?
I know I need to override the paint() method using FontMetrics Class and calculate the new position.
But how does it work efficiently and how do I need to clear the field and set the Cursor etc.
(Bonus answer could be, how does it work in comparison to swing/jfc :-), are there already functions to do this?)
Thanks, Marc
I tried something like this, but it looks pretty ugly...
public class TFieldTest extends Frame{
static TextField t2;
// do something
public static void main(String args[]) {
// create Frame and App here
TextField t2 = new TextField() {
public void paint(Graphics g) {
//super.paint(g);
Font font = TFieldTest.t2.getFont();
FontMetrics fm = FieldTest.t2.getFontMetrics(font);
Dimension size = this.getSize();
int width = fm.stringWidthTFieldTest.t2.getText());
g.setFont(font);
g.drawString(TFieldTest.t2.getText(),size.width-width,fm.getAscent());
System.out.println("Overwritten Paint in TextField t2 - right justyfied");
// do more
}

Well for purpose, I had 4 textfields that would show the subtotal, taxs, and grandtotal, that had to be aligned right.
So I use label, and used the Constructor Label(String text, int alignment).
ex:
Label lPrix01 = new Label ("", Label.RIGHT);
lTrans.setBounds(609,387,90,25);
Then with paint I simply drew lines, to have the effect of a textfield
g.setColor(white);
g.drawLine(609,412,699,412);      //hor          Label transport
g.drawLine(699,387,699,411);      //Ver          Label transport
g.setColor(noir);
g.drawLine(609,385,699,385);     //hor          Label transport
g.drawLine(608,387,608,412);     //Ver          Label transport

Similar Messages

  • Left- and right-justifying with dot leaders in JLabel and JButton

    Hi,
    I am developing checklists using JLabel and JButton components and want to finish up with the text in each component looking something like the following (each line is a separate button/label):
    ACTION No1............................RESPONSE No1
    ACTION No2............................RESPONSE No2
    ACTION No3............................RESPONSE No3
    The idea is to have the �Action� text left-justified and the �Response� text right-justified with dot-leaders as shown.
    Each text line will be put into its own fixed length label or button.
    I plan to construct a string from text blocks �ACTION No1� and �RESPONSE No1� and add the calculated, exact no of dots in between to fill the space.
    The text font can be fixed (e.g. Courier) or proportional (e.g. Arial).
    My question is how to calculate the number of dots to add to fill the space for different fonts and font sizes.
    I think that using FontMetrics could provide some help but am not sure how this would work.
    Can anyone help.
    Many tks
    John

    Hi,
    I've developed your suggested code further to enable selected JLabels to be toggled visible(true/false) by pressing a JButton.
    I'd like however that when a label is made invisible that the rest of the labels/buttons move up to fill the space left by the now invisible label and vice versa.
    How do I do this, can you enlighten me on a solution?
    Modified code included below. Not very elegant but serves to illustrate the point in question and only makes the label invisible.
    Many tks
    John
    package componentwierd;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class ComponentWierd extends JFrame implements ComponentListener, ActionListener {
        boolean isVisible = true;
        JLabel label2 = new JLabel();
        public ComponentWierd() {
            getContentPane().setLayout( new GridLayout(0, 1) );
            // Using my original suggestion
            JLabel label = new JLabel();
            label.setLayout(new BorderLayout());
            label.add(createWierdComponent());
            getContentPane().add(label);
            JButton button = new JButton();
            button.setLayout(new BorderLayout());
            button.add(createWierdComponent());
            button.addActionListener(this);
            getContentPane().add(button);
            // Using Font Metrics
            // JLabel label2 = new JLabel("Label2 West...Label2 East");
            label2.setText("Label2 West...Label2 East");
            label2.addComponentListener( this );
            getContentPane().add(label2);
            JButton button2 = new JButton("Button2 West...Button2 East");
            System.out.println(button2.getIconTextGap());
            button2.addComponentListener( this );
            button2.setVisible(true);
            getContentPane().add(button2);
        public void actionPerformed(ActionEvent e) {
            if (isVisible == true) {
                isVisible = false;
                label2.setVisible(false);
            } else if (isVisible == false) {
                isVisible = true;
                label2.setVisible(true);
        private JComponent createWierdComponent() {
            JPanel panel = new JPanel(new BorderLayout());
            panel.setOpaque( false );
            panel.add(new JLabel("Label WEST"), BorderLayout.WEST);
            panel.add(new JLabel("..............................................."));
            panel.add(new JLabel("Label EAST"), BorderLayout.EAST);
            return panel;
        public void componentResized(ComponentEvent e) {
            if (e.getComponent() instanceof JLabel) {
                JLabel component = (JLabel)e.getComponent();
                String text = component.getText();
                String fitText = fitText(component, text);
                component.setText( fitText );
            if (e.getComponent() instanceof JButton) {
                JButton component = (JButton)e.getComponent();
                String text = component.getText();
                String fitText = fitText(component, text);
                component.setText( fitText );
        private String fitText(JComponent component, String text) {
            // Calculate the total width for painting the text
            // (Not sure why I need the -8)
            Insets insets = component.getInsets();
            int availableWidth = getWidth() - insets.left - insets.right - 8;
            // Calculate the minimum width our text will take
            String start = text.substring(0, text.indexOf("."));
            String middle = "...";
            String end = text.substring(text.lastIndexOf(".") + 1);
            FontMetrics fm = getFontMetrics( component.getFont() );
            int startWidth = fm.stringWidth( start );
            int middleWidth = fm.stringWidth( middle );
            int endWidth = fm.stringWidth( end );
            int minimumWidth = startWidth + middleWidth + endWidth;
            // Add dots to fill out the extra space
            StringBuffer buffer = new StringBuffer(start);
            buffer.append(middle);
            if (minimumWidth < availableWidth) {
                String dot = ".";
                int dotWidth = fm.stringWidth( dot );
                int dots = (availableWidth - minimumWidth) / dotWidth;
                for (int i = 0; i < dots; i++) {
                    buffer.append( dot );
            buffer.append(end);
            String result = buffer.toString();
            return result;
        public void componentHidden(ComponentEvent e) {}
        public void componentMoved(ComponentEvent e) {}
        public void componentShown(ComponentEvent e) {}
        public static void main(String[] args) {
            ComponentWierd frame = new ComponentWierd();
            frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
            frame.setSize(200, 200);
            frame.setLocationRelativeTo( null );
            frame.setVisible(true);
    }

  • Using Right-justified and left zero-filled condition in message mapping of

    Hi,
    My Interface is outbound Interface.
    Suppose source field named 'MobNumber' is mapped with Target field named 'MobileNumber'.Condition is AS IS(Right-justified and left zero-filled).
    How should i do this mapping?
    Thanks,
    Sanghamitra

    Hi Sanghamitra,
         Similar question ahs been answered earlier in this thread
    Re: Message Mapping using Left justified, right blank/space filled
    just replace the filler variable by zero in my post
    One small request, if you think your questions are being answered correctly and properly, please kindly, if possible, close down the threads. This way forum members/users  who later look up for solutions to similar problem, they know for sure that the problem was finally solved, with the solutions provided in the thread.   
    regards
    Anupam
    Edited by: anupamsap on Aug 3, 2011 11:27 AM

  • Cursor Doesn't display in numeric right justified fields

    We have an aplication that we deployed at a client. Normally the cursor blinks in the field that has focus. However, at this particular client the cursor doesn't show on numeric fields that are right justified. The user can type in the values though. Please help.
    Alok

    Hello,
    Maybe you can increase the width of field.
    Regards,
    George
    We have an aplication that we deployed at a client. Normally the cursor blinks in the field that has focus. However, at this particular client the cursor doesn't show on numeric fields that are right justified. The user can type in the values though. Please help.
    Alok

  • FW: Caret Location Right Justified for LI when using HTMLEditorKit

    It appears that when using the HTMLEditorKit and inserting any sort of list
    item (ordered list or unordered list) into a view (while in edit mode), the
    caret is initially *---------| right justified with respect to the bullet
    image. If the identical html is loaded all at once however the caret is *-|
    left justified with respect to the bullet image. Is this a bug in
    HTMLEditorKit?

    Sure it is. In this special case IBM's JDK does a better job (at least under Linux).
    Generally I'm totally disappointed by the whole HTML package. I've been trying to implement a really primitive WYSIWIG-HTML-editor which understands <p>, <ul>, <h1> <b>, <i> and <a href>. It is a nightmare!
    - Dynamically modifying the document's structure (e.g., by making a <li> out of a <p>) works more or less, but you have absolutely no control over caret movement, and different JDK's make it differently!
    - The HTMLDocument inserts crude "extra-tags" (e.g., those <p-implied>'s. You never know exactly the structure of your document, and after a long debugging session you notice that the HTMLDocument was bluntly inserting yet another artificial element you did not specify. No docs at all what's going on.
    - It is nearly unbelievable how complicated so simple things like
    are internally modelled.
    - Frankly spoken: The whole document model sucks. Has to be harmonized with XML, DOM, JDOM, and all those nice new technologies where Java does a good job (unless you need a GUI...)
    If anybody has an idea to make it properly -> pls let me know
    thx
    Karl

  • How to Right Justify text on Ipod

    My ipod has been through some wear and tear, long story short, the screen is "cracked" so to speak down the middle and from the middle of the screen to the left side i cannot see anything. I'm trying to figure out how to right justify all of the text so that i can actually use my ipod and search songs

    You can't change the layout of any part of the iPod OS. Sorry. You might want to consider getting the screen replaced. There are lots of third party repair outfits that charge less than Apple to so the job.

  • Cursor not right-justifying in Oracle Forms 11.1.1.6.0

    Hi All,
    A user notice during testing that 'cursor not right-justifying' in a field on a form. There were not such problem in the old forms enviroment 10.1.2.0.2 and clients running JInitiator 1.3.1.22. The new forms enviroment is Oracle weblogic 10.3.6, Oracle forms and report 11.1.1.6.0, using forms demo pack cursorpos.jar and demo90.jar, have try the 11g demo pack but still the same problem, any ideas?
    Thanks
    Ola

    A user notice during testing that 'cursor not right-justifying' in a field on a form.What exactly do you mean by "cursor not right-justifying"?
    You will find noticable differences between the way the Oracle Jinitiiator and Oracle (Sun) Java work. Remember, the Jinitiator was based on the Sun JRE/JDK 1.3 and Forms 11g will be using either Java 1.6.0 or 1.7.0.
    Craig...

  • Sort options right justified in list view

    New to Maverick's, but I can't get my finder window to "stick" with the layout of the "sort options". My biggest beef is that I have the "Name" sort far left followed by "Date modified", etc.. yet every day in every new finder window, the 2nd sort jumps to right justified. I want this sort option to stick to the left alongside name. I use large monitors and scrolling over everytime to drag the sort modifier to the left is frustrating. Is there a solution?

    My guess would be the Images folder (Pictures in English) is designed to have the special, contextual grouping types.
    I don't know why they couldn't make them available in the dropdown menu, also, but they're not.
    I did a little testing and found if I called it Pictures unsorted, the options were available, but if I called the folder unsorted Pictures, they weren't.
    Try naming the folder starting with Images
    Edit: If I select the dimension and resolution column headers in the folder, then change the name of the folder, the columns are retained.

  • Tab delimited and Right justified fields

    Hi
    My requirement is to produce an output file where the line items consists of 5 fields of variable lengths and all of them are tab delimited and right justified at the same time
    for eg.
    ABC       123456ghtje  4567.45678   67.45678  pqr
    where all the values in the first field 'ABC' and 2nd field '123456ghtje' are right justified and are tab delimited and asme is the case for '4567.45678' , '67.45678' and 'pqr'
    they are all separated from each other by a tab but are not fixed lengths
    How can i achieve that ? i am using File Receiver Adapter ??
    Can it be done without Adapter Module ?
    Thanks
    Dev
    Edited by: sd on Feb 22, 2010 2:25 PM
    Edited by: sd on Feb 22, 2010 2:26 PM

    > they are all separated from each other by a tab but are not fixed lengths
    When thay are not fixed length fields, why do you have to worry about left or right justification? In delimetted files, you would only have the delimitter between the fields. You do not need to fill spaces for justifying them.
    VJ

  • How to get search help results in RIGHT-JUSTIFIED column

    I am writing a search help with search help exit. Therefore, I use a table lets say tabA. I don't need all fields of tabA but need some further fields which I fill during exit.
    tabA does not have currency or number fields.
    I need a currency field and use a char20 field of tabA instead. filling of this field and showing results is o.k., but of-course it is shown left-justified.
    I did not find any fields of shlp-fielddescr which sounds like left/centered/right-alignment. Another try was to fill char20 field with leading '_' signs - that looked terrible and was not right-justified either, because of not fixed-size font.
    Let's resume: there is no number or currency field which I can use. The shown results appear in a column of not fixed-size font.
    Any other idea?

    Hi, I have the same problem. Did you get to resolve it? . Thanks

  • Images in smart build open right justified

    Has anyone else seen this.
    I've just opened an existing Keynote08 file in 09. And all my smart build push images have become right justified and off center. I can't find anyway of putting them back into the center. Can anyone help?

    Have a look here. Only workaround I have found is to re-do the build. Send feedback to Apple via the Keynote Menu.

  • How to align Hgrid column(messagestyledtext) header text to right justified

    Hi All,
    I have a Hgrid table and i am using five columns in hgrid table.. I need to display column header text right justified. but by default it is left justified.
    Can any one tell me how to do it..
    Its very urgent.. Please help me out..
    Regards,
    Babu

    Use
    OAHGridBean GeneralHgrid=(OAHGridBean)webBean.findChildRecursive("<hgrid item name>");
    GeneralHgrid.prepareForRendering(pageContext);
    DataObjectList tableColumnFormats =GeneralHgrid.getColumnFormats();
    DictionaryData tableColumnFormat = (oracle.cabo.ui.data.DictionaryData)tableColumnFormats.getItem(pageContext.findChildIndex(GeneralHgrid, "<item id of item attached in hgrid column>"));
    tableColumnFormat.put(COLUMN_DATA_FORMAT_KEY, <enter format>);
    see below:
    �� TEXT_FORMAT (textFormat)- column content is Start justified.
    �� NUMBER_FORMAT (numberFormat)- column content is Right justified.
    �� ICON_BUTTON_FORMAT (iconButtonFormat)- column content is center justified.
    --Mukul                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • DW Right-justifying the index for one site only

    Dreamweaver has suddenly started showing the directory for one of my sites as right-justified:
    Does anyone know how I can get this back to left-justified?
    Thanks
    Steve

    toonbone23 wrote:
    ...Adobe who know exactly what causes this. Don't they ever visit the forum?.
    Steve
    I'm not sure they do!
    This is a user forum.  I htink if you want an answer to your question, you might like to consder raising a support ticket.  I come here quite a bit, and I have never noticed anyone ever having the same thing happen to them.
    Martin

  • Wrting data right justified column

    Hi
    In my application I am using producer consumer loop architechture. In the consumer loop i am writn data from a queue to a file. I want to write data in a certain format to analyze in another program.   Now when i write dat to a file it writes left justified in six columns. I want it to write to file like the one i have attached. Can somebody tell me how?
    Attachments:
    data.PNG ‏53 KB

    Ideally, you would just use a tab as delimiter and change the justification in the other program as needed. For example in MS word you can define how the tabs are justified.
    If you want the data right justified in simple text displays (wordpad, notepad), you just need to ensure that the field width is sufficient for the widest data.
    Try e.g. a format specifier of "%#15_6f' (and make sure that you use a fixed width font for display!)
    Message Edited by altenbach on 10-08-2008 09:53 PM
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    formatRight.png ‏15 KB

  • Tree html header text right justified

    hey ,
    i need to put  the text in the tree header to the right .
    is there any methods to right justified ?
    tried to put some blank in the text-symbols but it didnt work
    any suggustions ?
    Regards
    ASA

    hey ,
    i need to put  the text in the tree header to the right .
    is there any methods to right justified ?
    tried to put some blank in the text-symbols but it didnt work
    any suggustions ?
    Regards
    ASA

Maybe you are looking for