Get graphic of TableCell - tableview

I have implemented a custom TableCell & TableColumn to show a hyperlink while the cell is not editing. I want to add setOnAction event for the hyperlink. As i want to reuse the TableCell i cannot add the code in TableCell updateItem method. Is there any way to implement this?
public class TableColumnHyperlink<S> extends TableColumn<S, String> {
public TableColumnHyperlink (String header) {
super(header);
Callback<TableColumn<S, String>, TableCell<S, String>> hypCellFactory =
(TableColumn<S, String> p) -> new TableCellHyperlink();
setCellFactory(hypCellFactory);
}
}
And the TableCell implementation is
public class TableCellHyperlink<S> extends TableCell<S, String> {
private final TextField textField;
private final Hyperlink hyperlink;
public TableCellHyperlink() {
textField = new TextField();
hyperlink = new Hyperlink();
setAlignment(Pos.CENTER_LEFT);
}
#Override
public void startEdit() {
super.startEdit();
createTextField();
setText(null);
setGraphic(textField);
textField.requestFocus();
}
#Override
public void cancelEdit() {
super.cancelEdit();
setText(getItem());
setGraphic(null);
}
#Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty && (getTableRow() == null ? true : getTableRow().isEmpty()));
if (empty) {
setText(null);
setGraphic(null);
} else {
if(isEditing()) {
setText(getString());
setGraphic(textField);
} else {
setText(null);
hyperlink.setText(getString());
setGraphic(hyperlink);
}
}
}
private void createTextField() {
textField.setText(getString());
textField.setMinWidth(this.getWidth() - this.getGraphicTextGap() * 2);
textField.addEventFilter(KeyEvent.KEY_PRESSED, (KeyEvent t) -> {
if (t.getCode() == KeyCode.ENTER) {
commitEdit(textField.getText());
} else if (t.getCode() == KeyCode.ESCAPE) {
cancelEdit();
}
});
}
private String getString() {
return (getItem() != null)?getItem():"";
}
}

If the event handler implementation will vary by instance, you need to pass the event handler (or a function) into the constructor. Since you probably need to access the cell, you'll do something like
public class TableCellHyperlink<S> extends TableCell<S, String> {
private final TextField textField;
private final Hyperlink hyperlink;
public TableCellHyperlink(Consumer<TableCellHyperlink<S> handlerFunction) {
textField = new TextField();
hyperlink = new Hyperlink();
hyperlink.setOnAction(event -> handlerFunction.accept(this));
setAlignment(Pos.CENTER_LEFT);
}
// ...
}
Now you can do something like
TableCellHyperlink<MyType> hyperlinkCell = new TableCellHyperlink<>(cell -> {
MyType rowValue = (MyType) cell.getTableRow().getValue(); // getTableRow() returns TableRow, not TableRow<MyType>
String cellValue = cell.getItem();
// implement action
});
Obviously you can move the parameter up and pass it into the custom TableColumn constructor if you like.

Related

How to sort column in TableView JavaFx?

I'm trying to sort the columns by clicking the column head. The problem is that he does not sort the column defined as Integer.
I wrote comparator for Integer but I think that this is not the way to sort column.
The code below belongs the client:
public class Client4 extends Application
{ // IO streams
private DataOutputStream toServer = null;
private DataInputStream fromServer = null;
private TableView<Student> tableView = new TableView<Student>();
private ObservableList<Student> data = FXCollections.observableArrayList();
private ComboBox<String> cboStudent = new ComboBox<>();
private ComboBox<String> cboLecturer = new ComboBox<>();
private ArrayList<TableColumn> tableCol = new ArrayList<TableColumn>();
private Callback<TableColumn<Student, String>, TableCell<Student, String>> cellFactory
= (TableColumn<Student, String> p) -> new EditingCell();
#Override // Override the start method in the Application class
public void start(Stage primaryStage) throws Exception
{ // Panel p to hold the label and text field
Button btAddRow = new Button("Add Student");
Button btDeleteRow = new Button("Delete Student");
Button btEdit = new Button("Edit");
Button btAddColumn = new Button("Add Column");
Button btDeleteColumn = new Button("Delete Column");
tableView.setItems(data);
//tableView.setEditable(true);
// Callback<TableColumn<Student, String>, TableCell<Student, String>> cellFactory
// = (TableColumn<Student, String> p) -> new EditingCell();
BorderPane pane = new BorderPane();
pane.setPadding(new Insets(11.5, 12.5, 13.5, 14.5));
HBox hBox = new HBox(20);
hBox.getChildren().addAll(btAddRow, btDeleteRow,
btEdit, btAddColumn, btDeleteColumn);
pane.setTop(hBox);
try {
// #SuppressWarnings("resource")
Socket socket = new Socket("localhost", 8000);
// Create an input stream to receive data from the server
fromServer = new DataInputStream(socket.getInputStream());
// Create an output stream to send data to the server
toServer = new DataOutputStream(socket.getOutputStream());
ArrayList<String> lables = new ArrayList<String>();
int numberRecords=0;
numberRecords = fromServer.readInt();
System.out.println(numberRecords);
while (numberRecords>0)
{ String record =fromServer.readUTF();
lables.add(record);
cboStudent.getItems().add(record);
numberRecords--;
}
for(int i=0; i<lables.size();i++)
{
String lable = lables.get(i);
TableColumn<Student, String> string = new TableColumn<Student, String>(lable);
string.setMinWidth(100);
if (lable.equals("firstName") || lable.equals("lastName") || lable.equals("city") || lable.equals("street") || lable.equals("dept") )
{
string.setCellValueFactory(
new PropertyValueFactory<Student, String>(lable));
defineCell(string);
// ObservableList<String> cbValues = FXCollections.observableArrayList("1", "2", "3");
// string.setCellFactory(ComboBoxTableCell.forTableColumn(new DefaultStringConverter(), cbValues));
tableView.getColumns().add(string);
tableCol.add(string);
}
else if(lable.equals("birthDate"))
{
TableColumn<Student, Date> date = new TableColumn<Student, Date>(lable);
date.setCellValueFactory(
new PropertyValueFactory<Student, Date>(lable));
//defineCell(date);
tableView.getColumns().add(date);
tableCol.add(date);
}
else if(lable.equals("picture"))
{
TableColumn<Student, ImageView> pic = new TableColumn<Student, ImageView>(lable);
pic.setCellValueFactory(
new PropertyValueFactory<Student, ImageView>(lable));
tableView.getColumns().add(pic);
tableCol.add(pic);
}
else
{
TableColumn<Student, Integer> integer = new TableColumn<Student, Integer>(lable);
integer.setCellValueFactory(
new PropertyValueFactory<Student, Integer>(lable));
integer.setSortable(true);
integer.setComparator(new Comparator<Integer>() {
#Override
public int compare(Integer o1, Integer o2) {
if(o1<o2) return 1;
if(o1>o2)return -1;
return 0;
}
});
tableView.getColumns().add(integer);
tableCol.add(integer);
}
}
numberRecords=0;
numberRecords=fromServer.readInt();
while(numberRecords>0)
{ Student student = new Student();
student.setId(fromServer.readUTF());
student.setFirstName(fromServer.readUTF());
student.setLastName(fromServer.readUTF());
student.setCity(fromServer.readUTF());
student.setStreet(fromServer.readUTF());
student.setHouseNumber(fromServer.readUTF());
student.setZipCode(fromServer.readUTF());
student.setBirthDate(fromServer.readUTF());
student.setPicture(fromServer.readUTF());
student.setStartYear(fromServer.readUTF());
student.setDept(fromServer.readUTF());
student.setCredits(fromServer.readUTF());
student.setAverage(fromServer.readUTF());
student.setNumFailed(fromServer.readUTF());
student.setPlace(fromServer.readUTF());
System.out.println(student);
data.add(student);
numberRecords--;
}
tableView.setItems(data);
}
catch (IOException ex) {
}
btEdit.setOnAction(e -> {
editTable(btEdit.toString());
});
pane.setBottom(tableView);
Scene scene = new Scene(pane, 890, 400);
primaryStage.setTitle("ShowCombination"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
primaryStage.setAlwaysOnTop(true);
}
private void defineCell(TableColumn<Student, String> string) {
string.setCellFactory(cellFactory);
string.setOnEditCommit(
(CellEditEvent<Student, String> t) -> {
((Student) t.getTableView().getItems().get(
t.getTablePosition().getRow())
).setFirstName(t.getNewValue());
});
ObservableList<String> cbValues = FXCollections.observableArrayList("1", "2", "3");
string.setCellFactory(ComboBoxTableCell.forTableColumn(new DefaultStringConverter(), cbValues));
}
private void editTable(String string) {
tableView.setEditable(true);
Student student=(Student)tableView.getSelectionModel().getSelectedItem();
}
public static void main(String[] args)
{ launch(args);
}
class EditingCell extends TableCell<Student, String> {
private TextField textField;
public EditingCell() {
}
#Override
public void startEdit() {
if (!isEmpty()) {
super.startEdit();
createTextField();
setText(null);
setGraphic(textField);
textField.selectAll();
}
}
#Override
public void cancelEdit() {
super.cancelEdit();
setText((String) getItem());
setGraphic(null);
}
#Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
setGraphic(null);
} else {
if (isEditing()) {
if (textField != null) {
textField.setText(getString());
}
setText(null);
setGraphic(textField);
} else {
setText(getString());
setGraphic(null);
}
}
}
private void createTextField() {
textField = new TextField(getString());
textField.setMinWidth(this.getWidth() - this.getGraphicTextGap()* 2);
textField.focusedProperty().addListener(
(ObservableValue<? extends Boolean> arg0,
Boolean arg1, Boolean arg2) -> {
if (!arg2) {
commitEdit(textField.getText());
}
});
}
private String getString() {
return getItem() == null ? "" : getItem().toString();
}
}
}
You need to wrap your ObservableList holding the TableView data in a SortedList:
SortedList<Student> sortedItems = new SortedList<>(data);
tableView.setItems(sortedItems);
Next you need to link both together:
sortedItems.comparatorProperty().bind(tableView.comparatorProperty());
And as a friendly side note: Please consider posting a smaller code example showing only what is necessary to demonstrate your problem ;-)
As James_D says, cube root will sort in the same order, but here's a little example you can use to show what you're trying to do
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import javafx.application.Application;
import javafx.beans.property.ReadOnlyObjectWrapper;
import javafx.collections.FXCollections;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.stage.Stage;
public class TableSort extends Application {
#Override
public void start(Stage primaryStage) {
TableView tv = new TableView(FXCollections.observableArrayList(
IntStream.of(1,-2,3,-4,-5,6)
.map(n->{return (int)Math.pow(n, 3);})
.boxed().collect(Collectors.toList())));
TableColumn<Integer, Integer> numCol = new TableColumn("num");
numCol.setCellValueFactory((param) -> {
return new ReadOnlyObjectWrapper<>(param.getValue());
});
TableColumn<Integer, Integer> cbrtCol = new TableColumn("cube root");
cbrtCol.setCellValueFactory((param) -> {
return new ReadOnlyObjectWrapper<>((int)Math.cbrt(param.getValue()));
});
numCol.setComparator((Integer o1, Integer o2) -> {
return Double.compare(Math.cbrt(o1), Math.cbrt(o2));
});
tv.getColumns().addAll(numCol, cbrtCol);
Scene scene = new Scene(tv);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}

TableView, setting editable cells

I try to make Table cells editable. I managed to do this with two Collumns that have String values in it, but I cant make this with columns that represent Integer values.
Places with X is where compiler get the error:
The method setCellFactory(Callback<TableColumn<DataModel,Integer>,TableCell<DataModel,Integer>>) in the type TableColumn<DataModel,Integer> is not applicable for the arguments (Callback<TableColumn<DataModel,String>,TableCell<DataModel,String>>)
and places with XX is where compiler get the error:
The method setOnEditCommit(EventHandler<TableColumn.CellEditEvent<DataModel,Integer>>) in the type TableColumn<DataModel,Integer> is not applicable for the arguments ((CellEditEvent<DataModel, Integer> event) -> {})
Heres the code:
public void initialize(URL location, ResourceBundle resources) {
//Tworzymy sobie kolumny, które będą odpowiadać oraz przyjmować konretne dane
TableColumn<DataModel, String> nameColumn = new TableColumn<DataModel, String>("Name");
nameColumn.setMinWidth(100);
TableColumn<DataModel, String> surnameColumn = new TableColumn<DataModel, String>("Surname");
surnameColumn.setMinWidth(100);
TableColumn<DataModel, Integer> ageColumn = new TableColumn<DataModel, Integer>("Age");
ageColumn.setMinWidth(100);
TableColumn<DataModel, Integer> telNumberColumn = new TableColumn<DataModel, Integer>("Tel. Number");
telNumberColumn.setMinWidth(100);
//dodajemy kolumny do okna
tableView.getColumns().addAll(nameColumn,surnameColumn,ageColumn,telNumberColumn);
//podajemy nazwy zmiennych, których wartości mają się wyświetlać w poszczególnych kolumnach
nameColumn.setCellValueFactory(new PropertyValueFactory<>("sName"));
surnameColumn.setCellValueFactory(new PropertyValueFactory<>("sSurname"));
ageColumn.setCellValueFactory(new PropertyValueFactory<>("iAge"));
telNumberColumn.setCellValueFactory(new PropertyValueFactory<>("iPhoneNumber"));
//Sprawiamy że poszczególne kolumny stają się edytowalne
nameColumn.setCellFactory(TextFieldTableCell.<DataModel>forTableColumn());
nameColumn.setOnEditCommit((CellEditEvent<DataModel, String> event) -> {
((DataModel) event.getTableView().getItems(). get(event.getTablePosition().getRow())). setsName(event.getNewValue());
});
surnameColumn.setCellFactory(TextFieldTableCell.<DataModel>forTableColumn());
surnameColumn.setOnEditCommit((CellEditEvent<DataModel, String> event) -> {
((DataModel) event.getTableView().getItems(). get(event.getTablePosition().getRow())). setsSurname(event.getNewValue());
});
X ageColumn.setCellFactory(TextFieldTableCell.<DataModel>forTableColumn());
XX ageColumn.setOnEditCommit((CellEditEvent<DataModel, Integer> event) -> {
// ((DataModel) event.getTableView().getItems(). get(event.getTablePosition().getRow())). setiAge(Integer.valueOf(event.getNewValue()));
});
X telNumberColumn.setCellFactory(TextFieldTableCell.<DataModel>forTableColumn());
XX telNumberColumn.setOnEditCommit((CellEditEvent<DataModel, Integer> event) -> {
// ((DataModel) event.getTableView().getItems(). get(event.getTablePosition().getRow())). setiPhoneNumber(Integer.valueOf(event.getNewValue()));
});
tableView.setPlaceholder(new Label("Pust tabelka!"));//jaki element dodać jeśli tabelka nie jest wyświetlona
tableView.setEditable(true);
tableView.setItems(dataList); //wczytujemy dane do przygotowanej tabelki
buttAdd.setOnAction((ActionEvent e) -> {
buttAddAction(e);
});
}
Im taking oracle TableView tutorial, and its quite difficult. Help.
The issue is that TextFieldTableCell.forTableColumn() is typed to a String value. See the default implementation:
public static <S> Callback<TableColumn<S,String>, TableCell<S,String>> forTableColumn() {
return forTableColumn(new DefaultStringConverter());
}
What you need is the TextFieldTableCell with an IntegerStringConverter, for example:
ageColumn.setCellFactory(TextFieldTableCell.<DataModel, Integer>forTableColumn(new IntegerStringConverter()));
I searched through a lot of answers and I've borrowed/extended/merged to this solution. Edits are committed when focus moves from edited cell. I have a public class for each datatype that can be represented in a table: EditingTextCell, EditingIntegerCell etc. These public classes can be applied to any table provided that the data is represented as an observable list of a class that accesses the data to be displayed as properties. I publish this solution because I was faced with creating a class for each column of each table in my application. Currently, the double value and combobox cell versions are tied to specific columns of specific tables. I'll do a generalized version of these as time permits. Please forgive my not presenting the source links -- I forgot to bookmark them as I perused them.
Java documentation suggests that easier ways of doing this are forthcoming.
Example usage for Integer field:
TableColumn<Factor, Number> noLevelsCol =
new TableColumn<>("No. Levels");
noLevelsCol.setCellValueFactory(
new PropertyValueFactory("numberLevels"));
noLevelsCol.setMinWidth(40);
noLevelsCol.setCellFactory(col -> new EditingIntegerCell<>());
noLevelsCol.setOnEditCommit((CellEditEvent<Factor, Number> t) -> {
((Factor) t.getTableView().getItems().get(
t.getTablePosition().getRow())
).setNumberLevels(t.getNewValue().intValue());
});
Example usage for String field:
TableColumn<Factor, String> nameCol = new TableColumn<>("Name");
nameCol.setMinWidth(60);
nameCol.setCellValueFactory(
new PropertyValueFactory("factorName"));
nameCol.setCellFactory(cellFactory);
nameCol.setOnEditCommit((CellEditEvent<Factor, String> t) -> {
((Factor) t.getTableView().getItems().get(
t.getTablePosition().getRow())
).setFactorName(t.getNewValue());
});
Definition of Factor class:
public class Factor {
private final IntegerProperty factorID = new SimpleIntegerProperty();
public IntegerProperty getFactorID() { return factorID; }
private StringProperty factorName = new SimpleStringProperty();
public void setFactorName(String value) {
factorNameProperty().set(value); }
public String getFactorName() { return factorNameProperty().get(); }
public StringProperty factorNameProperty() {
if (factorName == null) factorName =
new SimpleStringProperty(this, "factorName");
return factorName;
}
private IntegerProperty numberLevels = new SimpleIntegerProperty();
public void setNumberLevels(int value) {
numberLevelsProperty().set(value); }
public IntegerProperty getNumberLevels() { return numberLevels; }
public IntegerProperty numberLevelsProperty() {
if (numberLevels == null) numberLevels =
new SimpleIntegerProperty(this, "numberLevels");
return numberLevels;
}
private StringProperty listOfLevels = new SimpleStringProperty();
public void setListOfLevels(String value) {
listOfLevelsProperty().set(value); }
public String getListOfLevels() { return listOfLevelsProperty().get(); }
public StringProperty listOfLevelsProperty() {
if (listOfLevels == null) listOfLevels =
new SimpleStringProperty(this, "listOfLevels");
return listOfLevels;
}
// Constructors
public Factor(int factorID, String factorName) {
this.factorID.set(factorID);
this.factorName.set(factorName);
this.numberLevels.set(1);
this.listOfLevels.set("-1, 1");
}
public Factor(int factorID, String factorName, int numberLevels,
String listOfLevels) {
this.factorID.set(factorID);
this.factorName.set(factorName);
this.numberLevels.set(numberLevels);
this.listOfLevels.set(listOfLevels);
}
#Override
public String toString() {
return "Factor{" + "factorName=" + factorName + '}';
}
public String[] getLevels() {
return listOfLevels.getValue().split(",");
}
}
Loading the data into the table
final ObservableList factorList =
FXCollections.observableArrayList(
new Factor(1, "Factor1", 2, "-1, 1")
);
factorTableView.setEditable(true);
factorTableView.getColumns().clear();
factorTableView.setItems(factorList);
boolean addAll;
addAll = factorTableView.getColumns().addAll(idCol,
nameCol, noLevelsCol, levelsCol);
The EditingIntegerCell class
public class EditingIntegerCell extends TableCell {
private TextField textField;
private final Pattern intPattern = Pattern.compile("-?\\d+");
public EditingIntegerCell() {
}
#Override
public void startEdit() {
if (!isEmpty()) {
super.startEdit();
createTextField();
setText(null);
setGraphic(textField);
textField.selectAll();
}
}
#Override
public void cancelEdit() {
super.cancelEdit();
setText((String) getItem().toString());
setGraphic(null);
}
#Override
public void updateItem(Number item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
setGraphic(null);
} else {
if (isEditing()) {
if (textField != null) {
textField.setText(getString());
}
setText(null);
setGraphic(textField);
} else {
setText(getString());
setGraphic(null);
}
}
}
private void createTextField() {
textField = new TextField(getString());
textField.setMinWidth(this.getWidth() - this.getGraphicTextGap()* 2);
textField.focusedProperty().addListener(
(ObservableValue<? extends Boolean> arg0, Boolean arg1, Boolean arg2)
-> {
if (!arg2) {
processEdit();
}
});
}
private void processEdit() {
String text = textField.getText();
if (intPattern.matcher(text).matches()) {
commitEdit(Integer.parseInt(text));
} else {
cancelEdit();
}
}
private String getString() {
return getItem() == null ? "" : getItem().toString();
}
}
** The EditingTextCell class **
public class EditingTextCell extends TableCell {
private TextField textField;
public EditingTextCell() {
}
#Override
public void startEdit() {
if (!isEmpty()) {
super.startEdit();
createTextField();
setText(null);
setGraphic(textField);
textField.selectAll();
}
}
#Override
public void cancelEdit() {
super.cancelEdit();
setText((String) getItem());
setGraphic(null);
}
#Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
setGraphic(null);
} else {
if (isEditing()) {
if (textField != null) {
textField.setText(getString());
}
setText(null);
setGraphic(textField);
} else {
setText(getString());
setGraphic(null);
}
}
}
private void createTextField() {
textField = new TextField(getString());
textField.setMinWidth(this.getWidth() - this.getGraphicTextGap()* 2);
textField.focusedProperty().addListener(
(ObservableValue<? extends Boolean> arg0, Boolean arg1, Boolean arg2)
-> {
if (!arg2) {
commitEdit(textField.getText());
}
});
}
private String getString() {
return getItem() == null ? "" : getItem();
}
}

Volley library throws application exception

I am adding my two separate android activities in one application, one of my activity having volley library but it gives me an exception that appcontroller(volley library) its an application not an activity please help me out
Ya, you have mention in your manifest file appcontroller class as Application. This solves the exception.
Main Acitivity:
public class MainActivity extends FragmentActivity implements OnTabChangeListener, OnPageChangeListener {
MyPageAdapter pageAdapter;
private ViewPager mViewPager;
private TabHost mTabHost;
private Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewPager = (ViewPager) findViewById(R.id.viewpager);
// Tab Initialization
initialiseTabHost();
// Fragments and ViewPager Initialization
List<Fragment> fragments = getFragments();
pageAdapter = new MyPageAdapter(getSupportFragmentManager(), fragments);
mViewPager.setAdapter(pageAdapter);
mViewPager.setOnPageChangeListener(MainActivity.this);
}
// Method to add a TabHost
private static void AddTab(MainActivity activity, TabHost tabHost, TabHost.TabSpec tabSpec,String message,int picture,Context x)
{
tabSpec.setContent(new MyTabFactory(activity));
View tabIndicator = LayoutInflater.from(x).inflate(R.layout.tab_indicator, tabHost.getTabWidget(), false);
TextView title = (TextView) tabIndicator.findViewById(R.id.title);
title.setText(message);
ImageView icon = (ImageView) tabIndicator.findViewById(R.id.icon);
icon.setBackgroundDrawable(x.getResources().getDrawable(picture));
icon.setScaleType(ImageView.ScaleType.FIT_CENTER);
tabSpec.setIndicator(tabIndicator);
tabHost.addTab(tabSpec);
}
// Manages the Tab changes, synchronizing it with Pages
public void onTabChanged(String tag) {
int pos = this.mTabHost.getCurrentTab();
this.mViewPager.setCurrentItem(pos);
for(int i=0;i<mTabHost.getTabWidget().getChildCount();i++)
{
mTabHost.getTabWidget().getChildAt(i).setBackgroundColor(Color.BLUE);
//mTabHost.getTabWidget().setDividerDrawable(R.Color.transperant);
}
mTabHost.getTabWidget().getChildAt(mTabHost.getCurrentTab()).setBackgroundColor(Color.CYAN);// selected
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
public void destroyItem(View collection, int position, Object view){
((ViewPager) collection).removeView((ImageView) view);
}
// Manages the Page changes, synchronizing it with Tabs
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
int pos = this.mViewPager.getCurrentItem();
this.mTabHost.setCurrentTab(pos);
}
#Override
public void onPageSelected(int arg0) {
}
private List<Fragment> getFragments(){
List<Fragment> fList = new ArrayList<Fragment>();
// TODO Put here your Fragments
NewSampleFragment f1 = NewSampleFragment.newInstance(getApplicationContext(),R.layout.newfragment_a);
MySampleFragment f2 = MySampleFragment.newInstance("Sample Fragment 2");
MySampleFragment f3 = MySampleFragment.newInstance("Sample Fragment 3");
MySampleFragment f4 = MySampleFragment.newInstance("Sample Fragment 4");
MySampleFragment f5 = MySampleFragment.newInstance("Sample Fragment 5");
fList.add(f1);
fList.add(f2);
fList.add(f3);
fList.add(f4);
fList.add(f5);
return fList;
}
// Tabs Creation
private void initialiseTabHost() {
mTabHost = (TabHost) findViewById(android.R.id.tabhost);
mTabHost.setup();
// TODO Put here your Tabs
MainActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab1").setIndicator("Tab1"),"Grocery",R.drawable.movies,getApplicationContext());
MainActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab2").setIndicator("Tab2"),"Crockery",R.drawable.artist,getApplicationContext());
MainActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab3").setIndicator("Tab3"),"Foods",R.drawable.song,getApplicationContext());
MainActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab3").setIndicator("Tab4"),"Drinks",R.drawable.shopping,getApplicationContext());
MainActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab3").setIndicator("Tab5"),"Toys",R.drawable.play,getApplicationContext());
mTabHost.setOnTabChangedListener(this);
}
}
OfferActivity (This should be open when button pressed)
public class OfferActivity extends Activity
{
private static final String TAG = MainActivity.class.getSimpleName();
private ListView listView;
private FeedListAdapter listAdapter;
private List<FeedItem> feedItems;
private ProgressDialog pDialog;
private String URL_FEED = "http://nusdtech.com/public_html/checking2.php";
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main1);
listView = (ListView) findViewById(R.id.list);
feedItems = new ArrayList<FeedItem>();
listAdapter = new FeedListAdapter(this, feedItems);
listView.setAdapter(listAdapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// These two lines not needed,
// just to get the look of facebook (changing background color & hiding the icon)
getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#3b5998")));
//getActionBar().setIcon(
// new ColorDrawable(getResources().getColor(android.R.color.transparent)));
JsonArrayRequest movieReq = new JsonArrayRequest(URL_FEED,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
FeedItem movie = new FeedItem();
movie.setId(obj.getInt("id"));
movie.setName(obj.getString("name"));
// Image might be null sometimes
String image = obj.isNull("image") ? null : obj
.getString("image");
movie.setImge(image);
movie.setStatus(obj.getString("status"));
movie.setProfilePic(obj.getString("profilePic"));
//movie.setTimeStamp(obj.getString("price"));
movie.setPrice(obj.getString("price"));
movie.setDate(obj.getString("dates"));
feedItems.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
listAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
AppController:
public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
LruBitmapCache mLruBitmapCache;
private static AppController mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public ImageLoader getImageLoader() {
getRequestQueue();
if (mImageLoader == null) {
getLruBitmapCache();
mImageLoader = new ImageLoader(this.mRequestQueue, mLruBitmapCache);
}
return this.mImageLoader;
}
public LruBitmapCache getLruBitmapCache() {
if (mLruBitmapCache == null)
mLruBitmapCache = new LruBitmapCache();
return this.mLruBitmapCache;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
Activity that contain fragment buttons
public class NewSampleFragment extends Fragment {
private static View mView;
private Context con;
public static final NewSampleFragment newInstance(Context con,int layout) {
NewSampleFragment f = new NewSampleFragment();
con=con;
Bundle b = new Bundle();
b.putInt("mylayout",layout);
f.setArguments(b);
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
int layout = getArguments().getInt("mylayout");
mView = inflater.inflate(R.layout.newfragment_a, container, false);
Button button = (Button) mView.findViewById(R.id.bactivity);
Button offer=(Button) mView.findViewById(R.id.aactivity);
button.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Intent myIntent = new Intent(getActivity(), ListViewDemo.class);
//Optional parameters
getActivity().startActivity(myIntent);
Log.e("Error","Kashif");
}
});
offer.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
startApplication("uzair.sabir.app.OfferActivity");
}
});
return mView;
}
public void startApplication(String application_name){
try{
Intent intent = new Intent("android.intent.action.MAIN");
intent.addCategory("android.intent.category.LAUNCHER");
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
List<ResolveInfo> resolveinfo_list = getActivity().getPackageManager().queryIntentActivities(intent, 0);
for(ResolveInfo info:resolveinfo_list){
if(info.activityInfo.packageName.equalsIgnoreCase(application_name)){
launchComponent("uzair.sabir.app", "OfferActivity");
break;
}
}
}
catch (ActivityNotFoundException e) {
Toast.makeText(getActivity(), "There was a problem loading the application: "+application_name,Toast.LENGTH_SHORT).show();
Log.e("Error",e.getMessage());
}
}
private void launchComponent(String packageName, String name){
Intent launch_intent = new Intent("android.intent.action.MAIN");
launch_intent.addCategory("android.intent.category.LAUNCHER");
launch_intent.setComponent(new ComponentName(packageName, name));
launch_intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getActivity().startActivity(launch_intent);
}
}

JavaFX - How to prevent mouse clicking on TableCell from triggering its startEdit method?

I got this class from Oracle tutorial but in my application I don't want to make cell edit function triggered when user focues on table cell by clicking mouse button but invoke it by other isolated control. It would be easy if only class contains some event handler but it doesn't and I'm stucked.
class EditingCell extends TableCell<Person, String> {
private TextField textField;
public EditingCell() {
}
#Override
public void startEdit() {
if (!isEmpty()) {
super.startEdit();
createTextField();
setText(null);
setGraphic(textField);
textField.selectAll();
}
}
#Override
public void cancelEdit() {
super.cancelEdit();
setText((String) getItem());
setGraphic(null);
}
#Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
setGraphic(null);
} else {
if (isEditing()) {
if (textField != null) {
textField.setText(getString());
}
setText(null);
setGraphic(textField);
} else {
setText(getString());
setGraphic(null);
}
}
}
private void createTextField() {
textField = new TextField(getString());
textField.setMinWidth(this.getWidth() - this.getGraphicTextGap()* 2);
textField.focusedProperty().addListener(new ChangeListener<Boolean>(){
#Override
public void changed(ObservableValue<? extends Boolean> arg0,
Boolean arg1, Boolean arg2) {
if (!arg2) {
commitEdit(textField.getText());
}
}
});
}
private String getString() {
return getItem() == null ? "" : getItem().toString();
}
}
}
Ok so there is a TabelCell command called setEditable(boolean) that I think you should just set to false (assuming I get what you're wanting here) and then set it to true and give it focus when your isolated control is invoked. I haven't really messed much with TableCell.

JavaFX TreeItem string not appearing

After hours of trying i finally somewhat managed to figure out how to hook a listener to TreeItems in a TreeView, it probably isn't at all the right way to do so but hey it works so far.
Although one thing isn't, that is the "label" or better said text in the TreeItems isn't showing up anymore.
Can anyone look at my code and tell me, if i'm either doing it completely wrong or why the text isn't showing up anymore?
Thanks in advance.
Code:
TreeView<String> tree = new TreeView<>();
TreeItem<String> treeRoot = new TreeItem<>(Login.name + " - " + Login.accountType);
treeRoot.getChildren().addAll(new TreeItem<>("Branches"),
new TreeItem<>("Planning"), new TreeItem<>("Courses"),
new TreeItem<>("Add new item"));
treeRoot.getChildren().get(1).getChildren().addAll(
new TreeItem<>("2014 - Q1"), new TreeItem<>("2014 - Q2"),
new TreeItem<>("2014 - Q3"), new TreeItem<>("2014 - Q4"));
treeRoot.getChildren().get(3).getChildren().addAll(
new TreeItem<>("Branch"), new TreeItem<>("Course"));
for(String str : loadBranchData()) {
treeRoot.getChildren().get(0).getChildren().add(
new TreeItem<>(str));
}
for(String str : loadCourseData()) {
treeRoot.getChildren().get(2).getChildren().add(
new TreeItem<>(str));
}
for(int c = 0; c <= 2; c++) {
treeRoot.getChildren().get(c).setExpanded(true);
}
treeRoot.setExpanded(true);
tree.setPrefWidth(PREFWIDTH);
tree.setRoot(treeRoot);
tree.setShowRoot(true);
tree.setCellFactory(new Callback<TreeView<String>,TreeCell<String>>(){
#Override
public TreeCell<String> call(TreeView<String> p) {
return new EpicTreeCell();
}
});
...
private final class EpicTreeCell extends TreeCell<String> {
#SuppressWarnings("unchecked")
super.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent evt) {
System.out.println("TEST?");
}
});
}
When the custom cell is defined, the setText() method should be called in its overridden updateItem() method.
private final class EpicTreeCell extends TreeCell<String> {
public EpicTreeCell() {
setOnMouseClicked (
new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent evt) {
System.out.println("TEST?");
}
}
);
}
#Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
} else {
setText(getItem() == null ? "" : getItem().toString());
}
setGraphic(null);
}
}
See the "Custom Java-fx cellfactory messes up the setCellValueFactory" for more information.

Resources