?
Solved

Right-alignment of numeric cell

Posted on 2006-05-14
6
Medium Priority
?
472 Views
Last Modified: 2008-03-10
Hi,

I am writing a spreadsheet application, If I type a text it is "left-aligned" which is OK. but if I type a number in the text, I want it to be shown as "right-aligned", could someone help me with that part?
Here is my code:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.table.*;
import java.util.*;
import javax.swing.event.*;

class  tableExample implements ActionListener, TableModelListener
{
JFrame frame;
JTable table;
Vector rows,columns;
DefaultTableModel tabModel;
JScrollPane scrollPane;
JLabel lblMessage;
JButton cmdOpen,cmdSave,cmdNew,cmdAdd,cmdDelete,cmdSetValue,cmdGetValue;
JPanel mainPanel,buttonPanel;


   public static void main(String[] args)
    {
tableExample t=new tableExample();
    }

tableExample()
{
rows=new Vector();
columns= new Vector();
String[] columnNames =
{
"A",
"B",
"C",
"D",
"E",
"F",
"G"
};
addColumns(columnNames);

tabModel=new DefaultTableModel();
tabModel.setDataVector(rows,columns);

table = new JTable(tabModel);
scrollPane= new JScrollPane(table);//ScrollPane

table.setRowSelectionAllowed(false);

table.getModel().addTableModelListener(this);

lblMessage=new JLabel("");


buttonPanel=new JPanel();
cmdOpen=new JButton("Open File");
cmdSave=new JButton("Save File");
cmdNew=new JButton("New File");
cmdAdd=new JButton("Add Row");
cmdDelete=new JButton("Delete") ;
cmdSetValue=new JButton("Set Value");
cmdGetValue=new JButton("Get Value");

buttonPanel.add(cmdOpen);
buttonPanel.add(cmdSave);
buttonPanel.add(cmdNew);
buttonPanel.add(cmdAdd);
buttonPanel.add(cmdDelete);
buttonPanel.add(cmdSetValue);
buttonPanel.add(cmdGetValue);

cmdOpen.addActionListener(this);
cmdSave.addActionListener(this);
cmdNew.addActionListener(this);
cmdAdd.addActionListener(this);
cmdDelete.addActionListener(this);
cmdSetValue.addActionListener(this);
cmdGetValue.addActionListener(this);

mainPanel=new JPanel();
frame=new JFrame("Table Example");
frame.setSize(800,600);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
mainPanel.setLayout(new BorderLayout());
mainPanel.add("Center",scrollPane);
mainPanel.add("South",buttonPanel);
mainPanel.setBackground(Color.white);
buttonPanel.setBackground(Color.white);
table.getParent().setBackground(Color.black);
frame.getContentPane().add(mainPanel);
frame.setVisible(true);
mainPanel.setBorder(BorderFactory.createLineBorder(Color.black));

}
 public void addColumns(String[] colName)//Table Columns
{
for(int i=0;i<colName.length;i++)
columns.addElement((String) colName[i]);
}

public void addRow() //Add Row
{
Vector r=new Vector();
r=createBlankElement();
rows.addElement(r);
table.addNotify();

}

// Start of Open File Class
public void openFile() //Open File
{
     JFileChooser fc = new JFileChooser();
     int returnVal = fc.showOpenDialog(cmdOpen);
}

public void saveFile() //Save File
{
     JFileChooser fc = new JFileChooser();
     int returnVal = fc.showSaveDialog(cmdSave);    
}

public void newFile() //New File
{
     JFileChooser fc = new JFileChooser();
     int returnVal = fc.showOpenDialog(cmdNew);    
}

 public Vector createBlankElement()
{
Vector t = new Vector();
t.addElement((String) " ");
t.addElement((String) " ");
t.addElement((String) " ");
t.addElement((String) " ");
t.addElement((String) " ");
t.addElement((String) " ");
t.addElement((String) " ");
return t;
}

 void deleteRow(int index)
   {
     if(index!=-1)//At least one Row in Table
      {
        rows.removeElementAt(index);
        table.addNotify();
       }

   }//Delete Row

 public void tableChanged(javax.swing.event.TableModelEvent source)     {
                 String msg="";
                 TableModel tabMod = (TableModel)source.getSource();
          switch (source.getType())
                   {
                       case TableModelEvent.UPDATE:
                       msg="Table Value Updated for  cell "+table.getSelectedRow()+","+table.getSelectedColumn()+"\nWhich is "+table.getValueAt(table.getSelectedRow(),table.getSelectedColumn()).toString();
              JOptionPane.showMessageDialog(null,msg,"Table Example",JOptionPane.INFORMATION_MESSAGE);
                break;

                   }

    }//Table Changed Method

public void selectCell(int row,int col)
    {
         if(row!=-1 && col !=-1)            
          {
          table.setRowSelectionInterval(row,row);
          table.setColumnSelectionInterval(col,col);
          }
    }


public void actionPerformed(ActionEvent source)
    {
          if (source.getSource()==(JButton) cmdOpen)
          {
               openFile();
          }
          if (source.getSource()==(JButton) cmdSave)
          {
               saveFile();
          }
          if (source.getSource()==(JButton) cmdNew)
          {
               newFile();
          }
         if (source.getSource()==(JButton) cmdAdd)
         {
             addRow();
         }
         if (source.getSource()==(JButton) cmdDelete)
         {
             deleteRow(table.getSelectedRow());
         }
         if (source.getSource()==(JButton) cmdSetValue)
         {
          String CName=JOptionPane.showInputDialog(null,"Enter Value to be set at Cell 0,2 ","Simple Table Example",JOptionPane.INFORMATION_MESSAGE);
              if(!CName.trim().equals("") && table.getRowCount()>0)
              {
                  selectCell(0,2);
                  table.setValueAt(CName,0,2);
              }
         }
         if (source.getSource()==(JButton) cmdGetValue)
         {
            if(table.getRowCount()>0)
             {
           String msg="Value At cell 0,0 is "+table.getValueAt(0,0).toString();
           JOptionPane.showMessageDialog(null,msg,"Table Example",JOptionPane.INFORMATION_MESSAGE);
             }
     }
   
    }//ActionList

}
0
Comment
Question by:johnmarco
  • 3
  • 2
6 Comments
 
LVL 14

Expert Comment

by:hoomanv
ID: 16678214
you need to use a number cell renderer for cells that are supposed to have number
this threads may help you
http://forum.java.sun.com/thread.jspa?threadID=623935
http://forum.java.sun.com/thread.jspa?threadID=151977

also look here to for some table-related Qs
http://javaalmanac.com/egs/javax.swing.table/pkg.html
0
 

Author Comment

by:johnmarco
ID: 16678308
I already saw these posts but could not figure it out. I am here asking help and I appreciate if you will give a part of code which will fit to the code above.
I see you answering my other posts as well but code is what I need, not a link.
0
 
LVL 14

Expert Comment

by:hoomanv
ID: 16678346
code is everybody's need here, but absolutely Im not allowed to write someone else's code
you must make effort to achieve your needs by yourself
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:johnmarco
ID: 16678371
That is your view. I do respect your opinion. But I am here requesting help and I have the right to ask/request what I want.

The points will go to a person who will adjust the code above.
0
 
LVL 23

Accepted Solution

by:
rama_krishna580 earned 2000 total points
ID: 16679693
Hi,

try this...

In you table cell renderer you can specify the alignment of the text.

public class MyTableCellRenderer extends JLabel implements TableCellRenderer
{
public MyTableCellRenderer
{
setOpaque(true);
setBackground(Color.white);
}

public Component getTable.....(JTable table,Object value,......) //fill all these things
{
setFont(table.getFont());

if(value instanceof Float)
{
setHorizontalAlignment(SwingConstants.RIGHT);
setText(value);
}

return this;
}
}

This would set all the Floats to RIGHT alignment.

R.K
0
 

Author Comment

by:johnmarco
ID: 16681269
Could you please adjust the code above(my first one) with this one, because it seems like you took it from the java  sun forums and I already saw it before.

Please adjust/merge the 2 codes.
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
In this post we will learn different types of Android Layout and some basics of an Android App.
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
Suggested Courses
Course of the Month16 days, 23 hours left to enroll

862 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question