Object sorting
Hi,
My poject need the sorting function according to one attribute of a object. but the attribute is varied by the selected list item on the user's interface, and we want to create a common function to this. It's diffcult to me now. can anyone give some advice ?
Thanks in advance.
Regards,
holly_xin,
You could create a set of objects which implement java.util.Comparator, one for each attribute you can search on. This is then passed to your sorting function which can then use any number of sorting methods (e.g. java.util.Arrays.sort()) to sort the objects.
Another option is to use a single Comparator which uses reflection, a case switch or any other other selection mechanism to determine the attribute to sort.
Graeme
Similar Messages
-
How do i create a Object & Sort.
Sorry . This is a post of the same question as the replies on the last thread seems not enough to let me carry on the next step to finish a project.
Firstly => I am creating a ranking page .
The records is record in Summary.txt as followed :
[playername,numberOfAttempts]
bravo1,3
1234567,3
woshibao2,5
This record is as can be seen , first is playername follow by numberOfAttempts.
I am trying to do a Top 10 Ranking base on the[b] LEAST attempts to win will be ranked the highest.
Many people told me that i can use Array[].sort in my previous thread.
However, firstly i will need to break the playerName and numberOfAttempts into 2 parts which is
StringTokenizer st = new StringTokenizer(brInFile.readLine(),",");
String playerName = st.nextToken(); // the use of string tokenizer.
String numberOfAttempts = st.nextToken(); But how do i create a ARRAY / OBJECT that can
SORT base on numberOfAttempts , then get Back the PlayerName and then i will use this information to be display on my ServerView.
Array cannot contain String , when i use StringTokenizer to break my records , by default the output will be string ? How would i able to rank by String or i should maybe convert by Integer.parseInt ?
Sorry , i am quite confused. Hope i can get some help.
[ Hope i can get some codes help or samples ]
i readed the API but i still not sure how to create the Object or etc..
Message was edited by:
baokyFirstly , how do i hold all the datas .
What Object or Array should i use to hold the
playerName and numberOfAttempts.You don't know what a class is?
class Car {
String make;
int yearOfManufacture;
int capacity;
int vin;
// etc
// constructor(s)
// methods
Secondly , i not sure about the "Comparable
Interface" .Read about it in the API. Experiment with some simple test code. If you still don't understand, post your code here and ask a specific question. At the moment you problem is "I want to build a space craft but don't know how. Can you show me?" Way too broad.
Thirdly , how do i write code that determine how i
order the objects.. hahaSimple. You compare the number of attempts and return an appropriate value.
Sorry , i hope someone will post a sample code on
that class :)Nope. It's not our work. It's yours. You write the code.
Sort => Then Obtain back player Name then able to
Display . even on a System.out.printlnwould be fine.Once you have the rest done, do as others have told you, call Arrays.sort which will sort your array for you. You can then loop over the array and print the details. -
ReportDocument object, sort options
I am using Visual Studio 2005, Visual Basic syntax, SqlServer 2000 and CrystalReports XI to build a Windows Forms application. I have a form that allows the user to define criteria for a report which I pass as a parameter to a ReportDocument object. I now want to allow the users to define the sort fields also. But it appears that the sort fields of the object are readonly. Can I define the sort fields of the ReportDocument class in my code?
Well, I thought my question was answered. It was a very good example. But.... I want to allow the users to select more than 1 field to sort by. I have created the following function and it works if I only have 1 item, but it fails on the 2nd item if I have more than 1. Can you sort by more than 1 item? And also, it is breaking to a new page for every new last name (my sort), is there a property I need to set so it does not do that? Thanks for your help.
Private Function lfSort(Byval pSortList As List(Of Miscellaneous3))
'pSortList contains a list of fields that the user wants this report to be sorted by
'the list contains 3 items: 1)Code=the field name as defined in the table 2)Display1=the field name in English, not geek talk 3)Display2=the sort order
Dim lSortFld As String
Dim lSortDir As String
Dim crDatabaseFieldDefinition As DatabaseFieldDefinition
Dim crSortField As SortField
If pSortList.Count > 0 Then
For i As Integer = 0 To pSortList.Count - 1
lSortFld = pSortList(i).Code
If pSortList(i).Display2 = "Desc" Then
lSortDir = SortDirection.DescendingOrder
Else
lSortDir = SortDirection.AscendingOrder
End If
'set the crystal parameters
crDatabaseFieldDefinition = crReportDocument.Database.Tables(0).Fields(lSortFld.ToString)
crSortField = crReportDocument.DataDefinition.SortFields(i)
crSortField.Field = crDatabaseFieldDefinition
crSortField.SortDirection = lSortDir
Next
End If
End Function -
Regarding ArrayList objects sorting
I have number of class instances to be stored in an ArrayList say for example, I have one employee class which has empname,empno,designation as columns.
I am adding this class instances into the ArrayList. I have an another class which has a method sorting() to sort this ArrayList object with 3 parameter . My ArrayList object is the first parameter passed to this
sort() method based on anyof the column names specified as second parameter along with ascending or descending as third parameter my object has to be sorted.
Is there any compatible way to sort the arrayList by the above requirement. Kindly guide us for further proceedings.// Sorting ArrayList of Objects(Emp) based on Date of Birth
import java.util.*;
import java.text.SimpleDateFormat;
public class SortObjects
public void checkData()
ArrayList ar = new ArrayList();
ar.add(new Emp(5, "ram", "13-Sep-2005 03:00:39 PM")); // Date is in String format
ar.add(new Emp(7, "shiva", "27-Oct-2005 09:08:28 AM"));
ar.add(new Emp(1, "raj", "29-Aug-2005 11:15:07 AM"));
ar.add(new Emp(4, "amar", "13-Mar-2005 10:29:18 AM"));
ar.add(new Emp(6, "bhanu", "08-Oct-2005 03:51:34 PM"));
ar.add(new Emp(11, "ramesh", ""));
ar.add(new Emp(2, "gopi", null));
System.out.println("\nBefore Sorting :");
for(int i=0; i<ar.size(); i++)
Emp ob = (Emp) ar.get(i);
System.out.println(ob.toString());
Collections.sort(ar);
System.out.println("\nAfter Sorting :");
for(int i=0; i<ar.size(); i++)
Emp ob = (Emp) ar.get(i);
System.out.println(ob.toString());
public static void main(String args[])
SortObjects ob = new SortObjects();
ob.checkData();
class Emp implements Comparable
private int eno;
private String ename;
private String dob;
public Emp(int eno, String ename, String dob)
this.eno = eno;
this.ename = ename;
this.dob = dob;
public int getEno()
return eno;
public String getEname()
return ename;
public String getDob()
return dob;
public String toString()
return eno + "\t" + ename + "\t" + dob;
public int compareTo(Object ob) throws ClassCastException // Order by Date
Emp temp = (Emp)ob; SimpleDateFormat sdf = new
SimpleDateFormat("dd-MMM-yyyy hh:mm:ss a");
Date date1 = null, date2 = null;
try
if ((dob!=null)&&(!dob.equalsIgnoreCase("")))
date1 = sdf.parse(dob);
if ((temp.dob!=null)&&(!temp.dob.equalsIgnoreCase("")))
date2 = sdf.parse(temp.dob);
catch(Exception e)
{ e.printStackTrace(); }
if ((date1!=null)&&(date2!=null) )
return date2.compareTo(date1);
else
return 0;
/* public int compareTo(Object ob) throws ClassCastException // Order by Employee No.
Emp temp = (Emp)ob;
int enum = eno - temp.eno;
return enum;
} -
Writing a function to that sorts any object
I am trying to write a function that sorts any type of array of objects. For example, I want to call
NewArray = exampleclass.sort(ObjectOfAnyType).
The sort function has to return a new array. I have run into two errors, however.
Error #1
as3.java [21:1] cannot resolve symbol
symbol : variable Object
location: class as3
if (Object instanceof Comparable)
^
Error #2
as3.java [25:1] incompatible types
found : java.lang.Object
required: java.lang.Object[]
Object [] rtn = obj.clone();
*** Below is my source code ***
import java.*;
public class as3 {
/** Creates new as3 */
public static Object sort(Object [] obj)
if (Object instanceof Comparable)
if (Object instanceof Cloneable)
Object [] rtn = obj.clone();
for (int i = 0; i<obj.length-1; i++)
for (int j=i+1; j<obj.length; j++)
if (rtn.compareTo(rtn[j]) == 1)
Object [] tmp = rtn[i];
rtn[i] = obj[j];
rtn[j] = tmp;
else
throw new ObjectIsNotComparableException("Object not comparable");
Any help appreciated. Thanks!Changing from "Object" to the name "obj" fixed the
statement:
if (obj instanceof Cloneable) but not if (obj
instanceof Comparable).
I don't know what's causing this one yet... worry about that in a sec
I am also getting one new error now:
as3.java [28:1] cannot resolve symbol
symbol : method compareTo (java.lang.Object)
location: class java.lang.Object
if (rtn[ i].compareTo(rtn[j])
This one is because rtn[ i] (and rtn[j]) is an Object, which has no method compareTo. Try casting it to a Comparable...
I think I just worked out why it let you go with the cloneable, but not with the comparable. obj is an array, and sure an array is cloneable, but how could you compare an array? Sure you can compare the elements in the array... So either check if obj[0] instanceof Comparable, or drop the test all together.
Note: checking obj[0] will give you an exception if someone asks you to sort an array of 0 length (no elements)
Hope this helps,
Radish21 -
Does anyone know how to take advantage of adf/uix built in sorting for view objects that contain only transient fields? For example, when I build a view object that references an entity object, sorting (via a uix table tag) works great. However, when using a view object with only transient attributes, sorting does not work through a uix table. Any ideas would really be appreciated...
FYI,
I've figured this out for anyone that sees this post in the future. Here's how to do it.
1 Open the transient view object in the view object editor (by double-clicking on the view object).
2 Select Java.
3 Press the Class extends button.
4 For Object, browse to the following class: SortableTransientViewObject (see below for implementation)
5 Press OK.
6 Select Attributes.
7 For each attributes:
1. Select the "Selected in Query" property.
2. Copy the exact name of the attribute to the query column alias field.
8 Press OK.
SortableTransientViewObject implementation:
=============================================================
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import oracle.jbo.Row;
import oracle.jbo.RowSetIterator;
import oracle.jbo.server.ViewObjectImpl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import oracle.jbo.NoDefException;
public class SortableTransientViewObject extends ViewObjectImpl
//flag for determining an invalid column index
public static final int INVALID_COLUMN_INDEX_FLAG = -1;
//default sort to INVALID_COLUMN_INDEX_FLAG
private int sortColumnIndex = INVALID_COLUMN_INDEX_FLAG;
private boolean sortAscending = true;
* Sole constructor. Do not remove.
public SortableTransientViewObject()
* Sets the default sort order. If the order has not been pre-defined, then the
* sort will not be executed when the view object is first created.
* @param sortField the sort field index. Each view object row implementation
* defines these attributes indices as constants. Those values are the values
* that should be used for this method.
* @param sortAscending sort ascending if true; descending otherwise.
public void setDefaultSortOrder( int sortField, boolean sortAscending )
this.setSortColumnIndex( sortField );
this.setSortAscending( sortAscending );
* ADF Framework extension.
* <br>
* This method is called by ADF when a view object is to be refreshed. In
* the case of sorting, this signals that the view object should be sorted.
* The ADF framework will have already called the setOrderByClause() method
* which tells this view object what to sort by.
public void executeQuery()
sort( getSortColumnIndex(), isSortAscending() );
* Over-riding to implement sort for transient view object.
* <br>
* This method will be called by the adf framework whenever a request
* is made to sort the view object through a ui component; most
* likely a table. The orderByClause parameter will always contain
* the sort column and will optionally contain the sort direction.
* <br>
* This method parses the orderByClass parameter and sets the
* corresponding sort index and direction. This method does not perform
* the actual sort; the sort will not take place until the executeQuery()
* method has been invoked.
* @param orderByClause a string representing the sort column and sort
* direction.
public void setOrderByClause( String orderByClause )
if( isNullOrEmpty( orderByClause ) ||
isNullOrEmpty( orderByClause.trim() ))
this.setSortColumnIndex( INVALID_COLUMN_INDEX_FLAG );
this.setSortAscending( true );
return;
else
orderByClause = orderByClause.trim();
boolean sortAscending = true;
String sortColumn = null;
int spaceCharacterIndex = orderByClause.indexOf( ' ' );
if( spaceCharacterIndex == -1 )
sortColumn = orderByClause;
sortAscending = true;
else
sortColumn = orderByClause.substring( 0, spaceCharacterIndex );
String sortDirectionStringValue = orderByClause.substring( spaceCharacterIndex, orderByClause.length() );
if( isNullOrEmpty( sortDirectionStringValue ) ||
isNullOrEmpty( sortDirectionStringValue.trim() ) )
sortAscending = true;
else
sortDirectionStringValue = sortDirectionStringValue.trim();
if( "desc".equals( sortDirectionStringValue.toLowerCase() ) )
sortAscending = false;
try
this.setSortColumnIndex( this.getAttributeIndexOf( sortColumn ) );
catch( NoDefException e )
this.setSortColumnIndex( INVALID_COLUMN_INDEX_FLAG );
this.setSortAscending( sortAscending );
* Sort helper method.
* <br>
* Sorts the view object. Because adf's built in sorting only works for
* non-transient attributes (ie attributes from an entity object), this
* method was created as a framework extension to support sorting.
* <br>
* This method accomplishes sorting by using Java's built in api for
* sorting: the Collections framework. First, all view object rows are
* copied into List object. Second, the list is sorted using Java's built
* in Collections.sort method. Third, all rows are removed from the view
* object and lastly, the view object is re-populated by iterating through
* the list.
* @param sortField the field to sort by.
* @param sortAscending sort ascending if true; descending otherwise.
private void sort( int sortFieldParameter, boolean sortAscendingParameter )
//don't sort if the column index is invalid
if( sortFieldParameter < 0 || sortFieldParameter >= this.getAttributeCount() )
return;
//step 1 - copy all rows to a List object and remove all rows from view object
List list = new LinkedList();
RowSetIterator rowIterator = this.getRowSet().createRowSetIterator( null );
while( rowIterator.hasNext() )
Row rowToAdd = (Row) rowIterator.next();
list.add( rowToAdd );
rowIterator.closeRowSetIterator();
//step 2 - sort the List object.
Collections.sort( list, new ViewObjectRowComparator( sortFieldParameter, sortAscendingParameter ) );
//step 3 - remove all rows from view object
rowIterator = this.getRowSet().createRowSetIterator( null );
while( rowIterator.hasNext() )
rowIterator.next();
rowIterator.removeCurrentRowAndRetain();
rowIterator.closeRowSetIterator();
//step 4 - re-populate the view object with the sorted list.
Iterator sortedValuesIterator = list.iterator();
while( sortedValuesIterator.hasNext() )
Row row = (Row) sortedValuesIterator.next();
this.insertRow( row );
public boolean isSortAscending()
return sortAscending;
private void setSortAscending(boolean sortAscending)
this.sortAscending = sortAscending;
public int getSortColumnIndex()
return sortColumnIndex;
private void setSortColumnIndex(int sortColumnIndex)
this.sortColumnIndex = sortColumnIndex;
============================================================= -
Hi All,
I would like to know the step by step creation of authorization object...
Iam able to create the authorization class and objects using SU21 for a ztable fields..
And am not getting how to use this in ABAP program.
I know using Authority-check we can do this...
Here Iam not understanding to whom we are checking the authorization..and how...
And also is this necessary to create a role in pfcg and assign it to user...
if so what is the necessary to create a role...
and what is the link between SU21 and pfcg...
how this is affecting...
can any one help me...out of this...
thanks and regards
raghuHai Phani
Go through this
For example:
program an AUTHORITY-CHECK.
AUTHORITY-CHECK OBJECT <authorization object>
ID <authority field 1> FIELD <field value 1>.
ID <authority field 2> FIELD <field value 2>.
ID <authority-field n> FIELD <field value n>.
The OBJECT parameter specifies the authorization object.
The ID parameter specifies an authorization field (in the authorization object).
The FIELD parameter specifies a value for the authorization field.
The authorization object and its fields have to be suitable for the transaction. In most cases you will be able to use the existing authorization objects to protect your data. But new developments may require that you define new authorization objects and fields.
go through report
TABLES: TOBJT.
DATA: OBJECT1 LIKE USR12-OBJCT,
OBJECT2 LIKE USR12-OBJCT,
OBJECT3 LIKE USR12-OBJCT,
AUTH1 LIKE USR12-AUTH,
AUTH2 LIKE USR12-AUTH,
AUTH3 LIKE USR12-AUTH,
IND LIKE SY-INDEX,
FLAG TYPE I.
DATA: BEGIN OF INTTAB OCCURS 30,
OBJECT LIKE USR12-OBJCT,
AUTH LIKE USR12-AUTH,
END OF INTTAB.
DATA: BEGIN OF INTTAB2 OCCURS 30,
OBJECT LIKE USR12-OBJCT,
AUTH LIKE USR12-AUTH,
EXPL LIKE TOBJT-TTEXT,
END OF INTTAB2.
DATA: BEGIN OF TABSET OCCURS 30,
SFIELD LIKE TOBJ-FIEL1,
VON(18),
BIS(18),
END OF TABSET.
*read up the authorizations from the user buffer
CALL 'ANALYSE_USERBUFFER'
ID 'AUTHS' FIELD INTTAB-SYS.
*filter out the multipy authorizatios of the same object
SORT INTTAB BY OBJECT.
DO.
IF SY-INDEX = 1.
OBJECT1 = ''. AUTH1 = ''.
READ TABLE INTTAB INDEX 1.
OBJECT2 = INTTAB-OBJECT .AUTH2 = INTTAB-AUTH.
READ TABLE INTTAB INDEX 2.
OBJECT3 = INTTAB-OBJECT.AUTH3 = INTTAB-AUTH.
ELSE.
OBJECT1 = OBJECT2. AUTH1 = AUTH2.
READ TABLE INTTAB INDEX SY-INDEX.
OBJECT2 = INTTAB-OBJECT .AUTH2 = INTTAB-AUTH.
IND = SY-INDEX + 1.
READ TABLE INTTAB INDEX IND.
IF SY-SUBRC = 0.
OBJECT3 = INTTAB-OBJECT.AUTH3 = INTTAB-AUTH.
ELSE.
OBJECT3 = ''. AUTH3 = ''.
IF OBJECT2 = OBJECT1 OR OBJECT2 = OBJECT3.
INTTAB2-OBJECT = OBJECT2.
INTTAB2-AUTH = AUTH2.
SELECT SINGLE * FROM TOBJT
WHERE LANGU = SY-LANGU
AND OBJECT = OBJECT2.
INTTAB2-EXPL = TOBJT-TTEXT.
ENDIF.
EXIT.
ENDIF.
ENDIF.
IF OBJECT2 = OBJECT1 OR OBJECT2 = OBJECT3.
INTTAB2-OBJECT = OBJECT2.
INTTAB2-AUTH = AUTH2.
SELECT SINGLE * FROM TOBJT
WHERE LANGU = SY-LANGU
AND OBJECT = OBJECT2.
INTTAB2-EXPL = TOBJT-TTEXT.
APPEND INTTAB2.
ENDIF.
ENDDO.
SORT INTTAB2 BY OBJECT AUTH.
*display the authorization and description, the objects, fields and
*field values
FLAG = 0. OBJECT1 = ''.
LOOP AT INTTAB2.
IF OBJECT1 = INTTAB2-OBJECT.
WRITE: / INTTAB2-AUTH COLOR 2.
PERFORM FIELD_VALUES.
LOOP AT TABSET.
WRITE: / TABSET-SFIELD, TABSET-VON, TABSET-BIS.
ENDLOOP.
ELSE.
SKIP.
WRITE: / INTTAB2-OBJECT COLOR 3, INTTAB2-EXPL COLOR 3.
PERFORM FIELD_VALUES.
WRITE: / INTTAB2-AUTH COLOR 2.
LOOP AT TABSET.
WRITE: / TABSET-SFIELD, TABSET-VON, TABSET-BIS.
ENDLOOP.
ENDIF.
OBJECT1 = INTTAB2-OBJECT.
ENDLOOP.
FORM FIELD_VALUES *
retrieve the field values of an authorization *
FORM FIELD_VALUES.
TABLES: USR12.
FIELD-SYMBOLS .
DATA: INTFLAG TYPE I VALUE 0, OFF TYPE I, VTYP, LNG TYPE I,
CLNG(2), GLNG(2), FLDLNG TYPE I VALUE 10, SETFILL.
SELECT SINGLE * FROM USR12
WHERE AUTH = INTTAB2-AUTH
AND OBJCT = INTTAB2-OBJECT
AND AKTPS = 'A'.
SETFILL = 0.
REFRESH TABSET.
CLEAR TABSET.
OFF = 2.
ASSIGN USR12-VALS+OFF(1) TO .
WRITE TO VTYP.
WHILE VTYP <> ' ' AND OFF < USR12-LNG.
OFF = OFF + 1.
CASE VTYP.
WHEN 'F'.
OFF = OFF + 5.
ASSIGN USR12-VALS+OFF(2) TO .
WRITE TO CLNG.
LNG = CLNG.
IF LNG <= 0.
EXIT.
ENDIF.
OFF = OFF + 2.
ASSIGN USR12-VALS+OFF(FLDLNG) TO .
WRITE TO TABSET-SFIELD.
OFF = OFF + FLDLNG.
WHEN 'E'.
ASSIGN USR12-VALS+OFF(LNG) TO .
WRITE TO TABSET-VON.
IF TABSET-VON = SPACE.
TABSET-VON = ''' '''.
ENDIF.
APPEND TABSET.
SETFILL = SETFILL + 1.
TABSET-VON = SPACE.
TABSET-BIS = SPACE.
OFF = OFF + LNG.
WHEN 'G'.
ASSIGN USR12-VALS+OFF(2) TO .
WRITE TO CLNG.
GLNG = CLNG.
OFF = OFF + 2.
ASSIGN USR12-VALS+OFF(LNG) TO .
IF INTFLAG = 0.
WRITE TO TABSET-VON.
WRITE '*' TO TABSET-VON+GLNG.
ELSE.
WRITE TO TABSET-BIS.
WRITE '*' TO TABSET-BIS+GLNG.
INTFLAG = 0.
ENDIF.
APPEND TABSET.
SETFILL = SETFILL + 1.
TABSET-VON = SPACE.
TABSET-BIS = SPACE.
OFF = OFF + LNG.
WHEN 'V'.
INTFLAG = 1.
ASSIGN USR12-VALS+OFF(LNG) TO .
WRITE TO TABSET-VON.
IF TABSET-VON = SPACE.
TABSET-VON = ''' '''.
ENDIF.
OFF = OFF + LNG.
WHEN 'B'.
INTFLAG = 0.
ASSIGN USR12-VALS+OFF(LNG) TO .
WRITE TO TABSET-BIS.
IF TABSET-BIS = SPACE.
TABSET-BIS = ''' '''.
ENDIF.
APPEND TABSET.
SETFILL = SETFILL + 1.
TABSET-VON = SPACE.
TABSET-BIS = SPACE.
OFF = OFF + LNG.
ENDCASE.
ASSIGN USR12-VALS+OFF(1) TO .
WRITE TO VTYP.
ENDWHILE.
ENDFORM.
go through this link
http://www.thespot4sap.com/Articles/SAP_ABAP_Queries_Authorizations.asp
also go through this Document
AUTHORITY-CHECK OBJECT object
ID name1 FIELD f1
ID name2 FIELD f2
ID name10 FIELD f10.
Effect
Explanation of IDs:
object Field which contains the name of the object for which the authorization is to be checked.
name1 ... Fields which contain the names of the name10 authorization fields defined in the object.
f1 ... Fields which contain the values for which the f10 authorization is to be checked.
AUTHORITY-CHECK checks for one object whether the user has an authorization that contains all values of f (see SAP authorization concept).
You must specify all authorizations for an object and a also a value for each ID (or DUMMY ).
The system checks the values for the ID s by AND-ing them together, i.e. all values must be part of an authorization assigned to the user.
If a user has several authorizations for an object, the values are OR-ed together. This means that if the CHECK finds all the specified values in one authorization, the user can proceed. Only if none of the authorizations for a user contains all the required values is the user rejected.
If the return code SY-SUBRC = 0, the user has the required authorization and may continue.
The return code is modified to suit the different error scenarios. The return code values have the following meaning:
4 User has no authorization in the SAP System for such an action. If necessary, change the user master record.
8 Too many parameters (fields, values). Maximum allowed is 10.
12 Specified object not maintained in the user master record.
16 No profile entered in the user master record.
24 The field names of the check call do not match those of an authorization. Either the authorization or the call is incorrect.
28 Incorrect structure for user master record.
32 Incorrect structure for user master record.
36 Incorrect structure for user master record.
If the return code value is 8 or possibly 24, inform the person responsible for the program. If the return code value is 4, 12, 15 or 24, consult your system administrator if you think you should have the relevant authorization. In the case of errors 28 to 36, contact SAP, since authorizations have probably been destroyed.
Individual authorizations are assigned to users in their respective user profiles, i.e. they are grouped together in profiles which are stored in the user master record.
Note
Instead of ID name FIELD f , you can also write ID name DUMMY . This means that no check is performed for the field concerned.
The check can only be performed on CHAR fields. All other field types result in 'unauthorized'.
Example
Check whether the user is authorized for a particular plant. In this case, the following authorization object applies:
Table OBJ : Definition of authorization object
M_EINF_WRK
ACTVT
WERKS
Here, M_EINF_WRK is the object name, whilst ACTVT and WERKS are authorization fields. For example, a user with the authorizations
M_EINF_WRK_BERECH1
ACTVT 01-03
WERKS 0001-0003 .
can display and change plants within the Purchasing and Materials Management areas.
Such a user would thus pass the checks
AUTHORITY-CHECK OBJECT 'M_EINF_WRK'
ID 'WERKS' FIELD '0002'
ID 'ACTVT' FIELD '02'.
AUTHORITY-CHECK OBJECT 'M_EINF_WRK'
ID 'WERKS' DUMMY
ID 'ACTVT' FIELD '01':
but would fail the check
AUTHORITY-CHECK OBJECT 'M_EINF_WRK'
ID 'WERKS' FIELD '0005'
ID 'ACTVT' FIELD '04'.
Thanks & regards
Sreenivasulu P -
Somebody pleaes help me for sorting arrays...
Hello.
I have a problem like this. (http://www.sfusd.edu/schwww/sch697/depts/math/simon/ICTJAVA/WebLessons/APCSL27/APCSL27-1-7.html)
public class Item implements Comparable
private int myId;
private int myInv;
public Item(int id, int inv)
myId = id;
myInv = inv;
public int getId(){ )
public int getInv(){ }
public int compareTo(Object otherObject){ }
public boolean equals(Object otherObject){ }
public String toString(){ }
public class Store
private Item[] myStore;
public Store(String fileName) { }
public void displayStore()
public String toString(){ }
public void doSort() { }
private void quickSort(Item[] list, int first, int last)
private void loadFile(String inFileName)
The first line of file50.txt contains the number of id/inventory integer pairs listed on subsequent lines. The idea behind the data type item is the simulation of an item in a store, nearly all of which use a bar code for identification purposes. For every item in a store we keep track of an id value and an inventory amount. So file50.txt looks like this:
50
3679 87
196 60
17914 12
18618 64
2370 65
etc. (for 45 more lines)
Each id value in file50.txt will be unique.
Assignment:
Write a program that solves the following sequential events:
loads the data file, file50.txt, as a collection of Item types maintained in a Store object
sorts the data using quickSort
prints the data , now in increasing order based on the id field of an Item object
The printing should add a blank line after every 10 items in the output. Include a line number in the output. For example:
Id Inv
1 184 14
2 196 60
3 206 31
4 584 85
5 768 85
6 2370 65
7 3433 5
8 3679 87
9 4329 64
10 5529 11
11 6265 58
12 6835 94
13 6992 76
14 7282 73
15 8303 90
16 9267 68
etc.
You will need to complete the getId(), getItem(), compareTo(), equals() and toString() methods for the Item class.
You will need to complete the Store() constructor, displayStore(), loadFile(), quickSort() and toString() methods for the Store class.
That's the assigned project.
this is a side story. I'm a highschooler, and my teacher always hangs out on the internet, teaching nothing. and like this, he just print some problems from the internet and give it to the students. is there a handout about lesson? no. is this always been like this? yeah...
I have no idea how to right a method called getId(), getInv(), etc...
would anybody please... please help me?
p.s.
the file50.txt is
on http://www.sfusd.edu/schwww/sch697/depts/math/simon/ICTJAVA/WebLessons/APCSL27/file50.txt
quicksort is in
http://www.sum-it.nl/QuickSort.java here.
somebody please... help me out...this is a side story. I'm a highschooler, and my
teacher always hangs out on the internet, teaching
nothing. and like this, he just print some problems
from the internet and give it to the students. is
there a handout about lesson? no. is this always been
like this? yeah...
I have no idea how to right a method called getId(),
getInv(), etc...
Well along with the F coming to you for your little assignment I also give you an F for creative writing. This is a shoddy attempt. Why not try something new. Like I live in a mountain town and could not get to school to attend class for three weeks because an avalanche closed the pass.. or my cat peed on my keyboard and I had to get a new one but I couldn't afford it so I don't have enough time left now to figure out myself.
I dunno. Lot's of ideas.
Nobody cares about your little sob story. If your teacher is in fact this bad then you should have taken it up with the school administration long ago. It might not be too late to do so. But truth or not it's not going to sucker somebody in to doing your homework for you.
If you want to learn then do the tutorials until you are capable of completing the assignment. If you have specific questions then help can be given. I don't know what I'm doing is NOT a specific question. -
Somebody please help me for sorting arrays!!
Hello.
I have a problem like this. (http://www.sfusd.edu/schwww/sch697/depts/math/simon/ICTJAVA/WebLessons/APCSL27/APCSL27-1-7.html)
public class Item implements Comparable
private int myId;
private int myInv;
public Item(int id, int inv)
myId = id;
myInv = inv;
public int getId(){ )
public int getInv(){ }
public int compareTo(Object otherObject){ }
public boolean equals(Object otherObject){ }
public String toString(){ }
public class Store
private Item[] myStore;
public Store(String fileName) { }
public void displayStore()
public String toString(){ }
public void doSort() { }
private void quickSort(Item[] list, int first, int last)
private void loadFile(String inFileName)
The first line of file50.txt contains the number of id/inventory integer pairs listed on subsequent lines. The idea behind the data type item is the simulation of an item in a store, nearly all of which use a bar code for identification purposes. For every item in a store we keep track of an id value and an inventory amount. So file50.txt looks like this:
50
3679 87
196 60
17914 12
18618 64
2370 65
etc. (for 45 more lines)
Each id value in file50.txt will be unique.
Assignment:
Write a program that solves the following sequential events:
loads the data file, file50.txt, as a collection of Item types maintained in a Store object
sorts the data using quickSort
prints the data , now in increasing order based on the id field of an Item object
The printing should add a blank line after every 10 items in the output. Include a line number in the output. For example:
Id Inv
1 184 14
2 196 60
3 206 31
4 584 85
5 768 85
6 2370 65
7 3433 5
8 3679 87
9 4329 64
10 5529 11
11 6265 58
12 6835 94
13 6992 76
14 7282 73
15 8303 90
16 9267 68
etc.
You will need to complete the getId(), getItem(), compareTo(), equals() and toString() methods for the Item class.
You will need to complete the Store() constructor, displayStore(), loadFile(), quickSort() and toString() methods for the Store class.
That's the assigned project.
this is a side story. I'm a highschooler, and my teacher always hangs out on the internet, teaching nothing. and like this, he just print some problems from the internet and give it to the students. is there a handout about lesson? no. is this always been like this? yeah...
I have no idea how to right a method called getId(), getInv(), etc...
would anybody please... please help me?
p.s.
the file50.txt is
on http://www.sfusd.edu/schwww/sch697/depts/math/simon/ICTJAVA/WebLessons/APCSL27/file50.txt
quicksort is in
http://www.sum-it.nl/QuickSort.java here.
somebody please... help me out...well you're really going to have to at least do a quick skim of:
http://java.sun.com/docs/books/tutorial/getStarted/index.html
And also how to use a browser and browse the API Docs
especially for: Comparable
You'll also get flamed for just posting a Homework assignment with no evidence of your own attempts to solve it, OR for not formatting the code with
[ c o d e ] [ / c o d e ]
I suppose you get some points if you answer some of the questions?
Try the easy parts first:
Complete the methods of the class Item
Ignore the deliberate Typos in the assignment
see how you have the class members defined already like:
private int myId; // The guy couldn't be bothered to document his code
private int myInv; // So you will have to.......document itlook at this:
public int getId() {}As it is the compiler will just say : Missing method body, or declare abstract...
Your job is to guess what it should do from the 'signature'
It must return an int and that should be related to Id neh?
So try things like:
@return the value of the myId field.
public int getId()
return this.myId; // return myId would do as well
Sets the value of myId field
@param newId the new Id to set.
public void setId( int newId )
this.myId = newId; // the old value is replaced with the new
}do the rest of the simple obvious methods.
You will get some marks and improve your confidence with simple Java
Read The API doc on Comparable Interface:
Decide Carefully how you want to "Order" Objects of type Item.
In this case this will probably depend first on myId and then subsequently on myInv
The Comparable interface helps Sorting methods decide qhich object comes first when sorting.
you will need ssomething like this.
Implements Comparable - Read the API
public int compareTo( Object o ) throws ClassCastException, NullPointerException
if( o == null )
throw new NullPointerException("Blah blah blah");
if( !( o instanceof Item ) )
throw new ClassCastException("Apples and Oranges!");
Item item = ( Item ) o; // Cast o to an Item so it can be checked
if( this.getId() < item.getId() )
return -1; // Signal that "this"is less than o
if ( this.getId() > item.getId() )
return 1;
// here both items have the same myId field
if( this.getInv() < item .getInv() )
return -1;
if( this.getInv() > item.getInv() )
return 1;
return 0; // they are at the same sort order
}You use that method like:
Item a;
Item b;
if( a.compareTo( b ) < 0 )
//blah blah
}To write the equals method read the API it is similar to compareTo()
To Read The file : Search on this forum for reading a file line by line.
Check the API.
ALso if you have installed Java:
There are many examples of how to do this in the demo directory
Even one on QuickSort ---
So plug away.................. -
JTable header : text = two-rows, onClick action = sorting
Hi guys.
I want to create a JTable where the user can have the data sorted by clicking upon a column's header. The code below shows the table I describe (you can click upon a column and sorting is performed).
import javax.swing.JFrame;
import java.awt.HeadlessException;
import java.awt.*;
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.Vector;
import javax.swing.table.DefaultTableModel;
//--------- TableSorter ----------
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.List;
import javax.swing.*;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.*;
//---------- Table Height - Column Width
import javax.swing.table.TableColumn;
import java.awt.FontMetrics;
import javax.swing.JTable;
import java.awt.Dimension;
* <p>Title: </p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2006</p>
* <p>Company: </p>
* @author not attributable
* @version 1.0
public class Test extends JFrame {
JPanel jPanel1 = new JPanel();
JPanel jPanel2 = new JPanel();
JButton jButton1 = new JButton();
FlowLayout flowLayout1 = new FlowLayout();
BorderLayout borderLayout1 = new BorderLayout();
BorderLayout borderLayout2 = new BorderLayout();
//------------- MY VARIABLES -------------
String[] columnNames_objectArr = new String[] {
"Col1",
"Column 2",
"Column 3",
"C4",
"Col5",
"Col 6",
Vector columnNames_vector = new Vector();
private Vector data_vector = new Vector();
private Object[][] data_objectArr;
public TableHeight_ColumnWidth tcw;
private int totalTableWidth = 0, totalTableHeight = 0;
private JComboBox jcmbxData = new JComboBox(
new String[] {"Not Configured", "Switch", "Modem"});
private int maxVisibleRows = 51;
TableSorter model;
private JTable table;
JScrollPane jScrollPane1;
public Test(String[] args) throws HeadlessException {
try {
jbInit();
setupGUI();
launchGUI();
catch(Exception e) {
e.printStackTrace();
private void jbtnClose_actionPerformed(ActionEvent e) {
dispose();
private void launchGUI() {
pack();
setVisible(true);
setResizable(false);
private void setupGUI() {
columnNames_vector.addElement("Col1");
columnNames_vector.addElement("Column 2");
columnNames_vector.addElement("Column 3");
columnNames_vector.addElement("C4");
columnNames_vector.addElement("Col5");
columnNames_vector.addElement("Col 6");
Vector row_data1 = new Vector();
Vector row_data2 = new Vector();
Vector row_data3 = new Vector();
Vector row_data4 = new Vector();
Vector row_data5 = new Vector();
Vector row_data6 = new Vector();
row_data1.add("Mary");
row_data1.add("Campioneato");
row_data1.add("Snowboarding");
row_data1.add(new Integer(578987899));
row_data1.add(new Boolean(false));
row_data1.add("Not Configured");
row_data2.add("Alison");
row_data2.add("Huml");
row_data2.add("Rowing");
row_data2.add(new Integer(3));
row_data2.add(new Boolean(true));
row_data2.add("Switch");
row_data3.add("Ka");
row_data3.add("Walrath");
row_data3.add("Knitting");
row_data3.add(new Integer(2));
row_data3.add(new Boolean(false));
row_data3.add("Modem");
row_data4.add("Sharon");
row_data4.add("Zakhouras");
row_data4.add("Speed reading");
row_data4.add(new Integer(20));
row_data4.add(new Boolean(true));
row_data4.add("Switch");
row_data5.add("Philip");
row_data5.add("Milner");
row_data5.add("Pool");
row_data5.add(new Integer(10));
row_data5.add(new Boolean(false));
row_data5.add("Not Configured");
data_vector.add(row_data1);
data_vector.add(row_data2);
data_vector.add(row_data3);
data_vector.add(row_data4);
data_vector.add(row_data5);
model = new TableSorter(new SortTableModel(data_vector, columnNames_vector));
table = new JTable(model);
tcw = new TableHeight_ColumnWidth(model, table);
jScrollPane1 = new JScrollPane(table);
model.setTableHeader(table.getTableHeader());
jPanel1.add(jScrollPane1, BorderLayout.CENTER);
//Add a JComboBox as a cellEditor...
DefaultCellEditor dce = new DefaultCellEditor(jcmbxData);
table.getColumnModel().getColumn(5).setCellEditor(dce);
//..... add the IPJPanel as cellEditor.....
tcw.fixTableLook(maxVisibleRows);
private void jbInit() throws Exception {
this.getContentPane().setLayout(borderLayout2);
jPanel1.setLayout(borderLayout1);
jPanel2.setLayout(flowLayout1);
jButton1.setText("Close");
jPanel1.setBorder(BorderFactory.createRaisedBevelBorder());
this.getContentPane().add(jPanel1, BorderLayout.CENTER);
this.getContentPane().add(jPanel2, BorderLayout.SOUTH);
jPanel2.add(jButton1, null);
jButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jbtnClose_actionPerformed(e);
public static void main( String[] args ) {
new Test(args);
public boolean getScrollableTracksViewportHeight() {
Component parent = getParent();
if (parent instanceof JViewport) {
return parent.getHeight() > getPreferredSize().height;
return false;
//------------------ MY TABLE MODEL ------------------
public class SortTableModel extends DefaultTableModel {
private boolean DEBUG = false;
public SortTableModel(Object[][] data, String[] columnNames) {
super(data, columnNames);
public SortTableModel(Vector data, Vector columnNames) {
super(data, columnNames);
//------------------ TABLE SORTER -----------------------
public class TableSorter extends AbstractTableModel {
protected TableModel tableModel;
public static final int DESCENDING = -1;
public static final int NOT_SORTED = 0;
public static final int ASCENDING = 1;
private Directive EMPTY_DIRECTIVE = new Directive(-1, NOT_SORTED);
public final Comparator COMPARABLE_COMAPRATOR = new Comparator() {
public int compare(Object o1, Object o2) {
return ((Comparable) o1).compareTo(o2);
public final Comparator LEXICAL_COMPARATOR = new Comparator() {
public int compare(Object o1, Object o2) {
return o1.toString().compareTo(o2.toString());
private Row[] viewToModel;
private int[] modelToView;
private JTableHeader tableHeader;
private MouseListener mouseListener;
private TableModelListener tableModelListener;
private Map columnComparators = new HashMap();
private List sortingColumns = new ArrayList();
public TableSorter() {
this.mouseListener = new MouseHandler();
this.tableModelListener = new TableModelHandler();
public TableSorter(TableModel tableModel) {
this();
setTableModel(tableModel);
public TableSorter(TableModel tableModel, JTableHeader tableHeader) {
this();
setTableHeader(tableHeader);
setTableModel(tableModel);
private void clearSortingState() {
viewToModel = null;
modelToView = null;
public TableModel getTableModel() {
return tableModel;
public void setTableModel(TableModel tableModel) {
if (this.tableModel != null) {
this.tableModel.removeTableModelListener(tableModelListener);
this.tableModel = tableModel;
if (this.tableModel != null) {
this.tableModel.addTableModelListener(tableModelListener);
clearSortingState();
fireTableStructureChanged();
public JTableHeader getTableHeader() {
return tableHeader;
public void setTableHeader(JTableHeader tableHeader) {
if (this.tableHeader != null) {
this.tableHeader.removeMouseListener(mouseListener);
TableCellRenderer defaultRenderer = this.tableHeader.getDefaultRenderer();
if (defaultRenderer instanceof SortableHeaderRenderer) {
this.tableHeader.setDefaultRenderer(((SortableHeaderRenderer) defaultRenderer).tableCellRenderer);
this.tableHeader = tableHeader;
if (this.tableHeader != null) {
this.tableHeader.addMouseListener(mouseListener);
this.tableHeader.setDefaultRenderer(
new SortableHeaderRenderer(this.tableHeader.getDefaultRenderer()));
public boolean isSorting() {
return sortingColumns.size() != 0;
private Directive getDirective(int column) {
for (int i = 0; i < sortingColumns.size(); i++) {
Directive directive = (Directive)sortingColumns.get(i);
if (directive.column == column) {
return directive;
return EMPTY_DIRECTIVE;
public int getSortingStatus(int column) {
return getDirective(column).direction;
private void sortingStatusChanged() {
clearSortingState();
fireTableDataChanged();
if (tableHeader != null) {
tableHeader.repaint();
public void setSortingStatus(int column, int status) {
Directive directive = getDirective(column);
if (directive != EMPTY_DIRECTIVE) {
sortingColumns.remove(directive);
if (status != NOT_SORTED) {
sortingColumns.add(new Directive(column, status));
sortingStatusChanged();
protected Icon getHeaderRendererIcon(int column, int size) {
Directive directive = getDirective(column);
if (directive == EMPTY_DIRECTIVE) {
return null;
return new Arrow(directive.direction == DESCENDING, size, sortingColumns.indexOf(directive));
private void cancelSorting() {
sortingColumns.clear();
sortingStatusChanged();
public void setColumnComparator(Class type, Comparator comparator) {
if (comparator == null) {
columnComparators.remove(type);
} else {
columnComparators.put(type, comparator);
protected Comparator getComparator(int column) {
Class columnType = tableModel.getColumnClass(column);
Comparator comparator = (Comparator) columnComparators.get(columnType);
if (comparator != null) {
return comparator;
if (Comparable.class.isAssignableFrom(columnType)) {
return COMPARABLE_COMAPRATOR;
return LEXICAL_COMPARATOR;
private Row[] getViewToModel() {
if (viewToModel == null) {
int tableModelRowCount = tableModel.getRowCount();
viewToModel = new Row[tableModelRowCount];
for (int row = 0; row < tableModelRowCount; row++) {
viewToModel[row] = new Row(row);
if (isSorting()) {
Arrays.sort(viewToModel);
return viewToModel;
public int modelIndex(int viewIndex) {
return getViewToModel()[viewIndex].modelIndex;
private int[] getModelToView() {
if (modelToView == null) {
int n = getViewToModel().length;
modelToView = new int[n];
for (int i = 0; i < n; i++) {
modelToView[modelIndex(i)] = i;
return modelToView;
// TableModel interface methods
public int getRowCount() {
return (tableModel == null) ? 0 : tableModel.getRowCount();
public int getColumnCount() {
return (tableModel == null) ? 0 : tableModel.getColumnCount();
public String getColumnName(int column) {
return tableModel.getColumnName(column);
public Class getColumnClass(int column) {
return tableModel.getColumnClass(column);
public boolean isCellEditable(int row, int column) {
return tableModel.isCellEditable(modelIndex(row), column);
public Object getValueAt(int row, int column) {
return tableModel.getValueAt(modelIndex(row), column);
public void setValueAt(Object aValue, int row, int column) {
tableModel.setValueAt(aValue, modelIndex(row), column);
// Helper classes
private class Row implements Comparable {
private int modelIndex;
public Row(int index) {
this.modelIndex = index;
public int compareTo(Object o) {
int row1 = modelIndex;
int row2 = ((Row) o).modelIndex;
for (Iterator it = sortingColumns.iterator(); it.hasNext();) {
Directive directive = (Directive) it.next();
int column = directive.column;
Object o1 = tableModel.getValueAt(row1, column);
Object o2 = tableModel.getValueAt(row2, column);
int comparison = 0;
// Define null less than everything, except null.
if (o1 == null && o2 == null) {
comparison = 0;
} else if (o1 == null) {
comparison = -1;
} else if (o2 == null) {
comparison = 1;
} else {
comparison = getComparator(column).compare(o1, o2);
if (comparison != 0) {
return directive.direction == DESCENDING ? -comparison : comparison;
return 0;
private class TableModelHandler implements TableModelListener {
public void tableChanged(TableModelEvent e) {
// If we're not sorting by anything, just pass the event along.
if (!isSorting()) {
clearSortingState();
fireTableChanged(e);
return;
// If the table structure has changed, cancel the sorting; the
// sorting columns may have been either moved or deleted from
// the model.
if (e.getFirstRow() == TableModelEvent.HEADER_ROW) {
cancelSorting();
fireTableChanged(e);
return;
// We can map a cell event through to the view without widening
// when the following conditions apply:
// a) all the changes are on one row (e.getFirstRow() == e.getLastRow()) and,
// b) all the changes are in one column (column != TableModelEvent.ALL_COLUMNS) and,
// c) we are not sorting on that column (getSortingStatus(column) == NOT_SORTED) and,
// d) a reverse lookup will not trigger a sort (modelToView != null)
// Note: INSERT and DELETE events fail this test as they have column == ALL_COLUMNS.
// The last check, for (modelToView != null) is to see if modelToView
// is already allocated. If we don't do this check; sorting can become
// a performance bottleneck for applications where cells
// change rapidly in different parts of the table. If cells
// change alternately in the sorting column and then outside of
// it this class can end up re-sorting on alternate cell updates -
// which can be a performance problem for large tables. The last
// clause avoids this problem.
int column = e.getColumn();
if (e.getFirstRow() == e.getLastRow()
&& column != TableModelEvent.ALL_COLUMNS
&& getSortingStatus(column) == NOT_SORTED
&& modelToView != null) {
int viewIndex = getModelToView()[e.getFirstRow()];
fireTableChanged(new TableModelEvent(TableSorter.this,
viewIndex, viewIndex,
column, e.getType()));
return;
// Something has happened to the data that may have invalidated the row order.
clearSortingState();
fireTableDataChanged();
return;
private class MouseHandler extends MouseAdapter {
public void mouseClicked(MouseEvent e) {
JTableHeader h = (JTableHeader) e.getSource();
TableColumnModel columnModel = h.getColumnModel();
int viewColumn = columnModel.getColumnIndexAtX(e.getX());
int column = columnModel.getColumn(viewColumn).getModelIndex();
if (column != -1) {
int status = getSortingStatus(column);
if (!e.isControlDown()) {
cancelSorting();
// Cycle the sorting states through {NOT_SORTED, ASCENDING, DESCENDING} or
// {NOT_SORTED, DESCENDING, ASCENDING} depending on whether shift is pressed.
status = status + (e.isShiftDown() ? -1 : 1);
status = (status + 4) % 3 - 1; // signed mod, returning {-1, 0, 1}
setSortingStatus(column, status);
private class Arrow implements Icon {
private boolean descending;
private int size;
private int priority;
public Arrow(boolean descending, int size, int priority) {
this.descending = descending;
this.size = size;
this.priority = priority;
public void paintIcon(Component c, Graphics g, int x, int y) {
Color color = c == null ? Color.GRAY : c.getBackground();
// In a compound sort, make each succesive triangle 20%
// smaller than the previous one.
int dx = (int)(size/2*Math.pow(0.8, priority));
int dy = descending ? dx : -dx;
// Align icon (roughly) with font baseline.
y = y + 5*size/6 + (descending ? -dy : 0);
int shift = descending ? 1 : -1;
g.translate(x, y);
// Right diagonal.
g.setColor(color.darker());
g.drawLine(dx / 2, dy, 0, 0);
g.drawLine(dx / 2, dy + shift, 0, shift);
// Left diagonal.
g.setColor(color.brighter());
g.drawLine(dx / 2, dy, dx, 0);
g.drawLine(dx / 2, dy + shift, dx, shift);
// Horizontal line.
if (descending) {
g.setColor(color.darker().darker());
} else {
g.setColor(color.brighter().brighter());
g.drawLine(dx, 0, 0, 0);
g.setColor(color);
g.translate(-x, -y);
public int getIconWidth() {
return size;
public int getIconHeight() {
return size;
private class SortableHeaderRenderer implements TableCellRenderer {
private TableCellRenderer tableCellRenderer;
public SortableHeaderRenderer(TableCellRenderer tableCellRenderer) {
this.tableCellRenderer = tableCellRenderer;
public Component getTableCellRendererComponent(JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column) {
Component c = tableCellRenderer.getTableCellRendererComponent(table,
value, isSelected, hasFocus, row, column);
if (c instanceof JLabel) {
JLabel l = (JLabel) c;
l.setHorizontalTextPosition(JLabel.LEFT);
int modelColumn = table.convertColumnIndexToModel(column);
l.setIcon(getHeaderRendererIcon(modelColumn, l.getFont().getSize()));
return c;
private class Directive {
private int column;
private int direction;
public Directive(int column, int direction) {
this.column = column;
this.direction = direction;
//-------------- FIX TABLE'S HEIGHT & COLUMN WIDTH ---------
public class TableHeight_ColumnWidth {
private TableSorter sorter;
private FontMetrics fm;
private JTable table;
private int numOfRows = 0, totalTableHeight = 0, totalTableWidth = 0;
* Constructor --- it needs the model as well the JTable as parameters
* @param sorter - the model
* @param table - the JTable created based on the model
public TableHeight_ColumnWidth(TableSorter sorter, JTable table) {
this.sorter = sorter;
this.table = table;
this.fm = table.getFontMetrics(table.getFont());
this.numOfRows = table.getRowCount();
* Calculates the width of each column according to the String it contains
* @param col = the desired column
* @param fm = the FontMetrics of this column
* @return - the width of the single column
public int determineColumnWidth(TableColumn col, FontMetrics fm) {
int headerWidth = fm.stringWidth((String)col.getHeaderValue());
int columnNumber = col.getModelIndex();
int max = headerWidth;
int columnWidth = 0;
String cell = "";
Integer cell_int = new Integer(0);
Short cell_short = new Short((short)0);
for (int i = 0; i != sorter.getRowCount(); i++) {
Object obj = (Object) sorter.getValueAt(i, columnNumber);
if (obj instanceof String) {
cell = (String)sorter.getValueAt(i, columnNumber);
else if (obj instanceof Integer) {
cell_int = (Integer)sorter.getValueAt(i, columnNumber);
cell = String.valueOf(cell_int.intValue());
else if (obj instanceof Short) {
cell_short = (Short) sorter.getValueAt(i, columnNumber);
cell = String.valueOf(cell_short.shortValue());
columnWidth = fm.stringWidth(cell) + 5;
if (columnWidth > max) {
max = columnWidth;
return max + 5;
* Calculates the total width of the table according to the width of each
* column.
* @return - totalTableWidth
private int fixColumnWidth () {
int totalTableWidth = 0;
TableColumn c = null;
int cw = 0;
for (int i = 0; i < table.getColumnCount(); i++) {
c = table.getColumn(table.getColumnName(i));
cw = this.determineColumnWidth(c, fm);
c.setPreferredWidth(cw);
totalTableWidth = totalTableWidth + cw;
c.setMinWidth(cw);
return totalTableWidth;
* Calculates the height of the table according to the height of each row
* multiplied by 51 (by default) or by the totalRowsCount.
* @return - totalTableHeight
private int fixTableHeight(int maxVisibleRows) {
int rowHeight = table.getRowHeight();
//Show maxVisibleRows rows maximum
if (numOfRows > maxVisibleRows) {
totalTableHeight = rowHeight * maxVisibleRows;
else {
totalTableHeight = rowHeight * numOfRows;
return totalTableHeight;
* Sets up the table according to the totalTableWidth and totalTableHeight
public void fixTableLook(int maxVisibleRows) {
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
totalTableWidth = this.fixColumnWidth();
totalTableHeight = this.fixTableHeight(maxVisibleRows);
table.setPreferredScrollableViewportSize(new Dimension(totalTableWidth, totalTableHeight));
}Also, I want some column headers to display their text in two-rows. But by using the HTML technique look at the result in comparison with the previous table I had!
import javax.swing.JFrame;
import java.awt.HeadlessException;
import java.awt.*;
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.Vector;
import javax.swing.table.DefaultTableModel;
//--------- TableSorter ----------
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.List;
import javax.swing.*;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.*;
//---------- Table Height - Column Width
import javax.swing.table.TableColumn;
import java.awt.FontMetrics;
import javax.swing.JTable;
import java.awt.Dimension;
* <p>Title: </p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2006</p>
* <p>Company: </p>
* @author not attributable
* @version 1.0
public class Test extends JFrame {
JPanel jPanel1 = new JPanel();
JPanel jPanel2 = new JPanel();
JButton jButton1 = new JButton();
FlowLayout flowLayout1 = new FlowLayout();
BorderLayout borderLayout1 = new BorderLayout();
BorderLayout borderLayout2 = new BorderLayout();
//------------- MY VARIABLES -------------
String[] columnNames_objectArr = new String[] {
"Col1",
"Column 2",
"Column 3",
"C4",
"Col5",
"Col 6",
Vector columnNames_vector = new Vector();
private Vector data_vector = new Vector();
private Object[][] data_objectArr;
public TableHeight_ColumnWidth tcw;
private int totalTableWidth = 0, totalTableHeight = 0;
private JComboBox jcmbxData = new JComboBox(
new String[] {"Not Configured", "Switch", "Modem"});
private int maxVisibleRows = 51;
TableSorter model;
private JTable table;
JScrollPane jScrollPane1;
public Test(String[] args) throws HeadlessException {
try {
jbInit();
setupGUI();
launchGUI();
catch(Exception e) {
e.printStackTrace();
private void jbtnClose_actionPerformed(ActionEvent e) {
dispose();
private void launchGUI() {
pack();
setVisible(true);
setResizable(false);
private void setupGUI() {
columnNames_vector.addElement("<html>Col1</html>");
columnNames_vector.addElement("<html>Column 2</html>");
columnNames_vector.addElement("<html>Column 3<br>Second Row</html>");
columnNames_vector.addElement("<html>C4</html>");
columnNames_vector.addElement("<html>Col5</html>");
columnNames_vector.addElement("<html>Col 6</html>");
Vector row_data1 = new Vector();
Vector row_data2 = new Vector();
Vector row_data3 = new Vector();
Vector row_data4 = new Vector();
Vector row_data5 = new Vector();
Vector row_data6 = new Vector();
row_data1.add("Mary");
row_data1.add("Campioneato");
row_data1.add("Snowboarding");
row_data1.add(new Integer(578987899));
row_data1.add(new Boolean(false));
row_data1.add("Not Configured");
row_data2.add("Alison");
row_data2.add("Huml");
row_data2.add("Rowing");
row_data2.add(new Integer(3));
row_data2.add(new Boolean(true));
row_data2.add("Switch");
row_data3.add("Ka");
row_data3.add("Walrath");
row_data3.add("Knitting");
row_data3.add(new Integer(2));
row_data3.add(new Boolean(false));
row_data3.add("Modem");
row_data4.add("Sharon");
row_data4.add("Zakhouras");
row_data4.add("Speed reading");
row_data4.add(new Integer(20));
row_data4.add(new Boolean(true));
row_data4.add("Switch");
row_data5.add("Philip");
row_data5.add("Milner");
row_data5.add("Pool");
row_data5.add(new Integer(10));
row_data5.add(new Boolean(false));
row_data5.add("Not Configured");
data_vector.add(row_data1);
data_vector.add(row_data2);
data_vector.add(row_data3);
data_vector.add(row_data4);
data_vector.add(row_data5);
model = new TableSorter(new SortTableModel(data_vector, columnNames_vector));
table = new JTable(model);
tcw = new TableHeight_ColumnWidth(model, table);
jScrollPane1 = new JScrollPane(table);
model.setTableHeader(table.getTableHeader());
jPanel1.add(jScrollPane1, BorderLayout.CENTER);
//Add a JComboBox as a cellEditor...
DefaultCellEditor dce = new DefaultCellEditor(jcmbxData);
table.getColumnModel().getColumn(5).setCellEditor(dce);
//..... add the IPJPanel as cellEditor.....
tcw.fixTableLook(maxVisibleRows);
private void jbInit() throws Exception {
this.getContentPane().setLayout(borderLayout2);
jPanel1.setLayout(borderLayout1);
jPanel2.setLayout(flowLayout1);
jButton1.setText("Close");
jPanel1.setBorder(BorderFactory.createRaisedBevelBorder());
this.getContentPane().add(jPanel1, BorderLayout.CENTER);
this.getContentPane().add(jPanel2, BorderLayout.SOUTH);
jPanel2.add(jButton1, null);
jButton1.addActionListener(new ActionListener() {
First of all I found out that when I set the column's header like this:
columnNames_vector.addElement("<html>Column 3<br>Second Row</html>"); //In the setupGUI() methodthe TableHeight_ColumnWidth.determineColumnWidth(TableColumn col, FontMetrics fm) method calculates the column's width by counting <html>, </html>, <br> characters as well. So I added a check to reject these characters and not count them for the column's width.
As for the header's height:
I found that when the first column's header is set to display two-lines, then the height of the rest columns headers is set to display two-lines as well. In other words, the height of the first column's header affects the height of the whole JTableHeader.
I found that the BasicTableHeaderUI.getHeaderHeight() method is called, within which there are these comments:
// If the header value is empty (== "") in the
// first column (and this column is set up
// to use the default renderer) we will
// return zero from this routine and the header
// will disappear altogether. Avoiding the calculation
// of the preferred size is such a performance win for
// most applications that we will continue to
// use this cheaper calculation, handling these
// issues as `edge cases'. Should I override a class and if so which one? I am so confused! If anyone has any idea about how to set the header's height according to the cell's height that is the maximum among all, please let me know. -
Appending data in ranges object
hi,
i have a ranges field i want to append the land data in
ranges object.sort table itab by vbeln posnr.
read table itab index 1.
ranges-low = itab-vbeln.
clear itab.
describe table itab lines w_line.
read table itab index w_line.
ranges-high = itab-vbeln.
ranges-sign = 'I'.
ranges-option = 'BT'.
append ranges.
This is surely help u.
Re: Moving DATA from Internal Table to Ranges -
"Bounce" objects in Motion 5?
Hey everyone,
I am trying to make an intro like this one: http://www.youtube.com/watch?v=7yVM3fGiJrs
And I was wondering how you could make the objects sort of "bounce" instead of just coming to a stop.
The obvious answer it just to keyframe it going further up than you want it and then keyframe it going back down, but I don't think that would be a very convincing bounce.
Any help is appreciated!
Thanks,
Adam
Founder of YouTube channel techBowker: http://www.youtube.com/channel/UC08-qHFLK_Oc7h1O-AAxlOw?feature=guideGroup the objects that will bounce together. Add a Gravity Behavior to their group. Enclose that group in another group (select the group and type Command Shift G). Add an Edge Collision behavior to the "parent" group. Adjust the Height parameter to bring the bounce off the bottom edge of the canvas (if needed.) Adjust the Bounce Strength to about 40%. Adjust the Acceleration of the Gravity behavior to around 1000 (to start) and move the bouncing group above the canvas by about twice the distance it needs to travel (you might have to slide the behavior starts to before the start of the project to assist in timing the "entry" of the bouncing objects into the "scene"; and extend the out points of the behaviors to the end of the project so once the objects come to "rest", they'll stay in place.) Edge Collision + Gravity can provide a quite realistic bounce effect.
-
Sorting properties from get-mailbox on a single mailbox, how?
get-aduser username -Properties * gives a nicely sorted list of the properties for a user's AD account.
get-mailbox username | fl * gives a nicely
unsorted list of the properties for a user's Exchange mailbox.
Anything more elegant for sorting the get-mailbox output?
Get-Mailbox username | fl * | Out-File -FilePath c:\username-mailbox.txt
Get-Content C:\username-mailbox.txt | sort
What is the technical terminology for the type of output produced by get-mailbox username?
Thank you for your time, Joe
-JoeHear ya Bill. But I'm only returning a single PSObject (Microsoft.Exchange.Data.Directory.Management.MailEnabledOrgPerson), and I'm attempting to sort the properties on the single object. Sorry I'm not explaining this well.
Example Output from: get-mailbox
Name Alias ServerName
ProhibitSendQuota
kcarael kcarael svrwmail unlimited
cuqt3 cuqt3 svrwmail unlimited
lsren lsren exchange03 unlimited
roreerb roreerb exchange03 unlimited
pacffsdfs pacffsdfs exchange03
unlimited
beon beon exchange03 unlimited
Not a problem to sort: get-mailbox | sort alias
Output from: get-mailbox someuser
Name Alias ServerName
ProhibitSendQuota
someuser someuser mbxn04 12.6 GB (13,529,147,392 bytes)
Example Output from: get-mailbox someuser | fl * (or get-mailbox someuser | Select-Object *)
RoleAssignmentPolicy : Default Role Assignment Policy
SharingPolicy : Default Sharing Policy
RemoteAccountPolicy :
MailboxPlan :
ArchiveDatabase : EX-DAG01-DB08
ArchiveGuid : 587bdddd-f651-4e11-87d0-88ae31dc24db
ArchiveQuota : 50 GB (53,687,091,200 bytes)
ArchiveWarningQuota : 45 GB (48,318,382,080 bytes)
ArchiveDomain :
ArchiveStatus : None
RemoteRecipientType : None
DisabledArchiveDatabase :
DisabledArchiveGuid : 00000000-0000-0000-0000-000000000000
QueryBaseDNRestrictionEnabled : False
MailboxMoveTargetMDB :
MailboxMoveSourceMDB :
MailboxMoveFlags : None
MailboxMoveRemoteHostName :
MailboxMoveBatchName :
MailboxMoveStatus : None
IsPersonToPersonTextMessagingEnabled : False
IsMachineToPersonTextMessagingEnabled : True
UserSMimeCertificate : {}
I'm not sure what to sort on... I've tried just: get-mailbox someuser | Select-Object * | sort
The output looks the same as output from: get-aduser someuser
This doesn't work either: get-aduser someuser | sort -descending
Thank you, Joe
-Joe -
Hi,
i have a JComboBox containing list of Strings
so lets say:
String[] test = {"omega", "alpha", "beta", "Arc"}
JComboBox testing = new JComboBox(test);
now is there a way to sort the elements inside the JComboBox once they have been inserted ? or anyone know how to sort the elements before putting them in inside JComboBox ?
the sample code was just for testing and I am dealing with MANY elements (at least 10) inside the JComboBox
thanks in advance
if you have any links that helps with this topic, I will also appreciate it<hmm>
1) Check out the [url http://java.sun.com/docs/books/tutorial/collections/index.html]Collections API
2) Note that using a java.util.Vector, (which combo box accepts in its constructor), allows you to do
one of two things:
............If you are using a custom object, have it implement Comparable
............If you are using flat Strings, never mind...
Then calling java.util.Collections.sort(myVector) would do this for you. NOTE: by not implementing
Comparable, this may have undesirable results....
A number of collection objects sort by default when you add an element..... -
Online test questions... plz provide answers
How can we copy a standard table to make our own z_table?
By using the copy option in SE11.
By using include structure command.
By using Append structure command.
By Copying the entire structure of the standard table in our new table.
In reporting tell me all the events in a sequentail order
1- Initialization.
2- At Selection-Screen
3- Start-of-Selection.
4- Top-of-Page.
5- AT PF-Status
6- End-of-Page.
7- End-of-Selection.
1, 2, 3, 4, 5, 6, 7.
1, 2, 3, 7, 4, 6, 5.
1, 2, 3, 7, 4, 5, 6.
1, 2, 3, 6, 4, 5, 7.
Can we create an ABAP program without using Y or Z?
YES
NO
Which is not a dml statement in sap?
Update.
Append.
Insert.
Delete.
What are different data types in ABAP/4?
Userdefined TYPES.
User defined TYPES as well as C,D,F,I,N,P,T,X.
C,D,F,I,N,P,T,X only
Only SAP defined types.
What are the types of tables?
Transparent table, Pool table and cluster table, Data dictionary table objects sorted table, indexed table and hash table.
All of the options
Transparent table, Pool table and cluster table.
Data dictionary table objects sorted table, indexed table and hash table.
When is top of the page event triggered?
Whenever a new page is triggered
After excuteing first write statement in start-of-selection event.
In all the cases.
Immediately after the End of selection
Command 'SUM' would add fields of type N,I only.
False
True
What is the system field for getting present date?
sy-tabix.
sy-datum.
sy-pageno.
sy-index.
What is the difference between internal and external subroutines?
Internal subroutines are SAP defined RFCs and External subroutines are Non SAP defined RFCs
It is the same.
External subroutines are used in Non SAP programs.
Internal subroutines are what are declared inside the program and external subroutines are what are declared outside the program and referred from outside the program.
How can we create field without data element?
By directly referring to type of the field.
We will not be able to create field without a data element
By using direct type option in SE11
By using Data element option in SE11.
What is the purpose of SM30?
SM30 is a table maintanance for the custom tables as well as database tables.
None of the options.
Transaction to create custom table.
SM30 is a table maintanance for the custom tables created by us.
What is the difference between selection screen elements and text elements?
Selection screen elements can only be used for the purpose of display names in selection screen wheareas text elements are reusable and dynamic text definition which can be used across the program.
Text elements are static whereas selection screen elements are dynamic
Both can be used to define a text definition and can be used in the entire program.
Selection screen elements can only be used for the purpose of display names in selection screen wheareas text elements are reusable and dynamic text definition which can be used across the program other than selection screen.
Local Variables cab be used in the whole program but not outside the program it is defined.
True
False
What is the different between clear and refresh?
Clear is used to clear the work area whereas Refresh to clear the contents of database or internal table.
Clear is used to clear the header content whereas Refresh is used to clear the contents of internal tables.
Both does the same.
Depending on the internal table declaration, either clear or refresh is used.
How many indexes can be created for a table?
9
1
As many as required.
4
How to access the logic coded in a program other than the one you are coding in?
By using SUBMIT command.
All of the options are valid.
By using CALL PROGRAM command.
By using INCLUDE command
What is data class?
The data class specifies in which table space the table is created in database.
All of the options.
The data class specifies what table type is created in database.
The data class specifies what size table is created in database.
For concatenating variables, variables must be of type..
Character or String only.
Variables of all types can be concatenated.
Character type only.
String only.
<b> ASSURE REWARD FOR ANSWERS </b>
THANK YOUhi rajesh,
How can we copy a standard table to make our own z_table?
By using the copy option in SE11. -
>
By using include structure command.
By using Append structure command.
By Copying the entire structure of the standard table in our new table.
In reporting tell me all the events in a sequentail order
1- Initialization.
2- At Selection-Screen
3- Start-of-Selection.
4- Top-of-Page.
5- AT PF-Status
6- End-of-Page.
7- End-of-Selection.
1, 2, 3, 4, 5, 6, 7.
1, 2, 3, 7, 4, 6, 5. -
>
1, 2, 3, 7, 4, 5, 6.
1, 2, 3, 6, 4, 5, 7.
Can we create an ABAP program without using Y or Z?
YES
NO -
>
Which is not a dml statement in sap?
Update.
Append.----
>
Insert.
Delete.
What are different data types in ABAP/4?
Userdefined TYPES.
User defined TYPES as well as C,D,F,I,N,P,T,X.
C,D,F,I,N,P,T,X only -
> not sure
Only SAP defined types.
What are the types of tables?
Transparent table, Pool table and cluster table, Data dictionary table objects sorted table, indexed table and hash table.
All of the options
Transparent table, Pool table and cluster table. -
>
Data dictionary table objects sorted table, indexed table and hash table.
When is top of the page event triggered?
Whenever a new page is triggered -
>
After excuteing first write statement in start-of-selection event.
In all the cases.
Immediately after the End of selection
Command 'SUM' would add fields of type N,I only.
False -
>
True
What is the system field for getting present date?
sy-tabix.
sy-datum. -
>
sy-pageno.
sy-index.
What is the difference between internal and external subroutines?
Internal subroutines are SAP defined RFCs and External subroutines are Non SAP defined RFCs
It is the same.
External subroutines are used in Non SAP programs.
Internal subroutines are what are declared inside the program and external subroutines are what are declared outside the program and referred from outside the program.----
>
How can we create field without data element?
By directly referring to type of the field.
We will not be able to create field without a data element
By using direct type option in SE11 -
>
By using Data element option in SE11.
What is the purpose of SM30?
SM30 is a table maintanance for the custom tables as well as database tables. -
>
None of the options.
Transaction to create custom table.
SM30 is a table maintanance for the custom tables created by us.
What is the difference between selection screen elements and text elements?
Selection screen elements can only be used for the purpose of display names in selection screen wheareas text elements are reusable and dynamic text definition which can be used across the program. -
>
Text elements are static whereas selection screen elements are dynamic
Both can be used to define a text definition and can be used in the entire program.
Selection screen elements can only be used for the purpose of display names in selection screen wheareas text elements are reusable and dynamic text definition which can be used across the program other than selection screen.
Local Variables cab be used in the whole program but not outside the program it is defined.
True -
>
False
What is the different between clear and refresh?
Clear is used to clear the work area whereas Refresh to clear the contents of database or internal table.
Clear is used to clear the header content whereas Refresh is used to clear the contents of internal tables. -
>
Both does the same.
Depending on the internal table declaration, either clear or refresh is used.
How many indexes can be created for a table?
9
1
As many as required. -
>
4
How to access the logic coded in a program other than the one you are coding in?
By using SUBMIT command. -
>
All of the options are valid.
By using CALL PROGRAM command.
By using INCLUDE command
What is data class?
The data class specifies in which table space the table is created in database. -
> not sure
All of the options.
The data class specifies what table type is created in database.
The data class specifies what size table is created in database.
For concatenating variables, variables must be of type..
Character or String only.
Variables of all types can be concatenated.
Character type only. -
>
String only.
Regards,
Guna..
Maybe you are looking for
-
Nano 6th gen, can I sync with iphone & how many times can I download music
Hi, I'm new to this, so I'm sorry if I make a mistake... I'm getting an nano 6th generation and I wondered if I can use the itunes I've bought for my iphone and music downloaded or if I have to start from scratch? Also, if I use the music can I use
-
My PC(s) no longer recognize my iPad2. Can't backup or sync.
First, a problem started 3 days ago when I got an error message "can't find server" in the email app. I finally decided to delete and reinstall the account, but when I went to backup I discovered a deeper problem. iTunes could see and sync with my
-
I keep getting a script error on yahoo mail. the page freezes up and loads and loads.
I can sign into Yahoo okay. It happens when I try to sign out the page won't let me sign out. So I minimize the page and tried to delete the cookies and cache. It hangs on forever deleting history. And I get a script error message.
-
Hello experts! I'm trying to create a maintenance transaction in my solution manager for my enterprise portal system (based on netweaver 7.3) *The system was registered automatically in SLD at installation *In SMSY I have this structure Product Syst
-
Hi, I use private browsing mode and when I try to adjust the settings to never remember history, whenever I look it always reverts to use custom settings. Sometimes when I close firefox and then reopen the old cookies are still there.