JTable How to align the Text in a Cell to Centre
Hi Plese Help regarding JTable.
I want to align the Text in the Table Cell to Centre how to align it. Im using Abstract Data Model TAble an what is the meaning of renderer and its use.. Help me out
Here are a couple of links you should read for information on tables and renderers:
http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#editrender
http://www-106.ibm.com/developerworks/java/library/j-jtable/index.html?dwzone=java
Here is an example of a simple renderer that will:
a) center the text
b) highlight the background when the cell gets focus
This renderer is only used in two of the columns of the table.
import java.awt.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
public class TableRenderer extends JFrame
public TableRenderer()
String[] columnNames = {"Date", "String", "Integer1", "Integer2", "Boolean"};
Object[][] data =
{new Date(), "A", new Integer(1), new Integer(5), new Boolean(true)},
{new Date(), "B", new Integer(2), new Integer(6), new Boolean(false)},
{new Date(), "C", new Integer(3), new Integer(7), new Boolean(true)},
{new Date(), "D", new Integer(4), new Integer(8), new Boolean(false)}
DefaultTableModel model = new DefaultTableModel(data, columnNames);
JTable table = new JTable( model )
// Returning the Class of each column will allow different
// renderers to be used based on Class
public Class getColumnClass(int column)
return getValueAt(0, column).getClass();
JScrollPane scrollPane = new JScrollPane( table );
getContentPane().add( scrollPane );
// Create cell renderer
TableCellRenderer centerRenderer = new CenterRenderer();
// Use renderer on a specific column
TableColumn column = table.getColumnModel().getColumn(3);
column.setCellRenderer( centerRenderer );
// Use renderer on a specific Class
table.setDefaultRenderer(String.class, centerRenderer);
public static void main(String[] args)
TableRenderer frame = new TableRenderer();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setVisible(true);
** Center the text and highlight the focused cell
class CenterRenderer extends DefaultTableCellRenderer
public CenterRenderer()
setHorizontalAlignment( CENTER );
public Component getTableCellRendererComponent(
JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if (hasFocus)
setBackground( Color.cyan );
else if (isSelected)
setBackground( table.getSelectionBackground() );
else
setBackground( table.getBackground() );
return this;
Similar Messages
-
How to align the text in justify format with SQL Server Reporting Services?
How to align the text in justify format In SQL server Reporting Services? Is there any code to do so?
Hi,
I'm afraid that if you want to have this kind of functionality, you will need to write a custom control. Here is an example: http://msdn2.microsoft.com/en-us/library/ms345265.aspx. The issue with custom controls is that it needs to be known by all the reportservers that will render your report.
Greetz,
Geert
Geert Verhoeven
Consultant @ Ausy Belgium
My Personal Blog -
How to set the text of a cell in Numbers to vertical direction? Tks.
Hi
In Numbers, please tell me how to switch the text of a cell to vertical direction?
Tks.Hi Kyle,
In Numbers, nothing having to do with a table can be rotated. (In Pages an entire Table can be rotated, but not text within a Table.)
There have been many suggestions posted here over the life of iWork for vertical labels. Most fall into three categories:
1. Type one letter, Option-Return, type another letter, Option-Return, and so forth.
2. Type label in a Text Box, rotate the box, position the box over the table, covering the cell where you need a label.
3. Create a PDF graphic with rotated text and insert it into table cell as Background Fill.
The third option is clearly the best. The steps for option three are:
Insert Text Box
Type label into the box
Rotate the text box
Select the text box (not the text inside the box)
Command-C
Switch to Preview.app
Command-N
Command-C
Switch to Numbers
Click on Cell where the label goes
Command-V
It sounds worse than it is. You can reuse the Text Box so you don't end up with a sheet full of them.
Regards,
Jerry -
How to align the text vertical in the edit box in mfc?
Hi,
I had an edit box of which height is increased than the default.Now the problem here is when I am entering text into the edit box the text is not present at the centre of the edit box, It is still aligned at the top.
After increasing the height of the edit box the text and cursor are aligned at the top as shown in the below figure.
But Actually how I want is the text and the cursor position needs to be aligned centre as shown in the below figure.
Note: "EDITTEXT IDC_EDIT_BOX,10,73,156,14,ES_AUTOHSCROLL"
Can anyone please help me how can I make the text and the position of the cursor to be aligned vertically i.e, to the centre of the control.
SivaVIf vertical alignment is not possible, then use an edit box without borders, having the default height, and place it inside a static control having
SS_WHITERECT style. (In MFC Dialog Editor, set the Type and Colour properties). Both of controls will be children of dialog. Use a proper tab order. Check if the style
WS_CLIPSIBLINGS is needed too. -
How to get the text of several cells in one? (Operator "&")
Hi there,
I have a list of done and planned tasks. In the one column, there is the description, in the other is the status like "plan" "open" and "closed".
Now I want to create an overview.How can I filter the "open" tasks and display them in one cell? I could do it like
+If(B1="open";A1;"") & If(B2="open";A2;"")...+
and so on. But as I have over 20 projects and therefor over 20 sheets, I'm seeking for a easier way. Also the reference thing would only work if there is only one open project, but sometimes I have two or three open tasks.schubladenachrank,
Now, I think I see what you are trying to do. With a clearer picture of what you wanted I came up with the following:
First of all, the added columns in you project (title) tables are no longer necessary.
Next, an "Open Tasks Summary", is still needed but a different concept is employed. A column is needed for each title and if a task is open, that task is concatenated with the previous list of open tasks. Not unlike the method you were attempting in your original post. At this point we note that the number of rows in all of your project tables must be at least equal to the maximum number of tasks of all projects. The number of rows in your summary table must be 1 greater. The sample allows a maximum of ten tasks and the last cell of a column will always show all of the open tasks for that project.
In the first row (row 2) of the "Open Tasks Summary" table enter the formula: ="" (This is to seed the subsequent formulas below)
The rest of the formulas follow the form: =IF(Title 1 :: $B2="Open",A2&" "&Title 1 :: $A2,A1)
Copy these across first and change the title names. Then they can be copied down.
Finally, match the last column cell to the proper title in your master summary under "Status" by using: =Open Tasks Summary :: A12
pw -
How to aling the text in a JTable???
I use this code to make a vertical header like in excel. The thing is that i want to aling the text in that column but i couldn´t. I try to set the render, but i loose the header render in the column. Anyone know how to aling the text in that column with out loosing the header effect????
i post a code that i use as model for my project.
package com.chuidiang.ejemplos;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.WindowConstants;
import javax.swing.table.DefaultTableModel;
* Ejemplo de cómo hacer una "cabecera" lateral en un JTable. Idea original de
* Leunamal en
* http://foro.chuidiang.com/java-j2se/tabla-de-referencias-cruzadas-en-java/
* Básicamente consiste en hacer que la primera columna: - No sea editable. - No
* sea seleccionable. - Tenga el mismo render que el JTableHeader superior.
* @author chuidiang
public class CabeceraLateral {
* Crea y visualiza una ventana con un JTable que tiene cabecera en la parte
* superior y en la columna izquierda
* @param args
public static void main(String[] args) {
// Un modelo de datos que hace la primera columna (la de
// la cabecera lateral) no editable.
DefaultTableModel tm = new DefaultTableModel(10, 5) {
@Override
public boolean isCellEditable(int row, int column) {
if (0 == column)
return false;
return super.isCellEditable(row, column);
// Titulos para la cabecera superior. El primero es vacio,
// puesto que corresponde
tm.setColumnIdentifiers(new String[] { "", "A", "B", "C", "D" });
// Valores para la primera columna, que es la cabecera lateral.
for (int i = 0; i < 10; i++)
tm.setValueAt(i + 1, i, 0);
// JTable al que se le pasa el modelo recien creado y se
// sobreescribe el metodo changeSelection para que no permita
// seleccionar la primera columna.
JTable t = new JTable(tm) {
@Override
public void changeSelection(int rowIndex, int columnIndex,
boolean toggle, boolean extend) {
if (columnIndex == 0)
super.changeSelection(rowIndex, columnIndex + 1, toggle,
extend);
else
super.changeSelection(rowIndex, columnIndex, toggle,
extend);
// Se pone a la primera columna el render del JTableHeader
// superior.
t.getColumnModel().getColumn(0).setCellRenderer(t.getTableHeader().getDefaultRenderer()); //here i set the render for the column. But when i try to aling the text, this column loose the effect.
// Creación y visualización de la ventana completa.
JFrame v = new JFrame("Cabecera lateral");
JScrollPane sp = new JScrollPane(t);
v.getContentPane().add(sp);
v.pack();
v.setVisible(true);
v.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}The word is "align" not aling.
To right-align the first column, you can do this in a prepareRenderer override. JTable t = new JTable(tm) {
@Override
public void changeSelection(int rowIndex, int columnIndex,
boolean toggle, boolean extend) {
if (columnIndex == 0) {
super.changeSelection(rowIndex, columnIndex + 1, toggle,
extend);
} else {
super.changeSelection(rowIndex, columnIndex, toggle,
extend);
@Override
public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
Component c = super.prepareRenderer(renderer, row, column);
if (column == 0) {
((JLabel) c).setHorizontalAlignment(JLabel.RIGHT);
return c;
};You can find other alternatives to your approach by searching the net for "[JTable row header|http://www.google.com/search?q=JTable+row+header]"
db -
Aligning the Text in Centre for MultiLine Cells in JTable
Hi;
Does anyone know how I could make a java table that has multiline text cells AND this multiline text is aligned to center? I tried to extend JTextArea and to implement TableRenderer - multiline was OK but it did not do anything on setHorizontalAlign. If I extend DefaultTableRender than I can align the text to center but I got no multiline...
Any ideas?
Kindly to provide me a solution for this its urgent.Hi;
Thanks for the reply,on using Text Area as renderer i.e using Multi-Line cells in JTable, i achieved the objective of displaying the text on multiple lines in the cell."In my Table there are 5 columns and i'm setting renderer on 3rd and 5th column,If the text is too large in column 5 it automatically gets wrapped off for all the cells in column 5.For column 3 my text is not so large as compared to column 5 and due to which the Text in the column 3 starts from the top for all the cells i.e (the first row in column 3 is parallel to first row in column 5 ),Now the problem is i can't display the text in the center of all cells for Column 3 .
Thanks in advance -
JLabel: How to Left Align the text
Hi.
I created a JLabel and wanted to left align the text. However, the text is always centered in the frame that contains it. Can you tell me what I need to add to the code?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Frame.*;
public class S extends JFrame
public S()
setSize(300, 300);
setTitle("Title Bar");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel("A label", JLabel.LEFT);
label.setHorizontalAlignment(JLabel.LEFT);
label.setToolTipText("Should be left aligned");
JPanel pane = new JPanel();
pane.add(label);
setContentPane(pane);
public static void main(String[] args)
S f = new S();
f.show();
}Thanks
RajaRead this section from the Swing tutorial on "Using Layout Managers":
http://java.sun.com/docs/books/tutorial/uiswing/layout/using.html
Layout Managers layout the components based on rules for each layout manager.
By default a JPanel uses a FlowLayout. By default FlowLayout aligns components in the center of the space allocated to it. In your case you allocated 300 to the width of the frame, therefore the panel has a width of 300, therefore the label is centered in the 300 pixels. -
How to print the text in points wise in sap script
hi friends,
how to print the text in points wise in sap script.
ex: if suppose paragraph consists of 15 lines. then according to one sentence or one fullstop (.) it should give point 1. like that...
1. hai how ru.
2. what r u doing.
3.where r u.
like this i want numbering.. waiting for ur replys.
thanks,
kirandeclare a counter
data : cnt type char 4.
print :
cnt = cnt + 1.
&cnt& &text&
cnt = cnt + 1. and so on.
or.
if the data is in an internal table
loop at internal_table.
cnt = cnt + 1.
write form.
in script -&cnt& &text&
endloop.
Edited by: NIKHILKUMAR POOJARI on Nov 17, 2008 11:18 AM -
How to print the text in only last but one page in sapscripts
hiiiiiiiiiii,
explian how to print the text in only last but one page in sapscripts? wher to write the code? plz if possible explain in detail with an example?Hello,
The total no pages is given by &SAPSCRIPT-FORMPAGES& command.
So u can handle the situation in ur form like this
/: if &PAGE& = &SAPSCRIPT-FORMPAGES&
p1 TEXT
/: endif
Try in this way it may help u.
Regards -
Did you know how to link the text in two or more text boxes?
Did anyone know how to link the text in two or more text boxes in Pages 5.0? Thanks for your answer.
Qualcuno sa come collegare il testo in due o più caselle di testo nella versione 5.0 di Pages. Grazie per le vostre risposte.It's just one of the many, many features that have been eliminated or changed. Leave feedback for the Pages team using the link in the Pages menu and review & rate the new versions in the Mac App Store.
If you previously had iWork '09, those apps are still in your Applications folder in a folder named iWork '09. You can continue to use them to get things done. -
I cannot figure out how to make the text larger in a received email. The finger method doesn't work and I can find no tool bar as I can for composing emails. I can find nothing in settings. Please help and thank you in advance.
Hi there,
Download a piece of software called TinkerTool - that might just solve your problem. I have used it myself to change the system fonts on my iMac. It is software and not an app.
Good wishes,
John. -
How to use the text module in script
hi,
i script how to use the text modules and how to write the code in layout of the script?Hi,
You canr use text modules in script. You have to use standard texts .
Standard text are maintained in SO10 transaction.
you can create translation text for other languages also . So based on logon language it will print translation text.
go to SO10
give textname it say Ztextname id as ST and language as EN
say create, then you will get editor there maintain your text and save it . then come back . Now change language (say for german DE) say create and eneter translation text and save it.
so now you have created a text called ztextname which you can use in your script.
Inorder to insert the texts in your script do as below
go to any window editor and select path
Insert->texts->symbols->standard symbols
then you will get popup in which you have to mention all the parameters that you have created earlier.
after inserting just change language EN to sy-langu
Reward points if useful
About text elements Sravan already given some informatiomn
Regards,
Nageswar -
How to clear the text in the Text Editor
Hi all,
I created a Text editor and also i am having language field in the screen.
whenever i change the language auomatically the text has to change when the text exists for that
language.
this is working fine, but when the Text exist , the text editor should be blank.
But it is carrying the Previous editor text itself into it .
How to clear the text in the Editor.
Regards,
MadhaviHello Madhavi
The simple report ZUS_SDN_TEXTEDIT_CONTROL shows how to switch the texteditor contents when changing the language.
*& Report ZUS_SDN_TEXTEDIT_CONTROL
*& Thread: how to clear the text in the Text Editor
*& <a class="jive_macro jive_macro_thread" href="" __jive_macro_name="thread" modifiedtitle="true" __default_attr="1145272"></a>
*& By default the itab GT_OUTTAB contains texts in DE and EN.
*& To switch the language directly enter into the command window:
*& LANGU=DE, LANGU=EN or LANGU=FR
REPORT zus_sdn_textedit_control.
TYPE-POOLS: abap.
TYPES: ty_t_text TYPE TABLE OF as4text
WITH DEFAULT KEY.
TYPES: BEGIN OF ty_s_outtab.
TYPES: language TYPE spras.
TYPES: text TYPE ty_t_text.
TYPES: END OF ty_s_outtab.
TYPES: ty_t_outtab TYPE STANDARD TABLE OF ty_s_outtab
WITH DEFAULT KEY.
DATA: gt_outtab TYPE ty_t_outtab,
gs_outtab TYPE ty_s_outtab.
DATA: gd_language TYPE spras.
DATA: go_docking TYPE REF TO cl_gui_docking_container,
go_textedit TYPE REF TO cl_gui_textedit.
DATA: gd_okcode TYPE ui_func,
gd_repid TYPE syst-repid.
START-OF-SELECTION.
PERFORM fill_texts.
gd_language = syst-langu.
PERFORM init_controls.
* Link the docking container to the target dynpro
gd_repid = syst-repid.
CALL METHOD go_docking->link
EXPORTING
repid = gd_repid
dynnr = '0100'
* CONTAINER =
EXCEPTIONS
OTHERS = 4.
IF sy-subrc NE 0.
* MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
* WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
ENDIF.
PERFORM set_text_editor.
* NOTE: dynpro does not contain any elements
" ok-code => GD_OKCODE
CALL SCREEN '0100'.
* Flow logic of dynpro (does not contain any dynpro elements):
*PROCESS BEFORE OUTPUT.
* MODULE STATUS_0100.
*PROCESS AFTER INPUT.
* MODULE USER_COMMAND_0100.
END-OF-SELECTION.
*& Module STATUS_0100 OUTPUT
* text
MODULE status_0100 OUTPUT.
SET PF-STATUS 'STATUS_0100'. " contains push button "DETAIL"
* SET TITLEBAR 'xxx'.
ENDMODULE. " STATUS_0100 OUTPUT
*& Module USER_COMMAND_0100 INPUT
* text
MODULE user_command_0100 INPUT.
TRANSLATE gd_okcode TO UPPER CASE.
CASE gd_okcode.
WHEN 'BACK' OR
'EXIT' OR
'CANC'.
SET SCREEN 0. LEAVE SCREEN.
WHEN 'LANGU=DE' OR
'LANGU=EN' OR
'LANGU=FR'.
PERFORM get_text_editor.
SPLIT gd_okcode AT '=' INTO gd_okcode gd_language.
PERFORM set_text_editor.
WHEN OTHERS.
ENDCASE.
CLEAR: gd_okcode.
ENDMODULE. " USER_COMMAND_0100 INPUT
*& Form FILL_TEXTS
* text
* --> p1 text
* <-- p2 text
FORM fill_texts .
* define local data
DATA: ld_string TYPE string.
gs_outtab-language = 'EN'. REFRESH: gs_outtab-text.
ld_string = 'Good morning'.
APPEND ld_string TO gs_outtab-text.
APPEND gs_outtab TO gt_outtab.
gs_outtab-language = 'DE'. REFRESH: gs_outtab-text.
ld_string = 'Guten Morgen'.
APPEND ld_string TO gs_outtab-text.
APPEND gs_outtab TO gt_outtab.
gs_outtab-language = 'FR'. REFRESH: gs_outtab-text.
ld_string = space.
APPEND ld_string TO gs_outtab-text.
APPEND gs_outtab TO gt_outtab.
ENDFORM. " FILL_TEXTS
*& Form INIT_CONTROLS
* text
* --> p1 text
* <-- p2 text
FORM init_controls .
CREATE OBJECT go_docking
EXPORTING
parent = cl_gui_container=>screen0
* repid =
* dynnr =
* side = dock_at_left
* extension = 50
* style =
* lifetime = lifetime_default
* caption =
* metric = 0
ratio = 90
* no_autodef_progid_dynnr =
* name =
EXCEPTIONS
cntl_error = 1
cntl_system_error = 2
create_error = 3
lifetime_error = 4
lifetime_dynpro_dynpro_link = 5
OTHERS = 6.
IF sy-subrc <> 0.
* MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
* WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
ENDIF.
CREATE OBJECT go_textedit
EXPORTING
* max_number_chars =
* style = 0
* wordwrap_mode = wordwrap_at_windowborder
* wordwrap_position = -1
* wordwrap_to_linebreak_mode = false
* filedrop_mode = dropfile_event_off
parent = go_docking
* lifetime =
* name =
EXCEPTIONS
error_cntl_create = 1
error_cntl_init = 2
error_cntl_link = 3
error_dp_create = 4
gui_type_not_supported = 5
OTHERS = 6.
IF sy-subrc <> 0.
* MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
* WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
ENDIF.
ENDFORM. " INIT_CONTROLS
*& Form SET_TEXT_EDITOR
* text
* --> p1 text
* <-- p2 text
FORM set_text_editor .
BREAK-POINT.
CLEAR: gs_outtab.
READ TABLE gt_outtab INTO gs_outtab
WITH KEY language = gd_language.
CALL METHOD go_textedit->set_text_as_stream
EXPORTING
text = gs_outtab-text
EXCEPTIONS
error_dp = 1
error_dp_create = 2
OTHERS = 3.
IF sy-subrc <> 0.
* MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
* WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
ENDIF.
ENDFORM. " SET_TEXT_EDITOR
*& Form GET_TEXT_EDITOR
* text
* --> p1 text
* <-- p2 text
FORM get_text_editor .
CLEAR: gs_outtab.
CALL METHOD go_textedit->get_text_as_stream
EXPORTING
only_when_modified = cl_gui_textedit=>true
IMPORTING
text = gs_outtab-text
* is_modified =
EXCEPTIONS
error_dp = 1
error_cntl_call_method = 2
OTHERS = 3.
IF sy-subrc <> 0.
* MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
* WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
ENDIF.
MODIFY gt_outtab FROM gs_outtab
TRANSPORTING text
WHERE ( language = gd_language ).
ENDFORM. " GET_TEXT_EDITOR
Regards
Uwe -
HOW TO DISPLAY THE TEXT ON A PARTICULAR PAGE IN SAPSCRIPTS
HI,
HOW TO DISPLAY THE TEXT ON A PARTICULAR PAGE IN SAPSCRIPTS?in ur script main window
/: IF &TTXSY-PAGE& = 15.
ur text or standard text
/: ENDIF.
use this.
hope it helps if any issues revert back
Maybe you are looking for
-
Okay, so I noticed my lightroom was on 240 PPI resolution. I changed it to 300 because I read 300 was for standard prints. What would I need to set the export to in the resolution box for a very large Canvas? Is it better to choose Tiff instead of Jp
-
Unable to change document through FI_DOCUMENT_CHANGE for second item line
Hi All, I am unable to change document through FM FI_DOCUMENT_CHANGE for second line item (buzei 002). I want to change assignment field(ZUNOR) for second item line.( Please be noted that bseg-koart for this document is maintained a
-
Dear all, I have activated IBAN field in IT0009. Right now we are using bank accounts and bank codes, customized in FI. But starting from summer we have to use IBAN's that replace bank accounts. Thus I have activated this IBAN field in IT0009 - table
-
Ipod not correctly measuring distance
About 3 weeks ago I began having a problem with the Nike+ system not correctly logging my milage. I typically run about 7:40 mile, but recently it has been clocking my runs between 10 & 12 minute miles. I went to a track near my house to calibrate th
-
Instructions for removal of Java 1.7
I forgot to add the PC instructions for the removal of Java 1.7. I need to do this on my Mac, but of course in Mac fashion. Thanks.