How to create Button which size is calculated from its text ?

I think JButton works like this: either in constructor or by setText() method the text is set and according the lenght, font and fontRendererContext preffered size is calculated before the layout manager ask for the prefferedSize for first time.
I want to override paint() method because i want to draw my own text(and the only way i discovered how to force button not to paint text is to set text to
null or empty String). I want the button to be as long as length of text plus insets.
But layout manager ask for preffered size before paint method is invoked but i find out what size should be in paint method because i need graphics
parameter to get FontRendererContext from it. So layout manager shrink button to minimum because first time the preffered size calculated from null or
empty String is returned.
public class MyButton extends JButton {
        public MyButton() {
            this.setText(null);  //or setText("");
            this.setContentAreaFilled(false);
            this.setFocusPainted(false);
            this.setBorderPainted(false);
                                                      ////already here i need to know what the size should be
        @Override
        public void paint(Graphics g) {
            Graphics2D g2 = (Graphics2D) g;
            TextLayout textLayout = new TextLayout("MyButton", this.getFont(), g2.getFontRenderContext());
            Rectangle2D boundsOfText = textLayout.getBounds();                                                                    /////////here i find out what size should be
            this.prefferedSize = new Dimension((int)boundsOfText.getWidth()+10,(int) boundsOfText.getHeight()+10);
            g2.setColor(Color.WHITE);
            g2.fillRoundRect(1, 1,(int)getPreferredSize().getWidth(),(int) getPreferredSize().getHeight(), 10, 10);
            g2.setColor(Color.BLACK);
            g2.drawRoundRect(1, 1,(int)getPreferredSize().getWidth(),(int)getPreferredSize().getHeight(), 10, 10);
            g2.drawString("MyButton", 7, (int)boundsOfText.getHeight() + 6);
            g2.dispose();
    }So how can i do that? How can JButton know prefferedSize before its paint method is invoked?

The previous example was simplified.
public class MyButton0 extends JButton {
    private String myText;
    public MyButton0(String text) {
        this.myText = "Button";
        //this.myText = text.toUpperCase();
        this.setFont(new Font("SansSerif", Font.PLAIN, 13));
        setContentAreaFilled(false);
        setBorderPainted(false);
        setFocusPainted(false);
    @Override
    public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        //backround painting
        GradientPaint background = new GradientPaint(0, 0, new Color(255, 255, 255), 0, getPreferredSize().height / 2, new Color(0, 0, 0), true);
        if(getModel().isRollover()){
            background = new GradientPaint(0, 0, new Color(255, 255, 255), getPreferredSize().width , getPreferredSize().height , new Color(0, 0, 0), true);
        if(getModel().isPressed()){
            background = new GradientPaint(0, 0, new Color(255, 255, 255), 0, getPreferredSize().height / 2, new Color(210, 210, 210), true);
        g2.setPaint(background);
        g2.fillRoundRect(1, 1, getPreferredSize().width - 3 , getPreferredSize().height - 3, 10, 10);
        //Border painting
        g2.setColor(new Color(255, 255, 255));
        g2.setStroke(new BasicStroke(2.0f, BasicStroke.CAP_BUTT, BasicStroke.CAP_BUTT, 10.0f));
        g2.draw(new RoundRectangle2D.Double(1, 1, getPreferredSize().width - 3, getPreferredSize().height - 3, 10, 10));
        //text paiting
        g2.setFont(getFont());
        TextLayout tl = new TextLayout(this.myText, getFont(), g2.getFontRenderContext());
        int startPositionOfText = getPreferredSize().width - (int) tl.getBounds().getWidth();
        startPositionOfText = startPositionOfText / 2;
        g2.setColor(new Color(255, 255, 255));
        g2.drawString(this.myText, startPositionOfText -2, getHeight() / 2 + 5);
        g2.dispose();
    @Override
    public Dimension getPreferredSize() {
        return new Dimension(133, 31);
}Assume text is so long as doesn't fit inside button. I have hard-set preffered size but i would like to calculate preffered size from text lenght.
Or i need calculate startPosition of text to center it. But i don't want have preffered size hard-set.

Similar Messages

  • ADF - How to create table which column header come from query result

    I would like to create table that show the summary of task for each month, the query result such as
    Status MonthofYear Total Task
    03 2007/06 9
    03 2007/05 12
    03 2007/04 10
    03 2007/03 7
    05 2007/06 6
    05 2007/05 3
    06 2007/06 1
    09 2007/06 1
    And the table that I would like to show in jdeveloper is
    Status 2007/06 | 2007/05 | 2007/04 | 2007/03 | ......... | 2006/05
    03 9 | 12 | 10 | 0 | .......
    05 6 | 3 | 0 | 0 | .......
    06 1 | 0 | 0 | 0 | .......
    09 1 | 0 | 0 | 0 | .......

    Lucas worked out a solution for this:
    http://technology.amis.nl/blog/?p=2070

  • How to Create Buttons With some operation

    Hello friends How can create button so that when i click that button it should open another new window so that i can select some options in that new window and do some calculations.
    Kindly help me .
    byee

    Hi JN,
    I have created a Frame which has some checkboxes , a button and text field. when i check some checkboxes and press the Button (ie in my program Metrics level Button ) it should display the result as number of checkboxes that are checked divided by total number of chechboxes. ie if i check some 6 check boxes and press the Metrics level button it should display 6 divided by 12 ie 0.5 in the Result Textfield.
    I am sending the code i have written.
    Thanks in advance.
    public class Frame extends java.awt.Frame {
    /** Creates new form Frame */
    public Frame() {
    initComponents();
    setSize(800, 800);
    private void initComponents() {
    label1 = new java.awt.Label();
    checkbox1 = new java.awt.Checkbox();
    checkbox2 = new java.awt.Checkbox();
    checkbox3 = new java.awt.Checkbox();
    checkbox4 = new java.awt.Checkbox();
    checkbox5 = new java.awt.Checkbox();
    checkbox6 = new java.awt.Checkbox();
    checkbox7 = new java.awt.Checkbox();
    checkbox8 = new java.awt.Checkbox();
    checkbox9 = new java.awt.Checkbox();
    checkbox10 = new java.awt.Checkbox();
    checkbox11 = new java.awt.Checkbox();
    checkbox12 = new java.awt.Checkbox();
    button1 = new java.awt.Button();
    textField1 = new java.awt.TextField();
    setLayout(null);
    addWindowListener(new java.awt.event.WindowAdapter() {
    public void windowClosing(java.awt.event.WindowEvent evt) {
    exitForm(evt);
    label1.setText("Select the Metrics below");
    add(label1);
    label1.setBounds(320, 20, 136, 20);
    checkbox1.setLabel("Architecture Metrics");
    add(checkbox1);
    checkbox1.setBounds(240, 80, 84, 20);
    checkbox2.setLabel("Runtime Metrics");
    add(checkbox2);
    checkbox2.setBounds(240, 200, 115, 20);
    checkbox3.setLabel("Documentation Metrics");
    add(checkbox3);
    checkbox3.setBounds(240, 320, 152, 20);
    checkbox4.setLabel("Size");
    add(checkbox4);
    checkbox4.setBounds(280, 110, 49, 20);
    checkbox5.setLabel("Structure");
    add(checkbox5);
    checkbox5.setBounds(280, 130, 75, 20);
    checkbox6.setLabel("Complexity");
    add(checkbox6);
    checkbox6.setBounds(280, 150, 86, 20);
    checkbox7.setLabel("Size");
    add(checkbox7);
    checkbox7.setBounds(290, 230, 49, 20);
    checkbox8.setLabel("Structure");
    add(checkbox8);
    checkbox8.setBounds(290, 250, 75, 20);
    checkbox9.setLabel("Complexity");
    add(checkbox9);
    checkbox9.setBounds(290, 270, 86, 20);
    checkbox10.setLabel("Size");
    add(checkbox10);
    checkbox10.setBounds(300, 350, 49, 20);
    checkbox11.setLabel("Structure");
    add(checkbox11);
    checkbox11.setBounds(300, 370, 75, 20);
    checkbox12.setLabel("Complexity");
    add(checkbox12);
    checkbox12.setBounds(300, 390, 86, 20);
    button1.setLabel("Metrics level");
    add(button1);
    button1.setBounds(290, 470, 83, 24);
    textField1.setText("Result");
    textField1.setName("Result");
    add(textField1);
    textField1.setBounds(400, 470, 60, 20);
    pack();
    public void actionPerformed(ActionEvent e) {
    ****** I think code should be added here for the button pressed event*******
    /** Exit the Application */
    private void exitForm(java.awt.event.WindowEvent evt) {
    System.exit(0);
    * @param args the command line arguments
    public static void main(String args[]) {
    new Frame().show();
    // Variables declaration - do not modify
    private java.awt.Button button1;
    private java.awt.Checkbox checkbox1;
    private java.awt.Checkbox checkbox10;
    private java.awt.Checkbox checkbox11;
    private java.awt.Checkbox checkbox12;
    private java.awt.Checkbox checkbox2;
    private java.awt.Checkbox checkbox3;
    private java.awt.Checkbox checkbox4;
    private java.awt.Checkbox checkbox5;
    private java.awt.Checkbox checkbox6;
    private java.awt.Checkbox checkbox7;
    private java.awt.Checkbox checkbox8;
    private java.awt.Checkbox checkbox9;
    private java.awt.Label label1;
    private java.awt.TextField textField1;
    // End of variables declaration
    this is the output when i execute the program

  • Create image which is filled in from another image*

    Create image which is filled in from another image?   How do I blend two images - using the outline of one and the coloring or background of the other? 

    Everything you want to do and more is available through the use of Photoshop Layers.
    It's kind of beyond the scope of the forum to teach basic Photoshop layer usage, but you can find many tutorials online, and Photoshop itself comes with decent documentation (Help).
    You can, for example, open one image, paste or place another over it as a second layer, then you can blend the two through many different Blending options, as well as 0 to 100% blending percentage.  You can even use transparency or masking to make parts of a layer transparent, opaque, or anything in between.
    Using selection and refinement tools, you can even put subjects on different backgrounds...
    -Noel

  • I need to make button which made a spool from my oracle forms 2.1

    i need to make button which made a spool from my oracle forms 2.1
    how can i do that
    thanks alot

    Wow, you just said the same thing. First, when you say "Forms 2.1" do you mean "Developer 2.1", which included Forms 5.0? Regardless, are you aware that these Forms versions are about 15 or more years old?
    What you are trying to do is still unclear. Are you trying to output records to a text file formated to csv? If you need assistance, please provide some clarification as to what you are trying to accomplish.

  • Can you have multiple Apple TV's in the same house and network? If so how do you know which one to pick from your Idevice?

    can you have multiple Apple TV's in the same house and network? If so how do you know which one to pick from your Idevice?

    Yes, there are even defaults for naming them, such as LivingRoom, Bedroom, etc, or you can even enter your own name with the remote for each AppleTV.

  • How to create a Blanket Release in iProc from a approved requistion

    Hi Gurus,
    How to create a blanket Release in iProcurement from a approved requisition. I have followed the below steps.
    1. Created a BPA from Front end.
    2. Run Loader Data program.
    3. Above program reflected the BPA in iProc.
    4. Created requisition from BPA.
    5. Requisition has been approved.
    After this i am stuck. How to proceed ahead. I want to create a Blanket Release from approved PR and then receive in iProcurement.
    please help me on this. We are using 11.5.10.2
    Regards,
    john

    911765 wrote:
    Hi Mahendra,
    Thank you so much for your reply.
    So you mean to say that it all depends upon the Sourcing Rule and ASL based upon that system would automatically create a Blanket Release or If its Automatic Release/Review then we have to manually create release through autocreate.
    The reason why i am asking this query is now when i tested it, system is automatically creating release and starngely there is no Sourcing Rule and ASL has been defined.
    But we are looking for a Manual Release through autocreate window.
    It would be great if you could please suggest.
    Regards,
    JohnJohn,
    When you say system is automatically creating release..as far as i know...it should be referencing a PO..correct...in the releases window..
    can you pull that up..and see if you can get any clue..bcz that PO would BPA...
    Also I am not that much into Iproc...I don't know...whether Iproc has some other setups
    HTH
    Mahendra

  • How to create pdf files in UNIX directory from oracle reports

    I would like to know how to create pdf files in UNIX directory from oracle reports.
    Thanks,

    Please make your question more clear . Also mention the reports version.
    1) If you are runnning reports in Unix, you can give
    .... destype=file desformat=pdf desname=<filename>
    in command line
    Please refer docs below.
    2) If by your question you mean
    "My reports server is running in Windows but I want to ftp my files to Unix after creating it"
    then the answer is that you can use pluggable destination "ftp"
    .... destype=ftp desformat=pdf desname=<ftp url>
    Pluggable destinations download
    http://otn.oracle.com/products/reports/pluginxchange/index.html
    Thanks
    Ratheesh
    [    All Docs     ]
    http://otn.oracle.com/documentation/reports.html
    [     Publishing reports to web  - 10G  ]
    http://download.oracle.com/docs/html/B10314_01/toc.htm (html)
    http://download.oracle.com/docs/pdf/B10314_01.pdf (pdf)
    [   Building reports  - 10G ]
    http://download.oracle.com/docs/pdf/B10602_01.pdf (pdf)
    http://download.oracle.com/docs/html/B10602_01/toc.htm (html)
    [   Forms Reports Integration whitepaper  9i ]
    http://otn.oracle.com/products/forms/pdf/frm9isrw9i.pdf

  • How to create a service entry sheet based from the PO

    how to create a service entry sheet based from the PO
    Gurus,
    I am creating a service entry sheet from the PO but I am getting an error of u201CPlease maintain services or limits Message no. SE029- Diagnosis(You cannot enter data until the PO item has been maintained correctly) u201C
    The document type of the PO is standard NB, account assignment category is Q- (Proj make to order) and the item category is D(service). Then I am trying also create a PR using account assignment category is Q- (Proj make to order) and the item category is D(service) but still cannot proceed, a message asking me to enter a service entry number. What I know the process is create a PO(maybe based from PR) then post the GR then create a service entry sheet in ML81N but I cannot proceed. Just creating a PR or PO using those mentioned account assignment and item category and getting an error of need to enter a service entry sheet number.
    Please help.thanks!

    HI,
    Process for Creating Service Entry Sheet
    Transaction Code :    ML81N
    1)To open the respective Purchase Order, Click on the u2018Other Purchase Orderu2019, then enter the Purchase Order No.
    2)Click on the u2018Create Entry Sheetu2019 icon(3rd Icon on Top-Left)
    3)Give Short Text (e.g. R/A Bill No. 1) and top service entry sheet number also generated.
    4)Click u2018Service Selectionu2019 Icon on the Bottom of the Screen.
    5)For the 1st Time, when we are making Service Entry Sheet for a respective Purchase Order, we need to u201CAdopt Full Quantityu201D by clicking the Check box next to it, then Enter.  (*For the next time, no adoption is required, just continue)
    6)Select the respective Services by clicking on the Left Hand Side, then Click u2018Servicesu2019 (Adopt services) icon on the Top.
    7)Give the completed Quantity, then Click u2018Acceptu2019 icon(a green flag on the top)
    8)Save .
    9)Service Entry Sheet is SAVED and account posting made.
    Hope, it is useful for you,
    Regards,
    K.Rajendran

  • TS2755 how do I see which apps are downloaded from a certain device when you have multiple devices

    how do I see which apps are downloaded from a certain device when you have multiple devices

    you can't.

  • How to create customer exit for characteristic variables and for text vars.

    hi friends,
      can anybody tell me how to create customer exit for characteristic variables and for text variables in bw ides system.
    thanks,
    sree

    Hi,
    Please have a look at:
    https://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/library/uuid/f1a7e790-0201-0010-0a8d-f08a4662562d
    Krzys

  • How to create button programmatically and assign trigger for it and add code

    is that possible ?
    How can I create item a button for example programmatically (at run time)
    and create trigger (when-button-pressed) programmatically and write a code
    in the trigger body as well programmatically.
    thankx

    Hello David
    I used the way list and go button which is more safer than creating buttons because
    you can populate the list on fly.
         | dropdown list     \/
              | go button |
    PROCEDURE populate_user_function_list IS
         rg_list_id RECORDGROUP;
         ret_code     NUMBER;
    BEGIN
         rg_list_id := FIND_GROUP('RG_LIST');
         IF NOT ID_NULL(rg_list_id) THEN
              DELETE_GROUP(rg_list_id);
         END IF;
         rg_list_id := CREATE_GROUP_FROM_QUERY('RG_LIST','SELECT FUNCTION_ID, FUNCTION_ID FROM SMS_ROLE_FUNCTION WHERE SMS_ROLE_FUNCTION.DB_ROLE ='||''''||:GLOBAL.USER_ROLE||''''||' ORDER BY SEQUENCE_NO');
         ret_code := POPULATE_GROUP(rg_list_id);
         --Populate record group.
              IF ret_code <> 0 THEN
              bell;
              MESSAGE('Record Group could not be populated');
              RAISE FORM_TRIGGER_FAILURE;
              END IF;
         POPULATE_LIST('DYNAMIC_BLK.USER_FUNCTION','RG_LIST');
         DELETE_GROUP(rg_list_id);
    END;
    --this is the button to go the user selection
    begin
         if :DYNAMIC_BLK.USER_FUNCTION is not null then
              --go to selected form
              call_form(:DYNAMIC_BLK.USER_FUNCTION,NO_HIDE,DO_REPLACE,NO_QUERY_ONLY,NO_SHARE_LIBRARY_DATA);     
         else
              bell;
              message('Please select a function');
         end if;
    end;

  • How to create Buttons for Excel,Print & help!

    Hi Experts
      Anyone has an experience how to create a Buttopn Group for the following options.
    1.Excel
    2.Printchart
    3.Printtable
    4.Printreport
    5.Help
    Pls revert to me <removed by moderator>.
    Thanks
    BI Learner
    Edited by: Siegfried Szameitat on Dec 1, 2008 10:46 AM

    Hi,
    Your PDF output and the output of the Template on Web should be similar, ideally. But, if the width of the 2 reports are bigger and that cannot fix in one page, then the PDF output will not be as you require it to be.
    You have to decrease the dimensions of the Analysis item in the Template and see how the output size varies in the Web.
    Also, when you have defined the command for converting to PDF, select the checkbox which allows you to see the "Page Setup" while you are converting it to PDF in the Web, ie in the output of the template. Here, set the margins to the minimum (Left, right, top and bottom). This also ensures that the Analysis item gets the maximum area in the output.
    Just try this piece of code too,
    <bi:CAPTION value="Print PDF" />
    <bi:TOOLTIP value="Print to PDF Document" />
    <bi:ACTION type="CHOICE" value="INSTRUCTION" >
    <bi:INSTRUCTION >
    <bi:EXPORT >
    <bi:REPEAT_KEYCOL value="" />
    <bi:PAPER_ORIENTATION value="LANDSCAPE" />
    <bi:MARGIN_RIGHT value="10" />
    <bi:MARGIN_LEFT value="10" />
    <bi:MARGIN_TOP value="10" />
    <bi:MARGIN_BOTTOM value="10" />
    Here the margins are set to 10. You can even try decreasing this depending on your requirement.

  • (Urgent) Dynamically created buttons: which one?

    I need to dynamically create an array of gridpanels. There is a button and some other components on each gridpanel. I need to implement an action handler for the button (using method binding). But how do I know which button fires the event?
    Thanks a lot!

    Hi,
    One of the possible solutions is:
    Have a hidden field in the form. For each of the buttons write a javascript onclick event method in which the id of the button clicked is assigned to the hidden field. The value of this hidden field is available in the method handler. This helps in identifying which button was clicked.
    Hope this helps
    Cheers
    Giri

  • How to create EAN which can ahve leading zeros ?

    hi,
    I am trying to create a range for EAN's where will have the chance to start with leading zeros.
    any one has had a similar issue ?
    any suggestion on how to create therange ?
    should be for 14 digits.
    Thanks,

    Hi Alex,
    You can define EAN in MM01 use Additional data button then EAN's tab or you can use the Plant data / stor 2 tab, General plant parameters -> Serial No. Profile field to create your EAN (serial) range. Hope this helps.
    Regards,
    Joven
    ==============
    Award points if useful

Maybe you are looking for