|
Здравствуйте, подскажите пожалуйста где можно достать материалы по курсу Кросс-платформенные и многозвенные технологии, о которых говориться, к примеру, в Лекции 2. Пример "Служба мгновенных сообщений" |
Опубликован: 18.03.2010 | Доступ: свободный | Студентов: 841 / 85 | Оценка: 4.48 / 4.33 | Длительность: 12:01:00
Тема: Программирование
Специальности: Администратор коммуникационных систем
Лекция 4:
Технология Enterprise Java Beans. Часть 2
Класс WidgetEditClient наследуется (extends) от JFrame. То как в нем организовано взаимодействие с EJB уже было рассмотрено ранее. Сейчас просто будет приведен код этого класса.
public class WidgetEditClient extends JFrame implements ActionListener
{
private static final long serialVersionUID = -7066592068515570150L;
private DefaultTableModel model;
private JTable table = null;
private Context jndiContext;
private WidgetHome home;
private JButton addButton;
public WidgetEditClient()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Obtaining the beans from the database
try
{
jndiContext = createJBossContext();
Object ref = jndiContext.lookup("WidgetBean");
home = (WidgetHome)
PortableRemoteObject.narrow(ref, WidgetHome.class);
}
catch(NamingException e)
{ e.printStackTrace();
}
loadElements();
JScrollPane scroll = new JScrollPane(table);
scroll.setBorder(BorderFactory.createEmptyBorder());
getContentPane().setLayout(new BorderLayout());
getContentPane().add(BorderLayout.CENTER, scroll);
getContentPane().add(BorderLayout.SOUTH, addButton = new
JButton("Add"));
addButton.addActionListener(this);
pack();
}
public void actionPerformed(ActionEvent e)
{
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
gc.insets = new Insets(5, 5, 5, 5);
gc.weightx = 1.0;
gc.weighty = 0.0;
gc.fill = GridBagConstraints.BOTH;
gc.gridx = 0;
gc.gridy = 0;
gc.gridwidth = 1;
gc.gridheight = 1;
panel.add(new JLabel("Price:"), gc);
gc.gridy = 1;
panel.add(new JLabel("Description:"), gc);
gc.gridx = 1;
gc.gridy = 0;
JTextField priceField = new JTextField(); panel.add(priceField, gc);
gc.gridy = 1;
JTextField descrField = new JTextField();
panel.add(descrField, gc);
int result = JOptionPane.showOptionDialog
(table, new JScrollPane(panel), "Add new widget",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, null, null);
if (result == JOptionPane.OK_OPTION)
{
try
{
double price = Double.parseDouble(priceField.getText());
String description = descrField.getText();
home.create(description, price);
loadElements();
table.invalidate();
}
catch (NumberFormatException ex)
{
ex.printStackTrace();
}
catch (RemoteException ex)
{
ex.printStackTrace();
}
catch (CreateException ex)
{
ex.printStackTrace();
}
}
}
}
private class DeleteCellEditor extends ButtonTableCellEditor
{
public DeleteCellEditor(TableCellEditor editor)
{
super(editor, "Yes");
}
protected void editCell(JTable table, int row, int column)
{
Integer id = (Integer) table.getModel().getValueAt(row, 0);
if (id.intValue() > 0)
{
try
{
home.remove(id);
loadElements();
table.invalidate();
}
catch (RemoteException e)
{
e.printStackTrace();
}
catch (RemoveException e)
{
e.printStackTrace();
}
}
}
}
private class DescriptionCellEditor extends ButtonTableCellEditor
{
public DescriptionCellEditor(TableCellEditor editor)
{
super (editor, "Edit");
}
protected void editCell(JTable table, int row, int column)
{
JTextField textField = new JTextField();
Object value = table.getValueAt(row, column);
if(value != null)
{
textField.setText((String) value);
textField.setCaretPosition(0);
}
int result = JOptionPane.showOptionDialog(table, new JScrollPane(textField),
(String)table.getColumnName(column),
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, null, null);
if (result == JOptionPane.OK_OPTION)
{
Integer id = (Integer)
table.getModel().getValueAt(row, 0);
if (id.intValue() > 0)
{
try
{
WidgetRemote remote = (WidgetRemote) home.findByPrimaryKey(id);
remote.setDescription(textField.getText());
table.setValueAt(textField.getText(), row, column);
table.invalidate();
}
catch (RemoteException e)
{
e.printStackTrace();
}
catch (FinderException e)
{
e.printStackTrace();
}
}
}
}
}
private class PriceCellEditor extends ButtonTableCellEditor
{
public PriceCellEditor(TableCellEditor editor)
{
super(editor, "Edit");
}
protected void editCell(JTable table, int row, int column)
{
JTextField textField = new JTextField();
Object value = table.getValueAt(row, column);
if(value != null)
{
textField.setText(((Double) value).toString());
textField.setCaretPosition(0);
}
int result = JOptionPane.showOptionDialog(table, new JScrollPane(textField),
(String)table.getColumnName(column),
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, null, null);
if(result == JOptionPane.OK_OPTION)
{
Integer id = (Integer)
table.getModel().getValueAt(row, 0);
if (id.intValue() > 0)
{
try
{
WidgetRemote remote = (WidgetRemote) home.findByPrimaryKey(id);
double price = Double.
parseDouble(textField.getText());
remote.setPrice(price);
table.setValueAt(price, row, column);
table.invalidate();
}
catch (RemoteException e)
{
e.printStackTrace();
}
catch (FinderException e)
{
e.printStackTrace();
}
catch (NumberFormatException e)
{
e.printStackTrace();
}
}
}
}
private void loadElements()
{
try
{
Collection col = home.findAll();
model = new DefaultTableModel();
model.addColumn("ID");
model.addColumn("Description");
model.addColumn("Price");
model.addColumn("Delete");
for (Iterator iter = col.iterator(); iter.hasNext();)
{
WidgetRemote remote = (WidgetRemote) iter.next();
model.addRow(new Object []{remote.getId(), remote.getDescription(),
remote.getPrice(), "Delete?"});
}
if (table == null)
{
table = new JTable(model);
}
else
{
table.setModel(model);
}
JTextField textField = new JTextField();
textField.setBorder(BorderFactory.createEmptyBorder());
DefaultCellEditor editor = new DefaultCellEditor(textField); editor.setClickCountToStart(l);
table.getColumn(table.getColumnName(1)).setCellEditor(
new DescriptionCellEditor(editor));
table.getColumn(table.getColumnName(2)).setCellEditor(
new PriceCellEditor(editor));
table.getColumn(table.getColumnName(3)).setCellEditor(
new DeleteCellEditor(editor));
}
catch(RemoteException e)
{
e.printStackTrace();
}
catch(FinderException e)
{
e.printStackTrace();
}
}
public static void main(String args[])
{
WidgetEditClient client = new WidgetEditClient();
client.setLocation(200, 200);
client.setSize(600, 400);
client.setVisible(true);
}
public static Context createJBossContext() throws NamingException
{
Properties p = new Properties();
p.put("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory");
p.put("java.naming.provider.url", "jnp://127.0.0.1:1099");
p.put("java.naming.factory.url.pkgs", "org.jboss.naming:org.jnp.interfaces");
Context jndiContext = new InitialContext(p);
return jndiContext;
}
}Вывод
Как видно из приведенного кода компонента WidgetBean,разработка BMP компонентов дело рутинное и довольно долгое. Использование CMP сильно упрощает процесс разработки объектных компонентов. В следующем примере будет рассмотрено использование CMP в следующем примере.