I have to limit the number of rows in a JTable. If I have 100 records I need to display 10 on the initial loading of JTable. I wish to put a button like "next", and after each click it shows another set of 10 records.
I have to limit the number of rows in a JTable. If i have 100 records i need to display 10 on the initial loading of JTable.
Use preferred size (+ an appropriate layout and layout constraint) to fix the size.
I wish to put a button like "next", and after each click it showing another set of 10 records.
Remove the scroll bar on the RHS of the scroll pane. Then use buttons instead for the effect of 'next/previous'.
Like this
FixedRowsTable.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
class FixedRowsTable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
String[] columns = {"1","2","3","4","5","6","7"};
Integer[][] data = new Integer[1000][columns.length];
for (int xx=0; xx<data.length; xx++) {
for (int yy=0; yy<data[0].length; yy++) {
data[xx][yy] = new Integer((xx+1)*(yy+1));
}
}
final int rows = 11;
JPanel gui = new JPanel(new BorderLayout(3,3));
final JTable table = new JTable(
new DefaultTableModel(data, columns));
final JScrollPane scrollPane = new JScrollPane(
table,
JScrollPane.VERTICAL_SCROLLBAR_NEVER,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
Dimension d = table.getPreferredSize();
scrollPane.setPreferredSize(
new Dimension(d.width,table.getRowHeight()*rows));
JPanel navigation = new JPanel(
new FlowLayout(FlowLayout.CENTER));
JButton next = new JButton(">");
next.addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent ae) {
int height = table.getRowHeight()*(rows-1);
JScrollBar bar = scrollPane.getVerticalScrollBar();
bar.setValue( bar.getValue()+height );
}
} );
JButton previous = new JButton("<");
previous.addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent ae) {
int height = table.getRowHeight()*(rows-1);
JScrollBar bar = scrollPane.getVerticalScrollBar();
bar.setValue( bar.getValue()-height );
}
} );
navigation.add(previous);
navigation.add(next);
gui.add(scrollPane, BorderLayout.CENTER);
gui.add(navigation, BorderLayout.SOUTH);
JOptionPane.showMessageDialog(null, gui);
}
});
}
}
If you use an AbstractTableModel you can display millions of records. The idea is that your model will be loading whatever records are needed for the view, on demand.
Here you have such a Model. It's not my best code, but will do :-) ...
public class SomeTableModel extends AbstractTableModel {
public SomeTableModel(ResultSet rs) {
this.rs = rs;
try {
pos = this.rs.getRow();
System.out.println(String.valueOf(pos));
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
public int getRowCount() {
int cnt = 0;
int apos = 0;
try {
apos = rs.getRow();
rs.last();
cnt = rs.getRow();
if (apos > 0)
rs.absolute(apos);
} catch (SQLException ex) {
System.out.println("getRowCount: " + ex);
}
return cnt;
}
public int getColumnCount() {
return 3;
}
public Object getValueAt(int rowIndex, int columnIndex) {
// make it jump back to pos !!
Object val = null;
Integer intVal;
try {
if (rowIndex == 0) {
pos = rs.getRow();
total = getRowCount();
}
rs.absolute(rowIndex + 1);
switch (columnIndex) {
case 0: intVal = rs.getInt(1); val = intVal; break;
case 1: val = rs.getString(2); break;
case 2: val = rs.getString(3); break;
default: val = "error";
}
rs.absolute(pos);
} catch (SQLException sqle) {
JOptionPane.showMessageDialog(null, "Trouble in model");
}
return val;
}
private ResultSet rs;
private int pos, total;
}
If you are loading the data from a database table, I think the best way to go is to limit the data coming from the database. Then apply a simple algorithm for the next and previous buttons.
Related
I want to adjust the size of a particular cell in JTable so that it should auto set itself when the size of text is greater than some size. This is how I am adding content to my table.
if(rs.next()) {
rs.beforeFirst();
Vector<String> columnNames = new Vector<String>();
columnNames.add("Tweet");
columnNames.add("Updated Time");
Vector<Vector<Object>> data = new Vector<Vector<Object>>();
while (rs.next()) {
Vector<Object> vector = new Vector<Object>();
Tweet = rs.getString(1);
vector.add(Tweet);
SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Timestamp time = rs.getTimestamp(2);
Updated_time = sdf.format(time);
vector.add(Updated_time);
data.add(vector);
}
DefaultTableModel dfm = new DefaultTableModel(data, columnNames);
JTable table = new JTable(dfm);
table.setAutoscrolls(true);
table.setShowGrid(false);
((DefaultTableCellRenderer)table.getDefaultRenderer(Object.class)).setOpaque(false);
table.setOpaque(false);
public class MyRenderer extends JTextArea implements TableCellRenderer {
private static final long serialVersionUID = 1L;
public MyRenderer() {
setLineWrap(true);
setWrapStyleWord(true);
setOpaque(true);
}
#Override
public Component getTableCellRendererComponent(
JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row, int column
) {
// TODO Auto-generated method stub
setText(value.toString());//or something in value, like value.getNote()..
if (isSelected) {
setForeground(table.getSelectionForeground());
setBackground(table.getSelectionBackground());
} else {
setForeground(table.getForeground());
setBackground(table.getBackground());
}
setSize(table.getColumnModel().getColumn(column).getWidth(),
getPreferredSize().height);
if (table.getRowHeight(row) != getPreferredSize().height) {
table.setRowHeight(row, getPreferredSize().height);
}
return this;
}
}
JTable cell actually is showing JLabel, so for text wrapping you can apply html like:
"<html>" + "Your value" + "<br>" + "Desc"
I am developing a desktop application in java swing; in which I need to take a bill print on dot matrix printer, the print will be having name, address and table which will be having item, qty, price…etc, which should be printed as per their x, y positions on paper, font stored in database .
But in print there is issue of overlapping/attaching letters if I use the following code:
class BillPrint implements ActionListener, Printable
{
PrintMngt PM=new PrintMngt();
public int print(Graphics gx, PageFormat pf, int page) throws PrinterException {
if (page>0){return NO_SUCH_PAGE;}
Graphics2D g = (Graphics2D)gx; //Cast to Graphics2D object
g.translate(pf.getImageableX(), pf.getImageableY());
Vector<Vector<Object>> data =PM.getvarientDetail(printID);
for (int i = 0; i <data.size(); i++) {
if(data.get(i).get(3).toString().equalsIgnoreCase("DYNAMIC"))
{
String bill_no=textField_Trans.getText();
int TblH,TblL;
Vector<String> Tbl_HL=PM.getTblHieghtNoLline(printID);
//PRINT_ID0, QUERY_STATIC1, OBJECT_NAME2, QUERY_TYPE3, X4, Y5, WIDTH6,
//ALIGN7, FONT8, F_SIZE9, F_STYLE10, SECTION11, LOOPES_NO12, OBJ_FORMAT13, VARIANT_ID14
TblH=Integer.parseInt(Tbl_HL.get(0).toString());
TblL=Integer.parseInt(Tbl_HL.get(1).toString());
int x=Integer.parseInt(data.get(i).get(4).toString());
int y=Integer.parseInt(data.get(i).get(5).toString());
String fName=data.get(i).get(8).toString();
int fSize=Integer.parseInt(data.get(i).get(9).toString());
String fStyle=data.get(i).get(10).toString();
Font font=null;
if(fStyle.equalsIgnoreCase("Plain"))
{
font = new Font(fName,Font.PLAIN, fSize);
}
else if(fStyle.equalsIgnoreCase("Bold"))
{
font = new Font(fName,Font.BOLD, fSize);
}
else if(fStyle.equalsIgnoreCase("Italic"))
{
font = new Font(fName,Font.ITALIC, fSize);
}
else if(fStyle.equalsIgnoreCase("Bold Italic"))
{
font = new Font(fName,Font.BOLD+ Font.ITALIC, fSize);
}
System.out.println("Myqry"+data.get(i).get(1).toString());
Vector<String> Query_Static=PM.getQuery_Static(data.get(i).get(1).toString(),bill_no);
for (int j = NoOfProd; j < Query_Static.size(); j++) {
g.drawString(Query_Static.get(j).toString(),x,y);
y=y+TblH/TblL;
g.setFont(font);
}
}
}
return PAGE_EXISTS; //Page exists (offsets start at zero!)
}
public void actionPerformed(ActionEvent e) {
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintable(this);
boolean ok = job.printDialog();
if (ok) {
try {
int ProductCnt= PM.getNoProduct(textField_Trans.getText().toString());//no. of products under given billno
int TableLine=PM.getTblNoLline(printID);//no. of lines to print
System.out.println("No of TableLines="+TableLine);
System.out.println("No of Product="+ProductCnt);
for (int i = 0; i <(TableLine/ProductCnt); i++)
{
job.print();
NoOfProd=NoOfProd+TableLine;
}
NoOfProd=0;
} catch (PrinterException ex) {
ex.printStackTrace();
}
}
}//end actionPerformed
}//end BillPrint
I have also tried with writing data to .txt file and then printing it. Here output is proper i.e letters are not overlapping , but here in this method I m not able to give proper positions for my data. Following method I used for this:
private void printData(){
File output = new File("E:\\PrintFile1.txt");
output.setWritable(true);
String billNo="B1000", patient = "ABC";
try
{
BufferedWriter out = new BufferedWriter(new FileWriter(output));
out.write(billNo + "\n");
out.write(patient + "\n" );
out.write("\n");
out.write("\n");
out.close();
}
catch (java.io.IOException e)
{
System.out.println("Failed to write Output");
}
FileInputStream textStream = null;
try
{
textStream = new FileInputStream("E:\\PrintFile1.txt");
}
catch (java.io.FileNotFoundException e)
{
System.out.println("Error trying to find the print file.");
}
DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
Doc mydoc = new SimpleDoc(textStream, flavor, null);
PrintService printer = PrintServiceLookup.lookupDefaultPrintService();
DocPrintJob printJob = printer.createPrintJob();
try
{
printJob.print(mydoc, null);
}
catch (javax.print.PrintException e)
{
JOptionPane.showMessageDialog(this, "Error occured while attempting to print.", "Error!", JOptionPane.ERROR_MESSAGE);
}
}
Basically for the issue in the letters i just add one space for each character in the string
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
public class Print implements Printable {
/* Just add one space for all charaters */
String numero = "Numero Nro :";
String numeroreplace = numero.replaceAll(".(?=.)", "$0 ");
public Print() {
super();
}
/* The font for you string */
public int print(Graphics g,PageFormat pf, int page) throws PrinterException{
Font textFont = new Font(Font.SANS_SERIF,Font.PLAIN,8);
/* To set the position, you can use for or while if u need it. */
g.setFont(textFont);
g.drawString(numeroreplace,350,150);
}
}
Finally you need to copy all this code just add one space for all characters in code.
Note : you must be call from yor main program.
I have problem when trying to fetch the data from database and display in database. I get from user input and store as a search variable. This is how I set up my table:
//I get the user input to perform search
#FXML
public void searchResident(ActionEvent event){
String search=getTb_search().getText();
if(search.equals("")){
Dialogs.showErrorDialog(null, "Please enter something", "Blank fields detected", "");
}else{
setUpSearchTable(search);
}
}
//How I set up my table
public void setUpSearchTable(String search) {
TableColumn rmNameCol = new TableColumn("Name");
rmNameCol.setVisible(true);
rmNameCol.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<SearchNeedyResidentController, String>, ObservableValue<String>>() {
public ObservableValue<String> call(TableColumn.CellDataFeatures<SearchNeedyResidentController, String> p) {
return p.getValue().searchNameProperty();
}
});
TableColumn rmNricCol = new TableColumn("NRIC");
rmNricCol.setCellValueFactory(new PropertyValueFactory<SearchNeedyResidentController, String>("search_nric"));
rmNricCol.setMinWidth(150);
TableColumn rmPhNoCol = new TableColumn("Phone Number");
rmPhNoCol.setCellValueFactory(new PropertyValueFactory<SearchNeedyResidentController,String>("search_phNo"));
rmPhNoCol.setMinWidth(350);
TableColumn rmIncomeCol = new TableColumn("Income($)");
rmIncomeCol.setCellValueFactory(new PropertyValueFactory<SearchNeedyResidentController, String>("search_income"));
rmIncomeCol.setMinWidth(100);
ResidentManagement.entity.NeedyResidentEntity searchValue= new ResidentManagement.entity.NeedyResidentEntity();
//viewProduct.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
table_search.setEditable(false);
table_search.getColumns().addAll(rmNricCol, rmNameCol, rmIncomeCol, rmPhNoCol);
table_search.getItems().setAll(searchValue.searchResident(search));
}
}
//How I populate the table data
public List<SearchNeedyResidentController> searchResident(String search){
List ll = new LinkedList();
try {
DBController db = new DBController();
db.getConnection();
String sql = "SELECT * FROM rm_needyresident WHERE name LIKE '" + search + "%'";
ResultSet rs = null;
// Call readRequest to get the result
rs = db.readRequest(sql);
while (rs.next()) {
String nric=rs.getString("nric");
String name = rs.getString("name");
double income = rs.getDouble("familyIncome");
String incomeStr = new DecimalFormat("##.00").format(income);
String phNo = rs.getString("phNo");
SearchNeedyResidentController row = new SearchNeedyResidentController();
row.setSearchNric(nric);
row.setSearchName(name);
row.setSearchIncome(incomeStr);
row.setSearchPhNo(phNo);
ll.add(row);
}
rs.close();
} catch (SQLException ex) {
ex.printStackTrace();
System.out.println("Error SQL!!!");
System.exit(0);
} catch (Exception e) {
e.printStackTrace();
}
return ll;
}
}
When search button is on click, the table column is displayed. However, it's just show a blank table even though there's matching result. I debug already and I think the error is at the retrieving data in the searchResident method. It's not retriving the data from database. Anybody know what's wrong?
Thanks in advance.
try dis one...
#FXML private void SearchButton()
{
Connection c ;
datamem = FXCollections.observableArrayList();
try
{
c = Dao.getCon();
String SQL =SELECT * FROM `Member`;
ResultSet rs = c.createStatement().executeQuery(SQL);
if(table.getColumns().isEmpty())
{
for(int i=0 ; i<rs.getMetaData().getColumnCount(); i++)
{
final int j = i;
TableColumn col = new TableColumn(rs.getMetaData().getColumnName(i+1));
col.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList,String>,ObservableValue<String>>(){
public ObservableValue<String> call(TableColumn.CellDataFeatures<ObservableList, String> param) {
return new SimpleStringProperty(param.getValue().get(j).toString());
}
});
table.getColumns().addAll(col);
}//for
}//if
while(rs.next())
{
ObservableList<String> row = FXCollections.observableArrayList();
for(int i=1 ; i<=rs.getMetaData().getColumnCount(); i++)
{
row.add(rs.getString(i));
}// for
datamem.add(row);
}//while
table.setItems(datamem);
}//try
catch(Exception e)
{
JOptionPane.showMessageDialog(null, "Problem in Search Button "+e);
}
}//else
}//else
} //search method
This question already has answers here:
BaseAdapter class wont setAdapter inside Asynctask - Android
(4 answers)
Closed 9 years ago.
I am trying to create my own arrayAdapter so I can place multiple textviews inside of a listview. I have searched everywhere and can not find a way to do it. I am new to this and not so sure how to handle it. So far I have an asynctask that gathers 3 strings in a JSON method. These strings are what I want placed in the textViews but I have no idea how to do so, here is my current code.
class loadComments extends AsyncTask<JSONObject, String, JSONObject> {
private ArrayAdapter<String> mAdapter = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
}
protected JSONObject doInBackground(JSONObject... params) {
JSONObject json2 = CollectComments.collectComments(usernameforcomments, offsetNumber);
return json2;
}
#Override
protected void onPostExecute(JSONObject json2) {
try {
if (json2.getString(KEY_SUCCESS) != null) {
registerErrorMsg.setText("");
String res2 = json2.getString(KEY_SUCCESS);
if(Integer.parseInt(res2) == 1){
JSONArray commentArray = json2.getJSONArray(KEY_COMMENT);
final String comments[] = new String[commentArray.length()];
for ( int i=0; i<commentArray.length(); i++ ) {
comments[i] = commentArray.getString(i);
}
JSONArray numberArray = json2.getJSONArray(KEY_NUMBER);
String numbers[] = new String[numberArray.length()];
for ( int i=0; i<numberArray.length(); i++ ) {
numbers[i] = numberArray.getString(i);
}
JSONArray usernameArray = json2.getJSONArray(KEY_USERNAME);
String usernames[] = new String[usernameArray.length()];
for ( int i=0; i<usernameArray.length(); i++ ) {
usernames[i] = usernameArray.getString(i);
}
ArrayList<String> myList = new ArrayList<String>();
class MyClassAdapter extends ArrayAdapter<String> {
private Context context;
public MyClassAdapter(Context context, int textViewResourceId, ArrayList<String> items) {
super(context, textViewResourceId, items);
this.context = context;
}
public View getView(int position, View convertView) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.list_item, null);
}
String item = getItem(position);
if (item!= null) {
// My layout has only one TextView
TextView commentView = (TextView) view.findViewById(R.id.listComment);
TextView usernameView = (TextView) view.findViewById(R.id.listPostedBy);
TextView NumberView = (TextView) view.findViewById(R.id.listNumber);
// do whatever you want with your string and long
commentView.setText(comments);
NumberView.setText(numbers);
usernameView.setText(usernames);
}
return view;
}
}
}//end if key is == 1
else{
// Error in registration
registerErrorMsg.setText(json2.getString(KEY_ERROR_MSG));
}//end else
}//end if
} //end try
catch (JSONException e) {
e.printStackTrace();
}//end catch
}
}
new loadComments().execute();
This code does not work but I think I am on the right track.
Let us say, you create a class that hold your information about the comments instead of creating three related Arrays :
class Commentary
{
public String username;
public String comment;
public int commentaryIndex;
}
The BaseAdapter can take a List as a parameter whereas the ArrayAdapter wouldn't.
class MyRealAdapter extends BaseAdapter
{
private List<Commentary> comments;
public MyRealAdapter(List<Commentary> comments )
{
this.comments = comments;
}
#Override
public int getCount() {
return comments.size();
}
#Override
public Object getItem(int index) {
return comments.get(index);
}
#Override
public long getItemId(int index) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Commentary c = (Commentary) getItem(position);
//c.username, c.comment, c.commentaryIndex
// create the view and stuff
return null;
}
}
As you can see, you again have the getView method but now you can retrieve your complete objet and not just a String.
There is a couple more method to override, but as you can see it's very simple.
You might need to pass other argument like a Context or a LayoutInflater to the constructor, but it's not mandatory.
EDIt :
JSONArray commentArray = json2.getJSONArray(KEY_COMMENT);
JSONArray numberArray = json2.getJSONArray(KEY_NUMBER);
JSONArray usernameArray = json2.getJSONArray(KEY_USERNAME);
ArrayList<Commentary> comments = new ArrayList<commentary>();
for ( int i=0; i<commentArray.length(); i++ ) {
Commentary c = new Commentary();
c.username = usernameArray.getString(i);
c.comment = commentArray.getString(i);
c.commentaryIndex = Integer.parseInt(numberArray.getString(i));
comments.add(c);
}
MyRealAdapter adapter = new MyRealAdapter(comments);
Hi I am currently doing my final year project; I need to develop an algorithm visualization tool. I need to cater for user-defined algo; that is animate the algorithm the user types in a text-editor provided in my tool.
I am using the Java Compiler API to compile the code that the user has typed and saved. My tool offers a set of classes that the user can use in his/her algo.
For example:
myArray(this class is provided by my tool)
import java.awt.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.accessibility.AccessibleContext;
import javax.swing.*;
public class myArray extends JComponent {
int size = 0;
int count = 0;
int[]hold;
Thread th;
public myArray(int[]arr)//pass user array as parameter
{
//th = new Thread();
size=arr.length;
hold = arr;//make a copy of the array so as to use later in swap operation
}
public int length()
{
return hold.length;
}
public void setAccessibleContext(AccessibleContext accessibleContext) {
this.accessibleContext = accessibleContext;
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
this.setPreferredSize(new Dimension(360,100));
for(int i=1; i<=size; i++)
{
g2d.drawRect((i*30), 30, 30, 50);
}
for(int i=1; i<=size; i++)
{
g2d.drawString(Integer.toString(hold[i-1]), (i*30)+15, 30+25);
}
}
public void set(int i, int j)//position of the two elements to swap in the array
{
try {
th.sleep(2000);//sleep before swapping because else user won't see original array since it would swap and then sleep
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int temp = hold[i];
hold[i] = hold[j];
hold[j] = temp;
hold[i]=j;
this.repaint();//can use eapint with a class that extends JPanel
}
public void swap(int i, int j)//position of the two elements to swap in the array
{
try {
th.sleep(2000);//sleep before swapping because else user won't see original array since it would swap and then sleep
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int temp = hold[i];
hold[i] = hold[j];
hold[j] = temp;
this.repaint();//can use eapint with a class that extends JPanel
}
public int get(int pos)
{
return hold[pos];
}
}
This is a portion of my GUI that will cause the compilation:
JavaCompiler jc = null;
StandardJavaFileManager sjfm = null;
File javaFile = null;
String[] options = null;
File outputDir = null;
URL[] urls = null;
URLClassLoader ucl = null;
Class clazz = null;
Method method = null;
Object object = null;
try
{
jc = ToolProvider.getSystemJavaCompiler();
sjfm = jc.getStandardFileManager(null, null, null);
File[] files = new File[1];
//files[0] = new File("C:/Users/user/Documents/NetBeansProjects/My_Final_Year_Project/myArray.java");
//files[1] = new File("C:/Users/user/Documents/NetBeansProjects/My_Final_Year_Project/Tool.java");
files[0] = new File("C:/Users/user/Documents/NetBeansProjects/My_Final_Year_Project/userDefined.java");
// getJavaFileObjects’ param is a vararg
Iterable fileObjects = sjfm.getJavaFileObjects(files);
jc.getTask(null, sjfm, null, null, null, fileObjects).call();
// Add more compilation tasks
sjfm.close();
options = new String[]{"-d", "C:/Users/user/Documents/NetBeansProjects/My_Final_Year_Project"};
jc.getTask(null, sjfm, null, Arrays.asList(options), null, fileObjects).call();
outputDir = new File("C:/Users/user/Documents/NetBeansProjects/My_Final_Year_Project");
urls = new URL[]{outputDir.toURL()};
ucl = new URLClassLoader(urls);
clazz = ucl.loadClass("userDefined");
method = clazz.getMethod("user", null);
object = clazz.newInstance();
Object ob = method.invoke(object, null);
}
This is an example of a user-defined algo(userDefined.java):
import java.awt.*;
import javax.swing.*;
public class userDefined
{
public void user()
{
int [] numArr = {1,3,1,-1,5,-5,0,7,12,-36};
myArray myArray = new myArray(numArr);
JFrame frame = new JFrame("Rectangles");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setSize(360, 300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.add(myArray);
for (int i=myArray.length(); i>1; i--)
{
for (int j=0; j<i-1; j++)
{
if (myArray.get(j) > myArray.get(j+1))
{
myArray.swap(j, j+1);
}
}
}
}
}
The problem I am getting is that if I try to use reflection like above; I only get a white window which does not show the animation) but just displays the result at the very end.
However if I use this instead of reflection(and change the method void user() to static void main(string args) in userDefined.java):
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
if(compiler.run(null, null, null, "userDefined.java") != 0) {
System.err.println("Could not compile.");
System.exit(0);
}
try {
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("java "+"userDefined");
BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line=null;
while((line=input.readLine()) != null) {
System.out.println(line);
}
} catch(Exception e) {
System.out.println(e.toString());
e.printStackTrace();
it woks provided that after first compilation I place the myArray class in the same folder as the userDefined.java. In this case I can see the animation take place correctly.
How do I use reflection to invoke the main method instead of using an instance of the class.
Please I really need some help with this. Thanks!
You a violating / missusing the first rule of swing: acces swing components only in the EDT (Event Dispatch Thread).
When you start your program using the main method, you are violating that rule. This happens to work, but might have all kinds of weird effects. This is not a theoretic warning, it happend to me and it is not nice.
When you run it using reflection from your code, you are most likely in the EDT, so your algorithm runs completely before the GUI gets updated again (which also happens on the EDT). Thats why you see only the final result of the algorithm.
The correct way to do this would be:
Run the algorithm in a seperate thread and make sure all changes to your myArray Component happen in the EDT, using SwingUtilities.invokeAndWait or SwingUtilities.invokeLater