How can I right-align a table header?

Does anyone know a way to right-align a table header?
For example, in the table below I want the word 'Price' to be right-aligned. I could set the table's 'header renderer' to be a right-aligned DefaultTableCellRenderer, but then the header would look like a cell, not a header. Why can't swing be simple, like table.getColumn(1).setAlignment(Column.RIGHT) ????
public class TestTableHeader {
     public static void main(String[] args) throws Exception {
          JFrame frame = new JFrame("Test");
          Object[][] rowData = new Object[][] { { "General Electric", "$100.60" },
                    { "IBM", "$5.20" }, { "Wal-mart", "$17.00" } };
          JTable table = new JTable(rowData, new Object[] { "Name", "Price" });
          DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
          renderer.setHorizontalAlignment(DefaultTableCellRenderer.RIGHT);
          table.getColumnModel().getColumn(1).setCellRenderer(renderer);
          frame.getContentPane().add(new JScrollPane(table));
          frame.setSize(400, 300);
          frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
          frame.setVisible(true);
}

I modified your code an came up with a solution to the problem.
import java.awt.Component;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
public class TestTableHeader {     
     public static void main(String[] args) throws Exception {
          JFrame frame = new JFrame("Test");
          Object[][] rowData = new Object[][] {
                    { "General Electric", "$100.60" }, { "IBM", "$5.20" },
                    { "Wal-mart", "$17.00" } };
          JTable table = new JTable(rowData, new Object[] { "Name", "Price" });
          RightAlignRender right = new TestTableHeader().new RightAlignRender();
          table.getColumnModel().getColumn(0).setHeaderRenderer(right);
          table.getColumnModel().getColumn(1).setHeaderRenderer(right);
          frame.getContentPane().add(new JScrollPane(table));
          frame.setSize(400, 300);
          frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
          frame.setVisible(true);
     public class RightAlignRender extends DefaultTableCellRenderer {
          public Component getTableCellRendererComponent(JTable table,
                    Object arg1, boolean arg2, boolean arg3, int arg4, int column) {
               Component toReturn = table.getTableHeader().getDefaultRenderer().getTableCellRendererComponent(table,
                         arg1, arg2, arg3, arg4, column);
               switch (column) {
               case 0:
                    ((JLabel) toReturn).setHorizontalAlignment(DefaultTableCellRenderer.CENTER);
                    break;
               case 1:
                    ((JLabel) toReturn).setHorizontalAlignment(DefaultTableCellRenderer.RIGHT);
                    break;
               return toReturn;
}

Similar Messages

  • *How can we use the internal table in module pool programming? Clarify plz*

    If we creating a screen using the table having four fields(for e.g.). The screen has the functions of display, modify, delete, save, exit etc for the fields. The front-end of the screen having I/O fields of the table using internal table. How can we declare the internal table in the screen?

    HI,
    Create one WA for your Internal table and then map it to your fields.
    For Example,
    Data : begin of wa,
              name(10),
              age type i,
               end of wa.
    data : it like table of wa with header line.
    Then in screen create input fields with the name, age and ***.
    Then the user entered values are stored in name age and ***.
    then you can manipulate with that values using wa.
    Thanks.

  • How can I know in which Tables are the fields stored

    Hi,
    In transaction FSE3 Display Financial Version
    Statement Version, if I drilldown in details, I can
    see Item No, Chart of Acc, From Accountm To Account D,
    C.
    when I do a F1 on the fields, I can see that it is a
    structure. How can I know in which Tables are the
    fields store?

    Hi Ankit,
    There are no rules or guidelines for finding the table but i will share some of the tips used generally.........but i am not sure if we can do it for a tree structure..but try anyways....
    Double click on the structure name seen on the F1 pop up window...
    in the structure screen, try to analyse the field which is very important something like a key in that set of fields or do the same for the fields which we feel are more important,then click on the domain for that field....once in the domain..click on the "where used list for the domain" on the top...
    it will display a pop up -> select only "table" and then press "Tick/OK"..A list will be displayed with the data element and table name ..from this we need to find out the right one we need either by going for text of the table or going through each and every one
    It takes time but does the job.....
    Regards
    Byju

  • How can I update a customized table from a text document?

    Hi,
    I am one sample file. The file is an text document. From this .txt file how can I update a customized table in SAP.
    How can I Update the fields in the Customized table.
    Thanks & Regards,
    NManohar.

    use the Function module GUI_UPLOAD or WS_UPLOAD and give the path and the file name from where the data has to be uploaded. in table parameter give the iternal table
    CALL FUNCTION 'GUI_UPLOAD'
      EXPORTING
        filename                      =
      FILETYPE                      = 'ASC'
      HAS_FIELD_SEPARATOR           = ' '
      HEADER_LENGTH                 = 0
      READ_BY_LINE                  = 'X'
      DAT_MODE                      = ' '
      CODEPAGE                      = ' '
      IGNORE_CERR                   = ABAP_TRUE
      REPLACEMENT                   = '#'
      CHECK_BOM                     = ' '
      VIRUS_SCAN_PROFILE            =
      NO_AUTH_CHECK                 = ' '
    IMPORTING
      FILELENGTH                    =
      HEADER                        =
      tables
        data_tab                      =
    EXCEPTIONS
      FILE_OPEN_ERROR               = 1
      FILE_READ_ERROR               = 2
      NO_BATCH                      = 3
      GUI_REFUSE_FILETRANSFER       = 4
      INVALID_TYPE                  = 5
      NO_AUTHORITY                  = 6
      UNKNOWN_ERROR                 = 7
      BAD_DATA_FORMAT               = 8
      HEADER_NOT_ALLOWED            = 9
      SEPARATOR_NOT_ALLOWED         = 10
      HEADER_TOO_LONG               = 11
      UNKNOWN_DP_ERROR              = 12
      ACCESS_DENIED                 = 13
      DP_OUT_OF_MEMORY              = 14
      DISK_FULL                     = 15
      DP_TIMEOUT                    = 16
      OTHERS                        = 17
    IF sy-subrc <> 0.
    MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
            WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
    ENDIF.
    and finally use insert command to update the database table with the data

  • How can i indicate that the table columns have different size?

    How can i indicate that the table columns have different size?
    It is because i have a table that has several columns....but i would like to have the possibility to indicate the size for every column....could somebody help me please?
    Thanks,
    Mary

    Hi,
    don't know as much as I should about JTable, but it seems that using yourTable.getDefaultRenderer() could help you: if I clearly understood the javadoc notes, it returns an object inheriting from JLabel, so you should be able to use setHorizontalAlignment(int align) on it... no time to verify this, but I'd be thankfull if you tell me the results !!!
    Regards

  • How can i order a new printer head for my photoshop 7250e

    How can i order a new printer head for my photoshop 7250e  Is there a number i can ring to speak to someone or email address i can use or a web page where i can order one
    or a list of agents i can use to get it from
    Finding simple information seems impossible, no where does it mention spares or replacements 
    I have tried a lot of fault finding am convinced this is the problem  

    Hello NigelH1, 
    The Print Head for the Photosmart 7250  is not available outside HP.
    Please call HP Tech Support for further assistance.
    If you are in US , the toll free # is 1-800-474-6836 .
    If you are not in US , then log on to www.hp.com , at bottom-left corner there is a world map icon, click on it and then select the region you belong to, which would then provide support options for you for that region.
    Regards,
    Jabzi
    Give Kudos to say "thanks" by clicking on the "thumps Up icon" .
    Click "Accept as Solution" if it solved your problem, so others can find it.
    Although I am an HP employee, I am speaking for myself and not for HP.

  • How can I create a new table in a MySQL database in MVC 5

    I have an MVC 5 app, which uses MySQL hosted in Azure as a data source. The point is that inside the database, I want to create a new table called "request". I have already activated migrations for my database in code. I also have the following
    code in my app.
    Request.cs: (inside Models folder)
    public class Request
    public int RequestID { get; set; }
    [Required]
    [Display(Name = "Request type")]
    public string RequestType { get; set; }
    Test.cshtml:
    @model Workfly.Models.Request
    ViewBag.Title = "Test";
    <h2>@ViewBag.Title.</h2>
    <h3>@ViewBag.Message</h3>
    @using (Html.BeginForm("SaveAndShare", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
    @Html.AntiForgeryToken()
    <h4>Create a new request.</h4>
    <hr />
    @Html.ValidationSummary("", new { @class = "text-danger" })
    <div class="form-group">
    @Html.LabelFor(m => m.RequestType, new { @class = "col-md-2 control-label" })
    <div class="col-md-10">
    @Html.TextBoxFor(m => m.RequestType, new { @class = "form-control", @id = "keywords-manual" })
    </div>
    </div>
    <div class="form-group">
    <div class="col-md-offset-2 col-md-10">
    <input type="submit" class="btn btn-default" value="Submit!" />
    </div>
    </div>
    @section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
    HomeController.cs:
    [HttpPost]
    public ActionResult SaveAndShare(Request request)
    if (ModelState.IsValid)
    var req = new Request { RequestType = request.RequestType };
    return RedirectToAction("Share");
    The point is that, I want the user to fill the form inside the Test view and click submit, and when the submit is clicked, I want a new entry in the new table to be created. But first of course I need to create the table. Should I create it using SQL query
    through MySQL workbench? If yes, then how can I connect the new table with my code? I guess I need some DB context but don't know how to do it. If someone can post some code example, I would be glad.
    UPDATE:
    I created a new class inside the Models folder and named it RequestContext.cs, and its contents can be found below:
    public class RequestContext : DbContext
    public DbSet<Request> Requests { get; set; }
    Then, I did "Add-Migration Request", and "Update-Database" commands, but still nothing. Please also note that I have a MySqlInitializer class, which looks something like this:
    public class MySqlInitializer : IDatabaseInitializer<ApplicationDbContext>
    public void InitializeDatabase(ApplicationDbContext context)
    if (!context.Database.Exists())
    // if database did not exist before - create it
    context.Database.Create();
    else
    // query to check if MigrationHistory table is present in the database
    var migrationHistoryTableExists = ((IObjectContextAdapter)context).ObjectContext.ExecuteStoreQuery<int>(
    string.Format(
    "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = '{0}' AND table_name = '__MigrationHistory'",
    // if MigrationHistory table is not there (which is the case first time we run) - create it
    if (migrationHistoryTableExists.FirstOrDefault() == 0)
    context.Database.Delete();
    context.Database.Create();

    Hello Toni,
    Thanks for posting here.
    Please refer the below mentioned links:
    http://azure.microsoft.com/en-us/documentation/articles/web-sites-dotnet-deploy-aspnet-mvc-app-membership-oauth-sql-database/
    http://social.msdn.microsoft.com/Forums/en-US/3a3584c4-f45f-4b00-b676-8d2e0f476026/tutorial-problem-deploy-a-secure-aspnet-mvc-5-app-with-membership-oauth-and-sql-database-to-a?forum=windowsazurewebsitespreview
    I hope that helps.
    Best Regards,
    Sadiqh Ahmed

  • How can I convert an existing table to IOT

    Hi,
    My Oracle version is 10.2.0.4
    Below is my structure of my test_table .
    It has 1141580 rows.
    I want to convert this into index Organized table. It has no secondary indexes.
    How can I convert an existing table to IOT.
    CREATE TABLE test_table (
       Column1             NUMBER        NOT NULL,
       Column2             DATE          NOT NULL,
       Column3             VARCHAR2(100) NOT NULL,
       Column4             VARCHAR2(8)   NULL,
       Column5             VARCHAR2(40)  NOT NULL,
       Column6             VARCHAR2(3)   NULL,
       Column7             NUMBER        NOT NULL,
       Column8             NUMBER        NULL,
       Column9             VARCHAR2(32)  NULL,
    ALTER TABLE test_table
      ADD CONSTRAINT test_table_pk2 PRIMARY KEY (
        Column1,
        Column2
      USING INDEX
        STORAGE (
          INITIAL   30720 K
    ALTER TABLE test_table
      ADD CONSTRAINT test_table_cons1 FOREIGN KEY (
        Column1
      ) REFERENCES test_table2 (
        Column1
    /

    alter table doesn't allow to change the organization of a table.
    So the logical answer to your question is
    You can not
    and your question
    redundant.
    As most other questions here.
    So the answer should have been
    - create a new table
    - insert all rows
    - drop the old table
    - rename the new table
    Oracle is not about rocket science.
    Oracle is about reading documentation and using brains.
    If you do that, maybe, one day, you will be a bigboy.
    If you keep asking redundant questions you will remain a littleboy.
    Sybrand Bakker
    Senior Oracle DBA

  • How can I create an active table of content in the sidebar to help readers to get to the section?

    How can I create an active table of content in the sidebar to help readers to get to the section?

    You can create bookmarks with Adobe Acrobat.

  • How can i create a custom table in to my banking services server

    I am having product type and account type details for those things I need to create a table
    Product Id.                 Account Type
    DP_PYGO_P     21
    DP_BASIC     25
    DP_UNLIMIT     24
    DP_ADVANTG     17
    DP_SAV                     34
    DP_TBILL                     54
    DP_USDCHQ     19
    DP_FREEDOM     52
    For the above fields how can i create a custom table into banking services server

    Transaction SE11, maybe? I don't really see the problem, unless you have never created a transparant table before...

  • How can I load data into table with SQL*LOADER

    how can I load data into table with SQL*LOADER
    when column data length more than 255 bytes?
    when column exceed 255 ,data can not be insert into table by SQL*LOADER
    CREATE TABLE A (
    A VARCHAR2 ( 10 ) ,
    B VARCHAR2 ( 10 ) ,
    C VARCHAR2 ( 10 ) ,
    E VARCHAR2 ( 2000 ) );
    control file:
    load data
    append into table A
    fields terminated by X'09'
    (A , B , C , E )
    SQL*LOADER command:
    sqlldr test/test control=A_ctl.txt data=A.xls log=b.log
    datafile:
    column E is more than 255bytes
    1     1     1     1234567------(more than 255bytes)
    1     1     1     1234567------(more than 255bytes)
    1     1     1     1234567------(more than 255bytes)
    1     1     1     1234567------(more than 255bytes)
    1     1     1     1234567------(more than 255bytes)
    1     1     1     1234567------(more than 255bytes)
    1     1     1     1234567------(more than 255bytes)
    1     1     1     1234567------(more than 255bytes)

    Check this out.
    http://download-west.oracle.com/docs/cd/B10501_01/server.920/a96652/ch06.htm#1006961

  • How can I write into a table cell (row, column are given) in a databae?

    How can I write into a table cell (row, column are given) in a database using LabVIEW Database Toolkit? I am using Ms Access. Suppose I have three columns in a table, I write 1st row of 1st column, then 1st row of 3rd column. The problem I am having is after writing the 1st row 1st column, the reference goes to second row and if I write into 3rd column, it goes to 2nd row 3rd column. Any suggestion? 
    Solved!
    Go to Solution.

    When you do a SQL INSERT command, you create a new row. If you want to change an existing row, you have to use the UPDATE command (i.e. UPDATE tablename SET column = value WHERE some_column=some_value). The some_column could be the unique ID of each row, a date/time, etc.
    I have no idea what function to use in the toolkit to execute a SQL command since I don't use the toolkit. I also don't understand why you just don't do a single INSERT. It would be much faster.

  • How can i find out the table hierarchy

    Hi experts,
    I have one doubt. how can i find out the table hierarchy in the particular schema.
    Let me explain my requirement in detail.. In my Database i have nearly 250 table each table have it's own temporary table(for authorization purpose we are maintaining the temporary tables) for each day i have to clear the temporary table data.
    All temporary table connected with each other. i mean all the table having foreign key relationship.. while i attempt the delete the data from the temporary table it showed ORA-02292: integrity constraint  violated - child record found.
    So can any one please tell how can i delete the child table record first and then parent record table record.
    Thanks in advance
    Arun

    CREATE OR REPLACE FUNCTION get_child_tables (
    ptable VARCHAR2,
    powner VARCHAR2 DEFAULT 'SCOTT',
    plevel NUMBER DEFAULT 10
    RETURN stringarray
    -- -- create this ON SQL*PLUS "CREATE OR REPLACE TYPE STRINGARRAY AS TABLE OF VARCHAR2(50);"
    -- AUTHID CURRENT_USER
    PIPELINED
    AUTHOR DATE VERSION COMMENTS
    ======================================================================================
    [email protected] 26-OCT-2009 1.0 Developed to ease developers effort to find Nth level of Referential integrity
    ======================================================================================
    -- PURPOSE -> To find PARENT=> CHILD relational TABLE(S) in Oracle upto a depth max N Level.
    --SYNTAX TO USE
    SELECT * FROM TABLE( get_child_tables('DEPT','SCOTT',3)); Store this query in a file for your use
    SELECT * FROM TABLE( get_child_tables('EMPLOYEE')); Store this query in a file for your use
    -- RESULTS looks as below
    --1 => DEPT
    --2 => EMP
    --2 => EMP2
    --3 => EMP_CHILD
    --3 => EMP2_CHILD
    -- and so on
    --This can be leveraged to use in any oracle database REGION 10g having and above.
    --This FUNCTION gives formatted result of the Oracle 10g Hierarchical query result coded in the cursor
    --to find MASTER => CHILD relational TABLE(S) upto a depth max 10 Level.
    --The result of the PIPELINED function can be retrieved using Oracle new operator
    --TABLE(array name) in SQL query.
    --Due to the AUTHID CURRENT_USER compiler directive any user can use based on his/her access privileges on the database.
    --GRANT EXECUTE ON SCOTT.get_child_tables TO PUBLIC;
    --CREATE OR REPLACE PUBLIC SYNONYM get_child_tables FOR SCOTT.get_child_tables;
    IS
    atname stringarray := stringarray ();
    -- create this ON SQL*PLUS CREATE OR REPLACE TYPE STRINGARRAY AS TABLE OF VARCHAR2(50);
    vlevel NUMBER;
    vtname VARCHAR2 (50);
    nindex NUMBER := 0;
    bprocessed BOOLEAN := FALSE;
    CURSOR c1 (powner_in IN VARCHAR2, ptable_in VARCHAR2, plevel_in NUMBER)
    IS
    SELECT LEVEL, LPAD (' ', (LEVEL - 1) * 2, ' ') || pt AS "TNAME"
    FROM (SELECT a.owner w1, a.table_name pt, a.constraint_name c1,
    a.r_constraint_name r1, b.owner w2, b.table_name ct,
    b.constraint_name c2, b.r_constraint_name r2
    FROM all_constraints a, all_constraints b
    WHERE a.constraint_name = b.r_constraint_name(+)
    AND a.owner = b.owner(+)
    AND a.owner =
    UPPER (powner)
    -- Change Owner here while testing
    --AND A.r_constraint_name IS NULL
    AND a.constraint_type IN ('P', 'R')) v1
    START WITH pt =
    UPPER
    (ptable)
    -- Change your master table here while testing the QUERY
    CONNECT BY PRIOR ct = pt AND LEVEL <= plevel;
    -- Change lavel here while testing
    BEGIN
    atname.EXTEND;
    atname (1) := 'NOTHING';
    OPEN c1 (powner, ptable, plevel);
    LOOP
    bprocessed := FALSE;
    FETCH c1
    INTO vlevel, vtname;
    IF nindex > 1 AND atname (atname.LAST - 1) = vtname
    THEN
    --DBMS_OUTPUT.PUT_LINE('2 ==== vtname  ' ||vtname || '   '|| atname.count|| '   '||atname.last ||  '   '||atname( atname.last-1));
    bprocessed := TRUE;
    END IF;
    IF NOT bprocessed
    THEN
    nindex := nindex + 1;
    atname.EXTEND;
    atname (nindex) := vtname;
    PIPE ROW (vlevel || ' => ' || vtname);
    DBMS_OUTPUT.put_line ( ' **** nindex - atname( nindex) '
    || nindex
    || ' - '
    || atname (nindex)
    DLOG('ADDING ',vTname); A LOGGING ATONOMUS PROCEDURE FOR DEBUG PURPOSE
    END IF;
    EXIT WHEN c1%NOTFOUND;
    END LOOP;
    CLOSE c1;
    FOR i IN 1 .. atname.COUNT
    LOOP
    DBMS_OUTPUT.PUT_LINE('atname (i) ' ||atname (i));
    END LOOP;
    RETURN;
    EXCEPTION
    WHEN no_data_needed
    THEN -- THIS EXCEPTION HAS TO BE THERE TO GET THE FUCTION WORKABLE
    DBMS_OUTPUT.put_line (SQLERRM);
    RETURN;
    --SELECT * FROM TABLE( get_child_tables('TB_XOP_LETR_TEMPLATE','OPS$CMS',5));
    END get_child_tables;
    Edited by: user3066657 on Jul 21, 2011 8:42 AM
    Edited by: user3066657 on Jul 21, 2011 11:26 AM

  • How can I copy and paste table cells from Pages into InDesign with minimum reformating?

    How can I copy and paste table cells from Pages into InDesign with minimum reformating?

    Do you mean you want to retain the formatting from Pages, or retain formatting already applied in ID?

  • How can I find out whitch table are used in whitch document?

    How can I find out whitch table are used in whitch document?
    In the table EUL5_DOCUMENTS are stored the Documents and in the table EUL5_OBJS are stored the tables. How can I query these tables together?
    Are there other possiblities?
    Thanks

    Hi Dierk
    Please take a look at this thread: Re: An EUL query to list out All the Columns  (Fileds) for each Workbook
    I think you may well find what you are looking for in the answer that I gave there.
    Best wishes
    Michael

Maybe you are looking for

  • Testing to see if a session has expired

    Hello all, I am trying to test to see if the user's session has expired by inserting the following code at the top of the page: HttpSession sess = request.getSession(); if(sess.getAttribute("userId")=="null"){response.sendRedirect("logon.jsp");}The p

  • I can hear them but they can't hear me! -- Detailed

    Hey. My iPhone has been acting up lately. About 2 months ago Apple replaced my almost-1-year-old iPhone 4 because the circle button wasn't responding. So, now I have a new iPhone 4. I have a Speck case on it and with my old phone had no problems with

  • Logic randomly quitting

    This just started happening in the last couple of days... haven't changed anything. Updated to 9.1.8 to see if that's the problem but no luck. Logic will just randomly quit. Sometimes it will work for a few minutes sometimes it will quit the second I

  • Poor quality videos in messages since iOS 8

    I Have an iPhone 4s. Since installing iOS 8 all of the videos I've received and sent via text are super grainy. The videos that I've received are embedded in the message screen and do not go full screen when I click on them as they did before the upd

  • App store set on a different country

    I can't download apps because my app store says it's italian and can't download apps from UK, by the way I live in the UK.. Any help?