62,615
社区成员
发帖
与我相关
我的任务
分享
package com.accp;
import java.text.NumberFormat;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
public class TableDemo {
String [] columnTitles = { "菜名", "单价" };
String [][] tableData = {
{ "板栗山鸡", "10" },
{ "番茄鱼片", "20" },
{ "豆腐", "25" },
{ "甜汁三文鱼", "10" },
{ "清蒸大闸蟹", "15" },
{ "生鱼丝薄饼", "20" },
{ "土豆粉", "28" },
{ "猪蹄汤肉酿鲫鱼", "40" },
{ "北京烤鸭", "25" }
};
NumberFormat currencyFormat = NumberFormat.getCurrencyInstance();
Table table;
Button btnTotal;
Text txtTotal;
void createWidgets(Shell shell) {
//
shell.setText("表格示例");
shell.setLayout(new GridLayout(2, true));
//
Group tableGroup = new Group(shell, SWT.NONE);
tableGroup.setLayoutData (new GridData (SWT.FILL, SWT.FILL, true, true));
tableGroup.setLayout (new GridLayout ());
tableGroup.setText("数据");
//表格
table = new Table(tableGroup, SWT.FULL_SELECTION | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
table.setHeaderVisible(true);
table.setLinesVisible(true);
//表头
for (int i = 0; i < columnTitles.length; i++) {
TableColumn tableColumn = new TableColumn(table, SWT.NONE);
tableColumn.setText(columnTitles[i]);
}
//
for (int i = 0; i < tableData.length; i++) {
TableItem item = new TableItem(table, SWT.NONE);
for (int j = 0; j < tableData[i].length; j++) {
item.setText(j, tableData[i][j]);
}
}
//
Group controlGroup = new Group(shell, SWT.NONE);
controlGroup.setLayoutData (new GridData (SWT.FILL, SWT.FILL, true, true));
controlGroup.setLayout (new GridLayout ());
controlGroup.setText("操作");
//
Composite panel = new Composite(controlGroup, SWT.NONE);
panel.setLayoutData(new GridData (SWT.CENTER, SWT.DEFAULT, true, true));
panel.setLayout( new FillLayout(SWT.VERTICAL) );
//
new Label(panel, SWT.NONE).setText("所有单价的总和");
//
txtTotal = new Text(panel, SWT.BORDER | SWT.RIGHT | SWT.READ_ONLY );
//
btnTotal = new Button(panel, SWT.NONE);
btnTotal.setText("计算");
//pack
for (int i = 0; i < table.getColumnCount(); i++) {
TableColumn tableColumn = table.getColumn(i);
tableColumn.pack();
}
shell.pack();
//事件
btnTotal.addSelectionListener(new SelectionAdapter () {
public void widgetSelected (SelectionEvent event) {
double total = 0, price;
for( int i = 0; i < table.getItemCount(); i++ )
{
TableItem item = table.getItem( i );
price = Double.parseDouble( item.getText( 1 ) );
total += price;
}
txtTotal.setText( currencyFormat.format( total ) );
}
});
}
public Shell open (Display display) {
Shell shell = new Shell(display, SWT.DIALOG_TRIM );
createWidgets( shell );
shell.open();
return shell;
}
public static void main(String[] args) {
Display display = new Display ();
TableDemo example = new TableDemo ();
Shell shell = example.open (display);
while (!shell.isDisposed ())
if (!display.readAndDispatch ()) display.sleep ();
display.dispose ();
}
}