From this code.makery blog, i was able to understand how tableview sorting and filtering works and implement. The problem is the blog showed an example that does not use ListProperty. When i tried to change the code example with ListProperty no sorting and filtering happens.
This is what the blog provided
FilteredList<Person> filteredData = new FilteredList<>(masterData, p -> true);
filterField.textProperty().addListener((observable, oldValue, newValue) -> {
filteredData.setPredicate(person -> {
if (newValue == null || newValue.isEmpty()) {
return true;
}
String lowerCaseFilter = newValue.toLowerCase();
if (person.getFirstName().toLowerCase().contains(lowerCaseFilter)) {
return true;
} else if (person.getLastName().toLowerCase().contains(lowerCaseFilter)) {
return true;
}
return false;
});
});
SortedList<Person> sortedData = new SortedList<>(filteredData);sortedData.comparatorProperty().bind(personTable.comparatorProperty());
personTable.setItems(sortedData);
The following is SSCCE for my implementation with ListProperty
import java.util.ArrayList;
import java.util.List;
import javafx.application.Application;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.FloatProperty;
import javafx.beans.property.ListProperty;
import javafx.beans.property.ReadOnlyFloatProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleFloatProperty;
import javafx.beans.property.SimpleListProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.collections.transformation.SortedList;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class SortTable extends Application{
private ObservableList<Collection> collectionList = FXCollections.observableArrayList();
private ListProperty<Collection> collectionListProperty = new SimpleListProperty<>();
public static void main(String[] args) { launch(args); }
#Override
public void start(Stage primaryStage) throws Exception {
BorderPane borderPane = new BorderPane();
collectionList.setAll(getCollection());
TableView<Collection> tv = new TableView();
TextField sortTF = new TextField();
TableColumn<Collection, Number> colAmount = createAmountColumn();
TableColumn<Collection, String> colMno = createMNOColumn();
TableColumn<Collection, Number> colPrice = createPriceColumn();
TableColumn<Collection, Number> colQty = createQuantityColumn();
tv.getColumns().addAll(colMno, colQty, colPrice, colAmount);
collectionListProperty.set(collectionList);
tv.itemsProperty().bind(collectionListProperty);
FilteredList<Collection> filteredData = new FilteredList<>(collectionList, p -> true);
sortTF.textProperty().addListener((observable, oldValue, newValue) -> {
filteredData.setPredicate(SaleTransaction -> {
if (newValue == null || newValue.isEmpty()) {
return true;
}
String lowerCaseFilter = newValue.toLowerCase();
if (SaleTransaction.getMno().toLowerCase().contains(lowerCaseFilter)) {
return true;
}
return false;
});
});
SortedList<Collection> sortedData = new SortedList<>(filteredData);
sortedData.comparatorProperty().bind(tv.comparatorProperty());
collectionList.setAll(sortedData);
borderPane.setTop(sortTF);
borderPane.setCenter(tv);
Scene scene = new Scene(borderPane, 600, 400);
primaryStage.setScene(scene);
primaryStage.show();
}
private TableColumn createQuantityColumn() {
TableColumn<Collection, Float> colQty = new TableColumn("Quantity");
colQty.setMinWidth(25);
colQty.setId("colQty");
colQty.setCellValueFactory(cellData -> cellData.getValue().quantityProperty().asObject());
return colQty;
}
private TableColumn createPriceColumn() {
TableColumn<Collection, Float> colPrice = new TableColumn("Price");
colPrice.setMinWidth(25);
colPrice.setId("colPrice");
colPrice.setCellValueFactory(cellData -> cellData.getValue().priceProperty().asObject());
return colPrice;
}
private TableColumn createAmountColumn() {
TableColumn<Collection, Float> colAmount = new TableColumn("Amount");
colAmount.setMinWidth(25);
colAmount.setId("colAmount");
colAmount.setCellValueFactory(cellData -> cellData.getValue().amountProperty().asObject());
return colAmount;
}
private TableColumn createMNOColumn() {
TableColumn colMNO = new TableColumn("M/NO");
colMNO.setMinWidth(25);
colMNO.setId("colMNO");
colMNO.setCellValueFactory(new PropertyValueFactory("mno"));
return colMNO;
}
private List<Collection> getCollection(){
List<Collection> collections = new ArrayList<>();
collections.add(new Collection(1, 10, "1", false));
collections.add(new Collection(2, 10, "12", true));
collections.add(new Collection(3, 10, "123", true));
collections.add(new Collection(4, 10, "312", true));
collections.add(new Collection(5, 10, "311", false));
collections.add(new Collection(6, 10, "322", true));
collections.add(new Collection(7, 10, "333", true));
collections.add(new Collection(8, 10, "321", false));
collections.add(new Collection(9, 10, "456", true));
collections.add(new Collection(10, 10, "551", true));
collections.add(new Collection(11, 10, "515", false));
collections.add(new Collection(12, 10, "134", true));
collections.add(new Collection(13, 10, "789", true));
collections.add(new Collection(14, 10, "879", false));
collections.add(new Collection(15, 10, "987", true));
collections.add(new Collection(16, 10, "856", true));
collections.add(new Collection(17, 10, "956", true));
collections.add(new Collection(18, 10, "589", true));
collections.add(new Collection(19, 10, "852", false));
collections.add(new Collection(20, 10, "456", false));
collections.add(new Collection(21, 10, "623", true));
collections.add(new Collection(22, 10, "147", false));
collections.add(new Collection(23, 10, "125", true));
collections.add(new Collection(24, 10, "258", false));
collections.add(new Collection(25, 10, "325", true));
collections.add(new Collection(26, 10, "753", true));
collections.add(new Collection(27, 10, "357", false));
collections.add(new Collection(28, 10, "159", false));
return collections;
}
public class Collection{
private final FloatProperty quantity = new SimpleFloatProperty();
private final FloatProperty price = new SimpleFloatProperty();
private final FloatProperty amount = new SimpleFloatProperty();
private final BooleanProperty paid = new SimpleBooleanProperty(false);
private String mno;
public Collection(){
this(0f, 0f, null, false);
}
public Collection(float quantity, float price, String mno, boolean paid) {
setQuantity(quantity);
setPrice(price);
setMno(mno);
setPaid(paid);
this.amount.bind(this.quantity.multiply(this.price));
}
public String getMno() {
return mno;
}
public void setMno(String mno) {
this.mno = mno;
}
public float getQuantity() {
return quantityProperty().get();
}
public void setQuantity(float quantity) {
quantityProperty().set(quantity);
}
public FloatProperty quantityProperty() {
return quantity ;
}
public float getPrice() {
return priceProperty().get();
}
public void setPrice(float price) {
priceProperty().set(price);
}
public FloatProperty priceProperty() {
return price ;
}
public float getAmount() {
return amountProperty().get();
}
public ReadOnlyFloatProperty amountProperty() {
return amount ;
}
public BooleanProperty paidProperty() {
return paid;
}
public void setPaid(boolean approved) {
this.paid.set(approved);
}
public boolean isPaid() {
return paid.get();
}
}
}
Related
I have a table with quantity and price columns that are editable and not disabled. The table is populated with ObservableList<Collection> . Collection object has a boolean attribute paid. What i am tring to achieve is whenever paid is true, make both price and quantity tablecells disabled and not editable.
This is what i have done so far:
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import javafx.application.Application;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.FloatProperty;
import javafx.beans.property.ReadOnlyFloatProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleFloatProperty;
import javafx.beans.value.ObservableValue;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableRow;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import javafx.util.Callback;
import javafx.util.converter.FloatStringConverter;
public class CollectionTable extends Application{
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception {
TableView<Collection> tv = new TableView();
tv.setEditable(true);
TableColumn<Collection, Number> colQty = createQuantityColumn();
colQty.setCellFactory(
new Callback<TableColumn<Collection, Number>, TableCell<Collection, Number>>() {
#Override
public TableCell<Collection, Number> call(TableColumn<Collection, Number> paramTableColumn) {
return new TextFieldTableCell<Collection, Number>() {
#Override
public void updateItem(Number s, boolean b) {
super.updateItem(s, b);
TableRow row = getTableRow();
if (row != null) {
Collection item = (Collection) row.getItem();
//Test for disable condition
if (item != null && item.isPaid()) {
setDisable(true);
setEditable(false);
this.setStyle("-fx-text-fill: grey;-fx-border-color: red");
}
}
}
};
}
});
TableColumn<Collection, Number> colPrice = createPriceColumn();
colPrice.setCellFactory(
new Callback<TableColumn<Collection, Number>, TableCell<Collection, Number>>() {
#Override
public TableCell<Collection, Number> call(TableColumn<Collection, Number> paramTableColumn) {
return new TextFieldTableCell<Collection, Number>() {
#Override
public void updateItem(Number s, boolean b) {
super.updateItem(s, b);
TableRow row = getTableRow();
if (row != null) {
Collection item = (Collection) row.getItem();
//Test for disable condition
if (item != null && !item.isPaid()) {
setDisable(true);
setEditable(false);
this.setStyle("-fx-text-fill: grey;-fx-border-color: red");
}
}
}
};
}
});
TableColumn<Collection, Number> colAmount = createAmountColumn();
TableColumn<Collection, String> colMno = createMNOColumn();
tv.getColumns().addAll(colMno, colQty, colPrice, colAmount);
tv.getItems().addAll(getCollection());
Scene scene = new Scene(new BorderPane(tv), 600, 400);
primaryStage.setScene(scene);
primaryStage.show();
}
private TableColumn createQuantityColumn() {
TableColumn<Collection, Float> colQty = new TableColumn("Quantity");
colQty.setMinWidth(25);
colQty.setId("colQty");
colQty.setCellFactory(TextFieldTableCell.<Collection, Float>forTableColumn(new FloatStringConverter()));
colQty.setCellValueFactory(cellData -> cellData.getValue().quantityProperty().asObject());
colQty.setOnEditCommit(new EventHandler<TableColumn.CellEditEvent<Collection, Float>>() {
#Override
public void handle(TableColumn.CellEditEvent<Collection, Float> t) {
}
});
return colQty;
}
private TableColumn createPriceColumn() {
TableColumn<Collection, Float> colPrice = new TableColumn("Price");
colPrice.setMinWidth(25);
colPrice.setId("colPrice");
colPrice.setCellFactory(TextFieldTableCell.<Collection, Float>forTableColumn(new FloatStringConverter()));
colPrice.setCellValueFactory(cellData -> cellData.getValue().priceProperty().asObject());
colPrice.setOnEditStart(new EventHandler<TableColumn.CellEditEvent<Collection, Float>>() {
#Override
public void handle(TableColumn.CellEditEvent<Collection, Float> t) {
Collection c = ((Collection) t.getTableView().getItems().get(t.getTablePosition().getRow()));
c.setPrice(Math.abs(c.getPrice()));
}
});
colPrice.setOnEditCommit(new EventHandler<TableColumn.CellEditEvent<Collection, Float>>() {
#Override
public void handle(TableColumn.CellEditEvent<Collection, Float> t) {
Collection c = ((Collection) t.getTableView().getItems().get(t.getTablePosition().getRow()));
c.setPrice(Math.abs((float)t.getNewValue()));
//int i = collectionHandler.updateCollection(c);
}
});
return colPrice;
}
private TableColumn createAmountColumn() {
TableColumn<Collection, Float> colAmount = new TableColumn("Amount");
colAmount.setMinWidth(25);
colAmount.setId("colAmount");
colAmount.setCellValueFactory(cellData -> cellData.getValue().amountProperty().asObject());
return colAmount;
}
private TableColumn createMNOColumn() {
TableColumn colMNO = new TableColumn("M/NO");
colMNO.setMinWidth(25);
colMNO.setId("colMNO");
colMNO.setCellValueFactory(new PropertyValueFactory("mno"));
return colMNO;
}
private List<Collection> getCollection(){
List<Collection> collections = new ArrayList<>();
collections.add(new Collection(1, 10, "1", false));
collections.add(new Collection(2, 10, "12", true));
collections.add(new Collection(3, 10, "123", true));
collections.add(new Collection(4, 10, "312", true));
collections.add(new Collection(5, 10, "311", false));
collections.add(new Collection(6, 10, "322", true));
collections.add(new Collection(7, 10, "333", true));
collections.add(new Collection(8, 10, "321", false));
collections.add(new Collection(9, 10, "456", true));
collections.add(new Collection(10, 10, "551", true));
collections.add(new Collection(11, 10, "515", false));
collections.add(new Collection(12, 10, "134", true));
collections.add(new Collection(13, 10, "789", true));
collections.add(new Collection(14, 10, "879", false));
collections.add(new Collection(15, 10, "987", true));
collections.add(new Collection(16, 10, "856", true));
collections.add(new Collection(17, 10, "956", true));
collections.add(new Collection(18, 10, "589", true));
collections.add(new Collection(19, 10, "852", false));
collections.add(new Collection(20, 10, "456", false));
collections.add(new Collection(21, 10, "623", true));
collections.add(new Collection(22, 10, "147", false));
collections.add(new Collection(23, 10, "125", true));
collections.add(new Collection(24, 10, "258", false));
collections.add(new Collection(25, 10, "325", true));
collections.add(new Collection(26, 10, "753", true));
collections.add(new Collection(27, 10, "357", false));
collections.add(new Collection(28, 10, "159", false));
return collections;
}
public class Collection{
private final FloatProperty quantity = new SimpleFloatProperty();
private final FloatProperty price = new SimpleFloatProperty();
private final FloatProperty amount = new SimpleFloatProperty();
private final BooleanProperty paid = new SimpleBooleanProperty(false);
private String mno;
public Collection(){
this(0f, 0f, null, false);
}
public Collection(float quantity, float price, String mno, boolean paid) {
setQuantity(quantity);
setPrice(price);
setMno(mno);
setPaid(paid);
this.amount.bind(this.quantity.multiply(this.price));
}
public String getMno() {
return mno;
}
public void setMno(String mno) {
this.mno = mno;
}
public float getQuantity() {
return quantityProperty().get();
}
public void setQuantity(float quantity) {
quantityProperty().set(quantity);
}
public FloatProperty quantityProperty() {
return quantity ;
}
public float getPrice() {
return priceProperty().get();
}
public void setPrice(float price) {
priceProperty().set(price);
}
public FloatProperty priceProperty() {
return price ;
}
public float getAmount() {
return amountProperty().get();
}
public ReadOnlyFloatProperty amountProperty() {
return amount ;
}
public BooleanProperty paidProperty() {
return paid;
}
public void setPaid(boolean approved) {
this.paid.set(approved);
}
public boolean isPaid() {
return paid.get();
}
}
}
The problem with my code is that as i scroll down the table and up again, cells which were previously enabled and editable change to disabled and not editable.
Before scroll After scroll:
The first problem is that you don't reset the state when a cell is reused from one which is paid to one which is not paid. This will happen, among other times, when you scroll. If a cell was previously used in a row that represented a "paid" item (so it is disabled, not editable, and has a red border), and is reused for an "unpaid" item, your updateItem() method will not change the editable or disabled state (or the style). So you should have something like:
if (item != null && item.isPaid()) {
setDisable(true);
setEditable(false);
this.setStyle("-fx-text-fill: grey;-fx-border-color: red");
} else {
setDisable(false);
setEditable(true);
setStyle("");
}
The second problem is that you have no control over the order in which the cell's state is updated. It seems that sometimes the row property is updated after the updateItem() method is called, so you end up with inconsistent state. You can safely use the cell's index to get the correct item from the table's data.
Also note that since both cell factories are identical, there is no need to replicate the code. This works for me:
#Override
public void start(Stage primaryStage) throws Exception {
TableView<Collection> tv = new TableView();
tv.setEditable(true);
TableColumn<Collection, Number> colQty = createQuantityColumn();
Callback<TableColumn<Collection, Number>, TableCell<Collection, Number>> cellFactory = new Callback<TableColumn<Collection, Number>, TableCell<Collection, Number>>() {
#Override
public TableCell<Collection, Number> call(TableColumn<Collection, Number> paramTableColumn) {
return new TextFieldTableCell<Collection, Number>() {
#Override
public void updateItem(Number s, boolean b) {
super.updateItem(s, b);
if (! isEmpty()) {
Collection item = getTableView().getItems().get(getIndex());
// Test for disable condition
if (item != null && item.isPaid()) {
setDisable(true);
setEditable(false);
this.setStyle("-fx-text-fill: grey;-fx-border-color: red");
} else {
setDisable(false);
setEditable(true);
setStyle("");
}
}
}
};
}
};
colQty.setCellFactory(cellFactory);
TableColumn<Collection, Number> colPrice = createPriceColumn();
colPrice.setCellFactory(cellFactory);
TableColumn<Collection, Number> colAmount = createAmountColumn();
TableColumn<Collection, String> colMno = createMNOColumn();
tv.getColumns().addAll(colMno, colQty, colPrice, colAmount);
tv.getItems().addAll(getCollection());
Scene scene = new Scene(new BorderPane(tv), 600, 400);
primaryStage.setScene(scene);
primaryStage.show();
}
I have a JTable in my JDialog which I populate myself in another method. Here is my code and I want the second null in my Object array to be a JCheckBox. I have been scowering the internet and saw someone say I need to override a method in the tablerenderer or something like that and I got confused on how to do it. Anyway here is the code
package privatelessontrackernetbeans;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.TreeMap;
import javax.swing.ImageIcon;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
/**
*
* #author Brent C
*/
public class WeeklyLessonsReductionGUI extends javax.swing.JDialog {
/**
* Creates new form WeeklyLessonsReductionGUI
* #param parent
* #param modal
*/
public WeeklyLessonsReductionGUI(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
postInitComponents();
}
private void postInitComponents() {
ImageIcon icon = new ImageIcon(PSLTrackerInfo.file + "ymcaLogo.png");
setIconImage(icon.getImage());
//Table for students that need more lessons
DefaultTableModel dtm = (DefaultTableModel) jTable1.getModel();
dtm.setRowCount(0);
//Center the Titles
DefaultTableCellRenderer centerRenderer = (DefaultTableCellRenderer)
jTable1.getTableHeader().getDefaultRenderer();
centerRenderer.setHorizontalAlignment(SwingConstants.CENTER);
//Center the Cells
jTable1.setDefaultRenderer(Object.class, centerRenderer);
TreeMap<Instructor, ArrayList<Student>> theList =
PSLTrackerInfo.theList_getMap();
for (Instructor key : theList.keySet()) {
ArrayList<Student> students = theList.get(key);
boolean listed = false;
for (Student values : students) {
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_MONTH, Calendar.MONDAY);
c.set(Calendar.WEEK_OF_YEAR, values.getLastUpdateWeek());
c.set(Calendar.YEAR, values.getLastUpdateYear());
DateFormat df = new SimpleDateFormat("MMMM dd, yyyy");
Date date = c.getTime();
String s = df.format(date);
if (listed) {
Object[] data = new Object[]{null,
values.getName(), s, null, null, null};
dtm.addRow(data);
} else {
Object[] data = new Object[]{values.getInstructor(),
values.getName(), s, null, null, null};
dtm.addRow(data);
listed = true;
}
}
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Lessons Update");
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Instructor", "Student", "Last Update", "Lesson Date", "Lesson Complete", "Unscheduled Lessons"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false, false, true, true
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane1.setViewportView(jTable1);
jButton1.setText("Update");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 829, Short.MAX_VALUE)
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton1)
.addGap(375, 375, 375))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton1)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
// End of variables declaration
}
No need for a custom renderer, just override the getColumnClass() method of the DefaultTableModel making the column with the boolean a Boolean object.
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
public class CheckBoxTable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Object[][] data
= {{"false", false},
{"true", true}};
String[] cols = {"String", "Boolean"};
DefaultTableModel model = new DefaultTableModel(data, cols) {
#Override
public Class<?> getColumnClass(int column) {
if (column == 1) {
return Boolean.class;
} else {
return String.class;
}
}
};
JTable table = new JTable(model);
JOptionPane.showMessageDialog(null, new JScrollPane(table));
}
});
}
}
why you just don't do a "new JCheckBox()" instead of the second null??
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I've got an application with some JButtons, if you click them you see a image. Now if you open the frame and you dont have clicked yet you see a image in the middle of the screen. Now i want if you click the JButton for the image, the image is shown and the other image in the middle of the screen is gone but i dont know how to do.
My Frame:
package View;
import java.awt.Color;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Image;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import Controller.HomeController;
import Controller.SelectieController;
public class Selectie extends JFrame{
private static String Gregory = "Gregory";
private static String Vermeer = "Vermeer";
private static String Alderweireld = "Alderweireld";
private static String Vertonghen = "Vertonghen";
private static String Anita = "Anita";
private static String Enoh = "Enoh";
private static String Sulejmani = "Sulejmani";
private static String Cristian = "Cristian";
private static String Kolbeinn = "Kolbeinn";
private static String Siem = "Siem";
private static String Lorenzo = "Lorenzo";
private static String Andre = "Andre";
private static String Nicolai = "Nicolai";
private static String Theo = "Theo";
private static String Daley = "Daley";
private static String Nicolas = "Nicolas";
private static String Dmitri = "Dmitri";
private static String Kruis = "Kruis";
private JLabel label, label1, label2;
private JButton keeper, verdediger, verdediger1, verdediger2, verdediger3, verdediger4;
private JButton middenvelder, middenvelder1, aanvaller, aanvaller1, middenvelder2;
private JButton aanvaller2, verdediger5, middenvelder3, verdediger6, middenvelder4;
private JButton aanvaller3, kruis;
private JPanel panel;
private Container window = getContentPane();
public Selectie()
{
initGUI();
}
public void initGUI()
{
setLayout(null);
setTitle();
setSize(800,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
label = new JLabel();
label.setBounds(0, 0, 266, 800);
label.setBackground(Color.RED);
label.setOpaque(true);
window.add(label);
label1 = new JLabel();
label1.setBounds(266, 0, 266, 800);
label1.setBackground(Color.BLACK);
label1.setOpaque(true);
window.add(label1);
label2 = new JLabel();
label2.setBounds(532, 0, 266, 800);
label2.setBackground(Color.RED);
label2.setOpaque(true);
window.add(label2);
JLabel foto = new JLabel();
label1.add(foto);
kruis = new JButton(new ImageIcon("../Ajax/src/img/logotje.gif"));
kruis.setBorderPainted(false);
kruis.setBounds(40, 150, 188, 188);
kruis.setActionCommand(Kruis);
label1.add(kruis);
keeper = new JButton("1. "+""+" Kenneth Vermeer");
Cursor cur = keeper.getCursor();
keeper.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
keeper.setBounds(20, 50, 186, 12);
keeper.setFocusable(false);
keeper.setBorderPainted(false);
keeper.setContentAreaFilled(false);
keeper.setFont(new Font("Arial",Font.PLAIN,17));
keeper.setForeground(Color.WHITE);
keeper.setActionCommand(Vermeer);
label.add(keeper);
verdediger = new JButton("2. "+""+" Gregory van der Wiel");
Cursor cur1 = verdediger.getCursor();
verdediger.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
verdediger.setBounds(20, 70, 215, 17);
verdediger.setFocusable(false);
verdediger.setBorderPainted(false);
verdediger.setContentAreaFilled(false);
verdediger.setFont(new Font("Arial",Font.PLAIN,17));
verdediger.setForeground(Color.WHITE);
verdediger.setActionCommand(Gregory);
label.add(verdediger);
verdediger1 = new JButton("3. "+""+" Toby Alderweireld");
Cursor cur2 = verdediger1.getCursor();
verdediger1.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
verdediger1.setBounds(20, 95, 188, 17);
verdediger1.setFocusable(false);
verdediger1.setBorderPainted(false);
verdediger1.setContentAreaFilled(false);
verdediger1.setFont(new Font("Arial",Font.PLAIN,17));
verdediger1.setForeground(Color.WHITE);
verdediger1.setActionCommand(Alderweireld);
label.add(verdediger1);
verdediger2 = new JButton("4. "+""+" Jan Vertonghen");
Cursor cur3 = verdediger2.getCursor();
verdediger2.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
verdediger2.setBounds(20, 120, 174, 17);
verdediger2.setFocusable(false);
verdediger2.setBorderPainted(false);
verdediger2.setContentAreaFilled(false);
verdediger2.setFont(new Font("Arial",Font.PLAIN,17));
verdediger2.setForeground(Color.WHITE);
verdediger2.setActionCommand(Vertonghen);
label.add(verdediger2);
verdediger3 = new JButton("5. "+""+" Vurnon Anita");
Cursor cur4 = verdediger3.getCursor();
verdediger3.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
verdediger3.setBounds(20, 145, 153, 12);
verdediger3.setFocusable(false);
verdediger3.setBorderPainted(false);
verdediger3.setContentAreaFilled(false);
verdediger3.setFont(new Font("Arial",Font.PLAIN,17));
verdediger3.setForeground(Color.WHITE);
verdediger3.setActionCommand(Anita);
label.add(verdediger3);
middenvelder = new JButton("6. "+""+" Eyong Enoh");
Cursor cur5 = middenvelder.getCursor();
middenvelder.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
middenvelder.setBounds(20, 170, 148, 17);
middenvelder.setFocusable(false);
middenvelder.setBorderPainted(false);
middenvelder.setContentAreaFilled(false);
middenvelder.setFont(new Font("Arial",Font.PLAIN,17));
middenvelder.setForeground(Color.WHITE);
middenvelder.setActionCommand(Enoh);
label.add(middenvelder);
aanvaller = new JButton("7. "+""+" Miralem Sulejmani");
Cursor cur6 = aanvaller.getCursor();
aanvaller.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
aanvaller.setBounds(20, 195, 190, 17);
aanvaller.setFocusable(false);
aanvaller.setBorderPainted(false);
aanvaller.setContentAreaFilled(false);
aanvaller.setFont(new Font("Arial",Font.PLAIN,17));
aanvaller.setForeground(Color.WHITE);
aanvaller.setActionCommand(Sulejmani);
label.add(aanvaller);
middenvelder1 = new JButton("8. "+""+" Cristian Eriksen");
Cursor cur7 = middenvelder1.getCursor();
middenvelder1.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
middenvelder1.setBounds(20, 220, 174, 12);
middenvelder1.setFocusable(false);
middenvelder1.setBorderPainted(false);
middenvelder1.setContentAreaFilled(false);
middenvelder1.setFont(new Font("Arial",Font.PLAIN,17));
middenvelder1.setForeground(Color.WHITE);
middenvelder1.setActionCommand(Cristian);
label.add(middenvelder1);
aanvaller1 = new JButton("9. "+""+" Kolbeinn Sightórsson");
Cursor cur8 = aanvaller1.getCursor();
aanvaller1.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
aanvaller1.setBounds(20, 245, 212, 17);
aanvaller1.setFocusable(false);
aanvaller1.setBorderPainted(false);
aanvaller1.setContentAreaFilled(false);
aanvaller1.setFont(new Font("Arial",Font.PLAIN,17));
aanvaller1.setForeground(Color.WHITE);
aanvaller1.setActionCommand(Kolbeinn);
label.add(aanvaller1);
middenvelder2 = new JButton("10. "+""+" Siem de Jong");
Cursor cur9 = middenvelder2.getCursor();
middenvelder2.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
middenvelder2.setBounds(20, 270, 168, 17);
middenvelder2.setFocusable(false);
middenvelder2.setBorderPainted(false);
middenvelder2.setContentAreaFilled(false);
middenvelder2.setFont(new Font("Arial",Font.PLAIN,17));
middenvelder2.setForeground(Color.WHITE);
middenvelder2.setActionCommand(Siem);
label.add(middenvelder2);
aanvaller2 = new JButton("11. "+""+" Lorenzo Ebecilio");
Cursor cur10 = aanvaller2.getCursor();
aanvaller2.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
aanvaller2.setBounds(20, 295, 189, 12);
aanvaller2.setFocusable(false);
aanvaller2.setBorderPainted(false);
aanvaller2.setContentAreaFilled(false);
aanvaller2.setFont(new Font("Arial",Font.PLAIN,17));
aanvaller2.setForeground(Color.WHITE);
aanvaller2.setActionCommand(Lorenzo);
label.add(aanvaller2);
verdediger4 = new JButton("13. "+""+" André Ooijer");
Cursor cur11 = verdediger4.getCursor();
verdediger4.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
verdediger4.setBounds(20, 320, 159, 17);
verdediger4.setFocusable(false);
verdediger4.setBorderPainted(false);
verdediger4.setContentAreaFilled(false);
verdediger4.setFont(new Font("Arial",Font.PLAIN,17));
verdediger4.setForeground(Color.WHITE);
verdediger4.setActionCommand(Andre);
label.add(verdediger4);
verdediger5 = new JButton("15. "+""+" Nicolai Boilesen");
Cursor cur12 = verdediger5.getCursor();
verdediger5.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
verdediger5.setBounds(20, 345, 183, 12);
verdediger5.setFocusable(false);
verdediger5.setBorderPainted(false);
verdediger5.setContentAreaFilled(false);
verdediger5.setFont(new Font("Arial",Font.PLAIN,17));
verdediger5.setForeground(Color.WHITE);
verdediger5.setActionCommand(Nicolai);
label.add(verdediger5);
middenvelder3 = new JButton("16. "+""+" Theo Janssen");
Cursor cur13 = middenvelder3.getCursor();
middenvelder3.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
middenvelder3.setBounds(20, 370, 169, 12);
middenvelder3.setFocusable(false);
middenvelder3.setBorderPainted(false);
middenvelder3.setContentAreaFilled(false);
middenvelder3.setFont(new Font("Arial",Font.PLAIN,17));
middenvelder3.setForeground(Color.WHITE);
middenvelder3.setActionCommand(Theo);
label.add(middenvelder3);
verdediger6 = new JButton("17. "+""+" Daley Blind");
Cursor cur14 = verdediger6.getCursor();
verdediger6.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
verdediger6.setBounds(20, 395, 150, 17);
verdediger6.setFocusable(false);
verdediger6.setBorderPainted(false);
verdediger6.setContentAreaFilled(false);
verdediger6.setFont(new Font("Arial",Font.PLAIN,17));
verdediger6.setForeground(Color.WHITE);
verdediger6.setActionCommand(Daley);
label.add(verdediger6);
middenvelder4 = new JButton("18. "+""+" Nicolás Lodeiro");
Cursor cur15 = middenvelder4.getCursor();
middenvelder4.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
middenvelder4.setBounds(20, 420, 180, 12);
middenvelder4.setFocusable(false);
middenvelder4.setBorderPainted(false);
middenvelder4.setContentAreaFilled(false);
middenvelder4.setFont(new Font("Arial",Font.PLAIN,17));
middenvelder4.setForeground(Color.WHITE);
middenvelder4.setActionCommand(Nicolas);
label.add(middenvelder4);
aanvaller3 = new JButton("19. "+""+" Dmitri Bulykin");
Cursor cur16 = aanvaller3.getCursor();
aanvaller3.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
aanvaller3.setBounds(20, 445, 168, 17);
aanvaller3.setFocusable(false);
aanvaller3.setBorderPainted(false);
aanvaller3.setContentAreaFilled(false);
aanvaller3.setFont(new Font("Arial",Font.PLAIN,17));
aanvaller3.setForeground(Color.WHITE);
aanvaller3.setActionCommand(Dmitri);
label.add(aanvaller3);
SelectieController s1 = new SelectieController(keeper, foto, verdediger, verdediger1, verdediger2,
verdediger3, middenvelder, aanvaller, middenvelder1, aanvaller1, middenvelder2, aanvaller2,
verdediger4, verdediger5, middenvelder3, verdediger6, middenvelder4, aanvaller3, kruis);
keeper.addActionListener(s1);
verdediger.addActionListener(s1);
verdediger1.addActionListener(s1);
verdediger2.addActionListener(s1);
verdediger3.addActionListener(s1);
verdediger4.addActionListener(s1);
verdediger5.addActionListener(s1);
verdediger6.addActionListener(s1);
middenvelder.addActionListener(s1);
aanvaller.addActionListener(s1);
middenvelder1.addActionListener(s1);
aanvaller1.addActionListener(s1);
middenvelder2.addActionListener(s1);
aanvaller2.addActionListener(s1);
middenvelder3.addActionListener(s1);
middenvelder4.addActionListener(s1);
aanvaller3.addActionListener(s1);
}
}
Kruis is the image in the midd of the screen a=
ActionPerformed class:
package Controller;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class SelectieController implements ActionListener {
private JButton keeper, verdediger, verdediger1, verdediger2, verdediger3;
private JButton middenvelder, aanvaller, middenvelder1, aanvaller1, middenvelder2;
private JButton aanvaller2, verdediger4, verdediger5, middenvelder3, verdediger6;
private JButton middenvelder4, aanvaller3, kruis;
private ImageIcon imageIcon, imageIcon1, imageIcon2, imageIcon3, imageIcon4, imageIcon5;
private ImageIcon imageIcon6, imageIcon7, imageIcon8, imageIcon9, imageIcon10, imageIcon11;
private ImageIcon imageIcon12, imageIcon13, imageIcon14, imageIcon15, imageIcon16;
private JLabel imageLabel;
private Image image, image1, image2, image3, image4, image5, image6, image7, image8, image9;
private Image image10, image11, image12, image13, image14, image15, image16;
private static String Vermeer = "Vermeer";
private static String Gregory = "Gregory";
private static String Alderweireld = "Alderweireld";
private static String Vertonghen = "Vertonghen";
private static String Anita = "Anita";
private static String Enoh = "Enoh";
private static String Sulejmani = "Sulejmani";
private static String Cristian = "Cristian";
private static String Kolbeinn = "Kolbeinn";
private static String Siem = "Siem";
private static String Lorenzo = "Lorenzo";
private static String Andre = "Andre";
private static String Nicolai = "Nicolai";
private static String Theo = "Theo";
private static String Daley = "Daley";
private static String Nicolas = "Nicolas";
private static String Dmitri = "Dmitri";
private static String Kruis = "Kruis";
public SelectieController(JButton vermeer, JLabel vermeer1, JButton gregory, JButton toby, JButton jan,
JButton vurnon, JButton eyong, JButton sulejmani, JButton cristian, JButton kolbeinn, JButton siem,
JButton lorenzo, JButton andre, JButton nicolai, JButton theo, JButton daley, JButton nicolas,
JButton dmitri, JButton kruis)
{
kruis = kruis;
keeper = vermeer;
verdediger1 = toby;
verdediger = gregory;
verdediger2 = jan;
verdediger3 = vurnon;
middenvelder = eyong;
aanvaller = sulejmani;
aanvaller1 = kolbeinn;
middenvelder1 = cristian;
imageLabel = vermeer1;
middenvelder2 = siem;
aanvaller2 = lorenzo;
verdediger4 = andre;
verdediger5 = nicolai;
middenvelder3 = theo;
verdediger6 = daley;
middenvelder4 = nicolas;
aanvaller3 = dmitri;
//Kenneth Vermeer
try
{
image = ImageIO.read(getClass().getResource("/img/kenneth.png"));
}
catch(Exception e)
{
e.printStackTrace();
}
imageIcon = new ImageIcon(image);
}{
// Gregory van der Wiel
try
{
image1 = ImageIO.read(getClass().getResource("/img/wiel.png"));
}
catch(Exception e)
{
e.printStackTrace();
}
imageIcon1 = new ImageIcon(image1);
}{
// Toby Alderweireld
try
{
image2 = ImageIO.read(getClass().getResource("/img/toby.png"));
}
catch(Exception e)
{
e.printStackTrace();
}
imageIcon2 = new ImageIcon(image2);
}{
// Jan Vertonghen
try
{
image3 = ImageIO.read(getClass().getResource("/img/jan.png"));
}
catch(Exception e)
{
e.printStackTrace();
}
imageIcon3 = new ImageIcon(image3);
}{
// Vurnon anita
try
{
image4 = ImageIO.read(getClass().getResource("/img/vurnon.png"));
}
catch(Exception e)
{
e.printStackTrace();
}
imageIcon4 = new ImageIcon(image4);
}{
// Eyong Enoh
try
{
image5 = ImageIO.read(getClass().getResource("/img/eyong.png"));
}
catch(Exception e)
{
e.printStackTrace();
}
imageIcon5 = new ImageIcon(image5);
}{
// Miralem Sulejmani
try
{
image6 = ImageIO.read(getClass().getResource("/img/sulejmani.png"));
}
catch(Exception e)
{
e.printStackTrace();
}
imageIcon6 = new ImageIcon(image6);
}{
// Cristian Eriksen
try
{
image7 = ImageIO.read(getClass().getResource("/img/eriksen.png"));
}
catch(Exception e)
{
e.printStackTrace();
}
imageIcon7 = new ImageIcon(image7);
}{
// Kolbeinn sightorsson
try
{
image8 = ImageIO.read(getClass().getResource("/img/kolbeinn.png"));
}
catch(Exception e)
{
e.printStackTrace();
}
imageIcon8 = new ImageIcon(image8);
}{
// Siem de Jong
try
{
image9 = ImageIO.read(getClass().getResource("/img/siem.png"));
}
catch(Exception e)
{
e.printStackTrace();
}
imageIcon9 = new ImageIcon(image9);
}{
// Lorenzo Ebecilio
try
{
image10 = ImageIO.read(getClass().getResource("/img/lorenzo.png"));
}
catch(Exception e)
{
e.printStackTrace();
}
imageIcon10 = new ImageIcon(image10);
}{
// Andre Ooijer
try
{
image11 = ImageIO.read(getClass().getResource("/img/andre.png"));
}
catch(Exception e)
{
e.printStackTrace();
}
imageIcon11 = new ImageIcon(image11);
}{
// Nicolai Boilesen
try
{
image12 = ImageIO.read(getClass().getResource("/img/nicolai.png"));
}
catch(Exception e)
{
e.printStackTrace();
}
imageIcon12 = new ImageIcon(image12);
}{
// Theo Janssen
try
{
image13 = ImageIO.read(getClass().getResource("/img/theo.png"));
}
catch(Exception e)
{
e.printStackTrace();
}
imageIcon13 = new ImageIcon(image13);
}{
// Daley Blind
try
{
image14 = ImageIO.read(getClass().getResource("/img/daley.png"));
}
catch(Exception e)
{
e.printStackTrace();
}
imageIcon14 = new ImageIcon(image14);
}{
// Nicolas Lodeiro
try
{
image15 = ImageIO.read(getClass().getResource("/img/nicolas.png"));
}
catch(Exception e)
{
e.printStackTrace();
}
imageIcon15 = new ImageIcon(image15);
}{
// Dmitri Bulykin
try
{
image16 = ImageIO.read(getClass().getResource("/img/dmitri.png"));
}
catch(Exception e)
{
e.printStackTrace();
}
imageIcon16 = new ImageIcon(image16);
}
public void actionPerformed(ActionEvent event)
{
String actionCommand = event.getActionCommand();
// Kenneth Vermeer
if (Vermeer.equals(actionCommand))
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
imageLabel.setIcon(imageIcon );
imageLabel.setBounds(75, 50, 120, 150);
kruis.setVisible(false);
}
});
}
// Gregory van der Wiel
if (Gregory.equals(actionCommand))
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
imageLabel.setIcon(imageIcon1 );
imageLabel.setBounds(75, 50, 120, 150);
}
});
}
// Toby Alderweireld
if (Alderweireld.equals(actionCommand))
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
imageLabel.setIcon(imageIcon2 );
imageLabel.setBounds(75, 50, 120, 150);
}
});
}
// Jan Vertonghen
if (Vertonghen.equals(actionCommand))
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
imageLabel.setIcon(imageIcon3 );
imageLabel.setBounds(75, 50, 120, 150);
}
});
}
//Vurnon Anita
if (Anita.equals(actionCommand))
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
imageLabel.setIcon(imageIcon4 );
imageLabel.setBounds(75, 50, 120, 150);
}
});
}
// Eyong Enoh
if (Enoh.equals(actionCommand))
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
imageLabel.setIcon(imageIcon5 );
imageLabel.setBounds(75, 50, 120, 150);
}
});
}
// Miralem Sulejmani
if (Sulejmani.equals(actionCommand))
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
imageLabel.setIcon(imageIcon6 );
imageLabel.setBounds(75, 50, 120, 150);
}
});
}
}}
First, whenever you have elements with names like button1, button2 etc. you need to refactor the code and work with an array instead. This way you can refer to the needed element using its index, instead of many if-else statements. That's applies for the Strings , Buttons, Images and ImageIcons.
Now, when a button is pressed, find it's index (in a loop for example) and make all other button/images disappear, using setVisible(false), and only the relevant image display using setVisible(true).
I got the following code from http://robin.mytechtip.com/2010/11/17/gwt-celltable-example-using-asyncdataprovider/#comment-920. I am trying to get it to work with uibinder. The result is that all data is shown in the celltable and therefore the simplePager navigation is disabled.
package com.example.random.client.view;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import com.example.random.shared.Contact;
import com.google.gwt.cell.client.DateCell;
import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.SimplePager;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.AsyncDataProvider;
import com.google.gwt.view.client.HasData;
public class HtmlBinder extends Composite {
private static HtmlBinderUiBinder uiBinder = GWT
.create(HtmlBinderUiBinder.class);
interface HtmlBinderUiBinder extends UiBinder<Widget, HtmlBinder> {
}
#SuppressWarnings("deprecation")
private static final List<Contact> CONTACTS = Arrays.asList(new Contact(
"John", new Date(80, 4, 12), "123 Abc Avenue"), new Contact("Joe",
new Date(85, 2, 22), "22 Lance Ln"), new Contact("Tom", new Date(
85, 3, 22), "33 Lance Ln"), new Contact("Jack",
new Date(85, 4, 22), "44 Lance Ln"), new Contact("Tim", new Date(
85, 5, 22), "55 Lance Ln"), new Contact("Mike",
new Date(85, 6, 22), "66 Lance Ln"), new Contact("George",
new Date(46, 6, 6), "77 Lance Ln"));
/**
* The main CellTable.
*/
#UiField(provided = true)
CellTable<Contact> cellTable;
/**
* The pager used to change the range of data.
*/
#UiField(provided = true)
SimplePager pager;
public HtmlBinder() {
pager = new SimplePager();
cellTable = new CellTable<Contact>(3);
initWidget(uiBinder.createAndBindUi(this));
setupCellTable();
setupSimplePager();
}
private void setupSimplePager() {
pager.setDisplay(cellTable);
}
private void setupCellTable() {
// Add a text column to show the name.
TextColumn<Contact> nameColumn = new TextColumn<Contact>() {
#Override
public String getValue(Contact object) {
return object.getName();
}
};
cellTable.addColumn(nameColumn, "Name");
// Add a date column to show the birthday.
DateCell dateCell = new DateCell();
Column<Contact, Date> dateColumn = new Column<Contact, Date>(dateCell) {
#Override
public Date getValue(Contact object) {
return object.getBirthday();
}
};
cellTable.addColumn(dateColumn, "Birthday");
// Add a text column to show the address.
TextColumn<Contact> addressColumn = new TextColumn<Contact>() {
#Override
public String getValue(Contact object) {
return object.getAddress();
}
};
cellTable.addColumn(addressColumn, "Address");
// Associate an async data provider to the table
// XXX: Use AsyncCallback in the method onRangeChanged
// to actaully get the data from the server side
AsyncDataProvider<Contact> provider = new AsyncDataProvider<Contact>() {
#Override
protected void onRangeChanged(HasData<Contact> display) {
int start = display.getVisibleRange().getStart();
int end = start + display.getVisibleRange().getLength();
end = end >= CONTACTS.size() ? CONTACTS.size() : end;
List<Contact> sub = CONTACTS.subList(start, end);
updateRowData(start, sub);
}
};
provider.addDataDisplay(cellTable);
provider.updateRowCount(CONTACTS.size(), true);
}
}
Entrypoint ...
public void onModuleLoad() {
RootLayoutPanel.get().add(new HtmlBinder());
}
I would like to use multiple-page editor (eclipse RCP). I want to follow this tutorial
but I cannot get "plug-in with multiple page editor" when I create a new project. I have only :
Hello
with a view
with an introduction
mail template
Does anyone have an idea about how to get the option plug-in with multiple page editor when creating a new RCP project?
Thnx
PS: I use Galileo 3.5.2
Please use the Eclipse Indigo instead.
Otherwise, you can create from the empty plugin project.
Here is my example of multiple pages editor. PropertyFileEditor is multiple pages editor. Hope this will help you.
FileDocumentProvider.java
package com.bosch.training.eclipseplugin.editors;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Map.Entry;
import java.util.Properties;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DocumentEvent;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IDocumentListener;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.part.MultiPageEditorPart;
import com.bosch.training.eclipseplugin.LinkedProperties;
public class PropertyFileEditor extends MultiPageEditorPart {
public static String EDITOR_ID = "com.bosch.training.eclipseplugin.editors.PropertyFileEditor";
private Text m_keyText;
private Text m_valueText;
private TableViewer m_tableViewer;
private IPath m_filePath;
private Properties m_properties;
private FileEditor m_firstPage;
public PropertyFileEditor() {
}
#Override
protected void createPages() {
try {
m_filePath = ((FileEditorInput) getEditorInput()).getFilePath();
m_firstPage = new FileEditor();
addPage(m_firstPage, (FileEditorInput) getEditorInput());
addPage(createDesignPage());
setPagesText();
} catch (PartInitException e) {
e.printStackTrace();
}
}
private void setPagesText() {
setPageText(0, "Plain Text");
setPageText(1, "Properties");
}
#Override
public void doSave(IProgressMonitor monitor) {
m_firstPage.doSave(monitor);
}
#Override
public void doSaveAs() {
}
#Override
public boolean isSaveAsAllowed() {
return false;
}
private Control createDesignPage() {
Composite parent = new Composite(getContainer(), SWT.NONE);
parent.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
parent.setLayout(new GridLayout(1, false));
// First row
Composite composite1 = new Composite(parent, SWT.NONE);
composite1.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
composite1.setLayout(new GridLayout(3, false));
m_keyText = new Text(composite1, SWT.SINGLE | SWT.LEAD | SWT.BORDER);
m_keyText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
m_keyText.setText("");
m_valueText = new Text(composite1, SWT.SINGLE | SWT.LEAD | SWT.BORDER);
m_valueText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
m_valueText.setText("");
Button applyButton = new Button(composite1, SWT.PUSH);
applyButton.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false));
applyButton.setText("Apply");
applyButton.addSelectionListener(new SelectionListener() {
#Override
public void widgetSelected(SelectionEvent e) {
m_properties.put(m_keyText.getText(), m_valueText.getText());
// Update table
TableItem tableItem= new TableItem(m_tableViewer.getTable(), SWT.NONE);
tableItem.setText(new String[] { m_keyText.getText(), m_valueText.getText() });
// Update editor
IDocument doc = m_firstPage.getDocumentProvider().getDocument(getEditorInput());
int offset;
try {
offset = doc.getLineOffset(doc.getNumberOfLines() - 1);
doc.replace(offset, 0, m_keyText.getText() + "=" + m_valueText.getText() + "\n");
} catch (BadLocationException ex) {
ex.printStackTrace();
}
// set text = ""
m_keyText.setText("");
m_valueText.setText("");
}
#Override
public void widgetDefaultSelected(SelectionEvent e) {
}
});
// Second row
Composite composite2 = new Composite(parent, SWT.NONE);
composite2.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
composite2.setLayout(new GridLayout(1, false));
m_tableViewer = new TableViewer(composite2, SWT.FILL);
Table table = m_tableViewer.getTable();
table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
TableColumn columnKey = new TableColumn(table, SWT.LEAD);
columnKey.setText("Key");
columnKey.setWidth(300);
TableColumn columnValue = new TableColumn(table, SWT.FILL);
columnValue.setText("Value");
columnValue.setWidth(300);
table.setHeaderVisible(true);
table.setLinesVisible(true);
m_tableViewer.setContentProvider(new IStructuredContentProvider() {
#Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
#Override
public void dispose() {
}
#Override
public Object[] getElements(Object inputElement) {
return (Object[]) inputElement;
}
});
m_tableViewer.setLabelProvider(new ITableLabelProvider() {
#Override
public void removeListener(ILabelProviderListener listener) {
}
#Override
public boolean isLabelProperty(Object element, String property) {
return false;
}
#Override
public void dispose() {
}
#Override
public void addListener(ILabelProviderListener listener) {
}
#Override
public String getColumnText(Object element, int columnIndex) {
if (element instanceof Entry) {
switch (columnIndex) {
case 0:
return String.valueOf(((Entry) element).getKey());
case 1:
return String.valueOf(((Entry) element).getValue());
}
}
return "";
}
#Override
public Image getColumnImage(Object element, int columnIndex) {
return null;
}
});
m_tableViewer.setInput(loadProperties());
m_firstPage.getDocumentProvider().getDocument(getEditorInput()).addDocumentListener(new IDocumentListener() {
#Override
public void documentChanged(DocumentEvent event) {
m_tableViewer.setInput(loadProperties());
}
#Override
public void documentAboutToBeChanged(DocumentEvent event) {
}
});
return parent;
}
private Object[] loadProperties() {
IDocument document = m_firstPage.getFileDocumentProvider().getDocument(getEditorInput());
m_properties = new LinkedProperties();
ByteArrayInputStream inputStream = null;
try {
inputStream = new ByteArrayInputStream(document.get().getBytes());
m_properties.load(inputStream);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
}
}
}
return m_properties.entrySet().toArray();
}
}
FileEditor.java
package com.bosch.training.eclipseplugin.editors;
import org.eclipse.ui.texteditor.AbstractTextEditor;
import org.eclipse.ui.texteditor.ITextEditorExtension3;
public class FileEditor extends AbstractTextEditor {
public static final String EDITOR_ID = "com.bosch.training.eclipseplugin.editors.FileEditor";
private FileDocumentProvider m_fileDocumentProvider;
public FileEditor() {
setKeyBindingScopes(new String[] { "org.eclipse.ui.textEditorScope" });
internal_init();
}
protected void internal_init() {
configureInsertMode(ITextEditorExtension3.SMART_INSERT, false);
m_fileDocumentProvider = new FileDocumentProvider();
setDocumentProvider(m_fileDocumentProvider);
}
public FileDocumentProvider getFileDocumentProvider() {
return m_fileDocumentProvider;
}
}
FileEditorInput.java
package com.bosch.training.eclipseplugin.editors;
import org.eclipse.core.runtime.IPath;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.IPathEditorInput;
import org.eclipse.ui.IPersistableElement;
import org.eclipse.ui.PlatformUI;
public class FileEditorInput implements IPathEditorInput {
private IPath m_filePath;
public FileEditorInput(IPath path) {
if (path == null) {
throw new IllegalArgumentException();
}
this.m_filePath = path;
}
#Override
public int hashCode() {
return m_filePath.hashCode();
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof FileEditorInput)) {
return false;
}
FileEditorInput other = (FileEditorInput) obj;
return m_filePath.equals(other.m_filePath);
}
#Override
public boolean exists() {
return m_filePath.toFile().exists();
}
#Override
public ImageDescriptor getImageDescriptor() {
return PlatformUI.getWorkbench().getEditorRegistry().getImageDescriptor(m_filePath.toString());
}
#Override
public String getName() {
return m_filePath.toString();
}
#Override
public String getToolTipText() {
return m_filePath.makeRelative().toOSString();
}
#Override
public IPath getPath() {
return m_filePath;
}
#SuppressWarnings("rawtypes")
#Override
public Object getAdapter(Class adapter) {
return null;
}
#Override
public IPersistableElement getPersistable() {
// no persistence
return null;
}
public IPath getFilePath() {
return m_filePath;
}
public void setFilePath(IPath filePath) {
m_filePath = filePath;
}
}
PropertyFileEditor.java
package com.bosch.training.eclipseplugin.editors;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Map.Entry;
import java.util.Properties;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DocumentEvent;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IDocumentListener;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.part.MultiPageEditorPart;
import com.bosch.training.eclipseplugin.LinkedProperties;
public class PropertyFileEditor extends MultiPageEditorPart {
public static String EDITOR_ID = "com.bosch.training.eclipseplugin.editors.PropertyFileEditor";
private Text m_keyText;
private Text m_valueText;
private TableViewer m_tableViewer;
private IPath m_filePath;
private Properties m_properties;
private FileEditor m_firstPage;
public PropertyFileEditor() {
}
#Override
protected void createPages() {
try {
m_filePath = ((FileEditorInput) getEditorInput()).getFilePath();
m_firstPage = new FileEditor();
addPage(m_firstPage, (FileEditorInput) getEditorInput());
addPage(createDesignPage());
setPagesText();
} catch (PartInitException e) {
e.printStackTrace();
}
}
private void setPagesText() {
setPageText(0, "Plain Text");
setPageText(1, "Properties");
}
#Override
public void doSave(IProgressMonitor monitor) {
m_firstPage.doSave(monitor);
}
#Override
public void doSaveAs() {
}
#Override
public boolean isSaveAsAllowed() {
return false;
}
private Control createDesignPage() {
Composite parent = new Composite(getContainer(), SWT.NONE);
parent.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
parent.setLayout(new GridLayout(1, false));
// First row
Composite composite1 = new Composite(parent, SWT.NONE);
composite1.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
composite1.setLayout(new GridLayout(3, false));
m_keyText = new Text(composite1, SWT.SINGLE | SWT.LEAD | SWT.BORDER);
m_keyText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
m_keyText.setText("");
m_valueText = new Text(composite1, SWT.SINGLE | SWT.LEAD | SWT.BORDER);
m_valueText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
m_valueText.setText("");
Button applyButton = new Button(composite1, SWT.PUSH);
applyButton.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false));
applyButton.setText("Apply");
applyButton.addSelectionListener(new SelectionListener() {
#Override
public void widgetSelected(SelectionEvent e) {
m_properties.put(m_keyText.getText(), m_valueText.getText());
// Update table
TableItem tableItem= new TableItem(m_tableViewer.getTable(), SWT.NONE);
tableItem.setText(new String[] { m_keyText.getText(), m_valueText.getText() });
// Update editor
IDocument doc = m_firstPage.getDocumentProvider().getDocument(getEditorInput());
int offset;
try {
offset = doc.getLineOffset(doc.getNumberOfLines() - 1);
doc.replace(offset, 0, m_keyText.getText() + "=" + m_valueText.getText() + "\n");
} catch (BadLocationException ex) {
ex.printStackTrace();
}
// set text = ""
m_keyText.setText("");
m_valueText.setText("");
}
#Override
public void widgetDefaultSelected(SelectionEvent e) {
}
});
// Second row
Composite composite2 = new Composite(parent, SWT.NONE);
composite2.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
composite2.setLayout(new GridLayout(1, false));
m_tableViewer = new TableViewer(composite2, SWT.FILL);
Table table = m_tableViewer.getTable();
table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
TableColumn columnKey = new TableColumn(table, SWT.LEAD);
columnKey.setText("Key");
columnKey.setWidth(300);
TableColumn columnValue = new TableColumn(table, SWT.FILL);
columnValue.setText("Value");
columnValue.setWidth(300);
table.setHeaderVisible(true);
table.setLinesVisible(true);
m_tableViewer.setContentProvider(new IStructuredContentProvider() {
#Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
#Override
public void dispose() {
}
#Override
public Object[] getElements(Object inputElement) {
return (Object[]) inputElement;
}
});
m_tableViewer.setLabelProvider(new ITableLabelProvider() {
#Override
public void removeListener(ILabelProviderListener listener) {
}
#Override
public boolean isLabelProperty(Object element, String property) {
return false;
}
#Override
public void dispose() {
}
#Override
public void addListener(ILabelProviderListener listener) {
}
#Override
public String getColumnText(Object element, int columnIndex) {
if (element instanceof Entry) {
switch (columnIndex) {
case 0:
return String.valueOf(((Entry) element).getKey());
case 1:
return String.valueOf(((Entry) element).getValue());
}
}
return "";
}
#Override
public Image getColumnImage(Object element, int columnIndex) {
return null;
}
});
m_tableViewer.setInput(loadProperties());
m_firstPage.getDocumentProvider().getDocument(getEditorInput()).addDocumentListener(new IDocumentListener() {
#Override
public void documentChanged(DocumentEvent event) {
m_tableViewer.setInput(loadProperties());
}
#Override
public void documentAboutToBeChanged(DocumentEvent event) {
}
});
return parent;
}
private Object[] loadProperties() {
IDocument document = m_firstPage.getFileDocumentProvider().getDocument(getEditorInput());
m_properties = new LinkedProperties();
ByteArrayInputStream inputStream = null;
try {
inputStream = new ByteArrayInputStream(document.get().getBytes());
m_properties.load(inputStream);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
}
}
}
return m_properties.entrySet().toArray();
}
}
I cannot tell you, if this template is available in Galileo. It is in Indigo.
But this template just combines two steps you can do on your own. Create an empty plugin project, open the MANIFEST.MF to open the plugin editor and select the extension tabs.
There you can add extension for editors and for wizards.
For a multipage editor click on Add, then select org.eclipse.ui.editors. In the template area at the bottom of the dialog select Multi-Page editor. Then enter the properties as show in your tutorial.
Repeat for the new wizard by selectin org.eclipse.ui.newWizard and the New File Wizard template.