ads

sábado, 24 de janeiro de 2009

Código para excluir uma coluna de uma JTable em tempo de execução

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


public class Estudos extends JFrame{
public Estudos(){
super("Exemplo de uma tabela simples");

final DefaultTableModel modelo = new MyDefaultTableModel();

// constrói a tabela
final JTable tabela = new JTable(modelo);
tabela.setAutoCreateColumnsFromModel(false);

// Cria duas colunas
modelo.addColumn("Nome");
modelo.addColumn("Idade");

JButton btn = new JButton("Inserir Colunas");
btn.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
String titulo = JOptionPane.showInputDialog(null,
"Informe o título para a nova coluna:");
int pos = Integer.parseInt(JOptionPane.showInputDialog(null,
"Informe a posição da nova coluna:"));

// testa se a posição é válida
if(pos > (modelo.getColumnCount() - 1))
pos = 0;

// Insere uma coluna na posição especificada
insertColumn(tabela, titulo, null, pos);
}
}
);

JButton btn2 = new JButton("Excluir Colunas");
btn2.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
int pos = Integer.parseInt(JOptionPane.showInputDialog(null,
"Informe a posição da coluna a ser excluída:"));

// testa se a posição é válida
if(pos < modelo.getColumnCount())
// remove a coluna na posição especificada
removeColumnAndData(tabela, pos);
}
}
);

tabela.setPreferredScrollableViewportSize(new Dimension(350, 50));

Container c = getContentPane();
c.setLayout(new FlowLayout());

JScrollPane scrollPane = new JScrollPane(tabela);
c.add(scrollPane);
c.add(btn);
c.add(btn2);

setSize(400, 300);
setVisible(true);
}

public void betterAddColumn(JTable table, Object headerLabel,
Object[] values) {
DefaultTableModel model = (DefaultTableModel)table.getModel();
TableColumn col = new TableColumn(model.getColumnCount());

if(table.getAutoCreateColumnsFromModel()) {
throw new IllegalStateException();
}
col.setHeaderValue(headerLabel);
table.addColumn(col);
model.addColumn(headerLabel.toString(), values);
}

public void insertColumn(JTable table, Object headerLabel,
Object[] values, int vColIndex){
betterAddColumn(table, headerLabel, values);
table.moveColumn(table.getColumnCount()-1, vColIndex);
}

public void removeColumnAndData(JTable table, int vColIndex) {
MyDefaultTableModel model = (MyDefaultTableModel)table.getModel();
TableColumn col = table.getColumnModel().getColumn(vColIndex);
int columnModelIndex = col.getModelIndex();
Vector data = model.getDataVector();
Vector colIds = model.getColumnIdentifiers();

table.removeColumn(col);

colIds.removeElementAt(columnModelIndex);

for (int r=0; rVector row = (Vector)data.get(r);
row.removeElementAt(columnModelIndex);
}
model.setDataVector(data, colIds);

Enumeration enume = table.getColumnModel().getColumns();
for (; enume.hasMoreElements(); ) {
TableColumn c = (TableColumn)enume.nextElement();
if (c.getModelIndex() >= columnModelIndex) {
c.setModelIndex(c.getModelIndex()-1);
}
}
model.fireTableStructureChanged();
}

public static void main(String args[]){
Estudos app = new Estudos();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
class MyDefaultTableModel extends DefaultTableModel {
public Vector getColumnIdentifiers() {
return columnIdentifiers;
}
}

Mask Formatter in Java

The Java 2 Standard Edition (J2SE), version 1.4 add the Swing component JFormattedTextField. With this component it's possible build formatted fields like telephone, date, CPF, etc...

The DefaultFormatterFactory component comes with preinstalled formatters for dates, numbers, java.text.Format subclasses.

Configuring acceptable input

Masked input is typically configured by using an instance of the MaskFormatter class. Found in the javax.swing.text package, MaskFormatter works by using a series of characters to designate acceptable input. Each of the eight characters in the series represents one character in the input, as listed below:

# - A number
? - A letter
A - A letter or number
* - Anything
U - A letter, with lowercase characters mapped to their uppercase equivalents
L - A letter, with uppercase characters mapped to their lowercase equivalents
H - A hexadecimal digit (A-F, a-f, 0-9)
' - Used to escape another mask character

In addition to MaskFormatter, you can use the DateFormat and NumberFormat classes from the java.text package to specify the input format. Listing 1 shows some possible formats.

// Four-digit year, followed by month name and day of month,
// each separated by two dashes (--)
DateFormat format =
new SimpleDateFormat("yyyy--MMMM--dd");
DateFormatter df = new DateFormatter(format);
// US Social Security number
MaskFormatter mf1 =
new MaskFormatter("###-##-####");
// US telephone number
MaskFormatter mf2 =
new MaskFormatter("(###) ###-####");


Once you've specified the input format, you would then pass the formatter into the JFormattedTextField constructor, as shown below:

JFormattedTextField ftf1 = new
JFormattedTextField(df);

Depending on the formatter used, there are other configurable options. For instance, with MaskFormatter, you can set the placeholder character with setPlaceholderCharacter(char). Also, for date fields, it helps if you initialize the field to some value so a user will know what input format is acceptable.


Example:

import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
import java.util.*;
import java.text.*;
public class FormattedSample {
public static void main (String args[]) throws ParseException {
JFrame f = new JFrame("JFormattedTextField Sample");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container content = f.getContentPane();
content.setLayout(new BoxLayout(content, BoxLayout.PAGE_AXIS));
// Four-digit year, followed by month name and day of month,
// each separated by two dashes (--)
DateFormat format =
new SimpleDateFormat("yyyy--MMMM--dd");
DateFormatter df = new DateFormatter(format);
JFormattedTextField ftf1 = new
JFormattedTextField(df);
ftf1.setValue(new Date());
content.add(ftf1);
// US Social Security number
MaskFormatter mf1 =
new MaskFormatter("###-##-####");
mf1.setPlaceholderCharacter('_');
JFormattedTextField ftf2 = new
JFormattedTextField(mf1);
content.add(ftf2);
// US telephone number
MaskFormatter mf2 =
new MaskFormatter("(###) ###-####");
JFormattedTextField ftf3 = new
JFormattedTextField(mf2);
content.add(ftf3);
f.setSize(300, 100);
f.show();
}
}

Source: IBM, SUN

segunda-feira, 12 de janeiro de 2009

GMaps4JSF

GMaps4JSF visa a integração do Google Maps com JavaServer Faces.

Usuários da tecnologia JSF serão capazes de construir complexas StreetViewPanoramas e mapas com apenas algumas tags JSF.

GMaps4JSF é uma biblioteca de mashups que permite aos desenvolvedores contruírem aplicações em JSF facilmente.

Algumas novidades para a nova versão:
* Ícone para simplificar o marcador de imagem personalizado
* Agora é permitido adicionar notas ao componente de marcador
* Suporte a Facelets
* Bugs resolvidos da versão 1.1.0

Fonte: Theserverside.com