I create a ComboBox in Scene Builder and I want to populate him with data from a text file (eg. Text.txt):
public class ToDoListController implements Initializable {
#FXML
private ComboBox<?> eventsSelector;
How to do this?
Thank you very much!
Two solutions:
1.
#FXML
private ComboBox eventsSelector;
#Override
public void initialize(URL location, ResourceBundle resources) {
List<String> myList;
try {
myList = Files.lines(Paths.get("path of my text file")).collect(Collectors.toList());
eventsSelector.setItems(FXCollections.observableArrayList(myList));
} catch (IOException e) {
System.out.println("Don t find file");
}
}
2.
//Read items from txt File
try {
BufferedReader br = new BufferedReader(new
FileReader("path of my text file"));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
//Add Item
eventsSelector.getItems().add(line);
sb.append(line);
line = br.readLine();
}
br.close();
} catch (IOException e) {
System.out.println("Don t find file");
}
Since you want to add content from a .txt file the items in the ComboBox are Strings so you can change to this :
#FXML
private ComboBox<String> eventsSelector;
Then you need a list of the elements that you want to add to the ComboBox<String>, then you can add them simply by:
List<String> myList = Files.lines(path).collect(Collectors.toList());
comboBox.setItems(FXCollections.observableArrayList(myList));
I wrote some code for you, this should work for you:
public class YourController {
//Combobox
#FXML
ComboBox<String> combobx;
//Initialize FXML
#FXML
public void initialize() throws IOException {
//Read items from txt File
BufferedReader br = new BufferedReader(new FileReader("/items.txt"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
//Add Item
combobx.getItems().add(line);
sb.append(line);
line = br.readLine();
}
} finally {
br.close();
}
//Default Selection first item
combobx.getSelectionModel().select(0);
}
}
The txt file must be in this case in the root directory of your project.
Related
I wanna make a TableView where each column contains a checkbox with a specified text, with an Add method. Here is the code of my controller class :
public class Controller implements Initializable {
#FXML
private CheckBox checkFc, checkNc,
checkMspd, checkDupl,
checkGps, checkPw;
#FXML
private TableView<users> tableUsers;
#FXML
private TableColumn<users, String> colFc, colNc,
colDupl, colMspd,
colGps, colPw;
ObservableList<users> listM;
int index = -1;
Connection conn = null;
ResultSet rs = null;
PreparedStatement pst = null;
public void AddUsers() {
conn = mysqlconnect.ConnectDb();
String sql = "insert into users (fc, nc, dupl, mspd, gps, pw)Values(?,?,?,?,?,?)";
try {
pst = conn.prepareStatement(sql);
pst.setString(4, checkFc.getText());
pst.setString(5, checkNc.getText());
pst.setString(6, checkDupl.getText());
pst.setString(7, checkMspd.getText());
pst.setString(8, checkGps.getText());
pst.setString(9, checkPw.getText());
pst.execute();
JOptionPane.showMessageDialog(null, "addition was a success");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
#Override
public void initialize(URL url, ResourceBundle rb) {
colFc.setCellValueFactory(new PropertyValueFactory<users,String>("fc"));
colNc.setCellValueFactory(new PropertyValueFactory<users,String>("nc"));
colDupl.setCellValueFactory(new PropertyValueFactory<users,String>("dupl"));
colMspd.setCellValueFactory(new PropertyValueFactory<users,String>("mspd"));
colGps.setCellValueFactory(new PropertyValueFactory<users,String>("gps"));
colPw.setCellValueFactory(new PropertyValueFactory<users,String>("pw"));
listM = mysqlconnect.getDatausers();
tableUsers.setItems(listM);
}
}
The app works fine but my checkboxes text is visible all the time instead of when being checked. I unsuccessfully tried to find some YouTube videos and look for some answers online, can anybody help me?
I have the main form Form1 which opens when I run the app. I pass a list from this form which contains Supplier objects to a secondary Form2, to help me build Product objects using an attribute of objects stored in the Suppliers list in Form1.
In Form2 I have the list of Product objects which I want to pass back to Form1 after i complete it and show it in a ListView. But something is not working..i don't figure out what. Thank you in advance.
Form1:
public partial class Form1 : Form
{
public ArrayList suplist = new ArrayList(); //suppliers list
public List<Product> productlist = new List<Product>(); //products list which will be populated with objects sent from Form2
public Form1()
{
InitializeComponent();
//Read Suppliers from txt
StreamReader sr = new StreamReader("Suppliers.txt");
string linie = null;
while((linie=sr.ReadLine())!=null) {
try
{
int id = Convert.ToInt32(linie.Trim().Split(',')[0]);
string nume = linie.Trim().Split(',')[1];
Supplier sp = new Supplier(id, nume);
suplist.Add(sp);
}
catch(Exception ex) { MessageBox.Show(ex.Message); }
}
listView1.Columns.Add("ID");
listView1.Columns.Add("Nume");
listView1.Columns.Add("Units");
listView1.Columns.Add("Price");
listView1.Columns.Add("SUpplier Id");
}
private void button1_Click(object sender, EventArgs e)
{
Form2 from = new Form2(suplist);
from.ShowDialog();
}
public List<Product> ProductList
{
get { return productlist; }
set { productlist = value; }
}
private void button2_Click(object sender, EventArgs e)
{ //this function is supposed to populate listview with the productlist objects when i click the button;
//not sure if it is wrong writeed, or passing the list of products created in Form2 failed
foreach (Product p in productlist)
{
//listView1.Items.Add(p.Id);
ListViewItem itm = new ListViewItem(p.Id.ToString());
itm.SubItems.Add(p.Nume);
itm.SubItems.Add(p.Units.ToString());
itm.SubItems.Add(p.Price.ToString());
itm.SubItems.Add(p.SupplierId.ToString());
}
}
}
Form2:
public partial class Form2 : Form
{
public List<Product> prodList = new List<Product>(); //list which stores the Products == > the list i want to send back to Form 1
public ArrayList supplierList = new ArrayList(); //list of suppliers received from From 1, used to build Products objects
public Form2(ArrayList suplist)
{
InitializeComponent();
supplierList = suplist;
foreach(Supplier s in supplierList)
{
comboBox1_supID.Items.Add(s.Id);
}
Product p1 = new Product(1, "Cola", 4, 45, 1);
Product p2 = new Product(2, "Fanta", 32, 22, 2);
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1__id.Text == "") errorProvider1.SetError(textBox1__id, "Introduceti id");
else if (textBox2_nume.Text == "") errorProvider1.SetError(textBox2_nume, "Introduceti numele");
else if (textBox3_units.Text == "") errorProvider1.SetError(textBox3_units, "Introduceti units");
else if (textBox4_price.Text == "") errorProvider1.SetError(textBox4_price, "enter price");
else if (comboBox1_supID.Text == "") errorProvider1.SetError(comboBox1_supID, "Select sup id");
else
try
{
int id = Convert.ToInt32(textBox1__id.Text);
string nume = textBox2_nume.Text;
int units = Convert.ToInt32(textBox3_units.Text);
double price = Convert.ToDouble(textBox4_price.Text);
int supid = Convert.ToInt32(comboBox1_supID.Text);
Product pd = new Product(id, nume, units, price, supid);
prodList.Add(pd);
MessageBox.Show("Produs adaugat cu succes");
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
textBox1__id.Clear();
textBox2_nume.Clear();
textBox4_price.Clear();
textBox3_units.Clear();
errorProvider1.Clear();
}
}
private void textBox4_price_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsDigit(e.KeyChar))
{
errorProvider1.SetError(textBox4_price, "Introduceti numai cifre");
}
else errorProvider1.Clear();
}
private void button2_Click(object sender, EventArgs e)
{
Form1 frm = new Form1();
frm.productlist = prodList;
frm.Show();
}
}
I want to send to Form1 prodList from Form2, (store it in productlist i guess in Form1) and show them in listview1 in Form1.
On short, in Form1 I create Suppliers, store them in suplist and pass this list to Form2(in supplierlist). In Form2 I create Products, store them in prodList and pass it to Form1(in productList). Why isn't working? and why listview doesn't show anything??
I haven't worked yet with the ListView-Object itself yet but I think you missed to add the created ListViewItem to your ListView
foreach (Product p in productList)
{
ListViewItem itm = new ListViewItem(p.Id.ToString());
itm.SubItems.Add(p.Nume);
itm.SubItems.Add(p.Units.ToString());
itm.SubItems.Add(p.Price.ToString());
itm.SubItems.Add(p.SupplierId.ToString());
listView1.Items.Add(itm);
}
so I want to store the file I read into an array but I am not sure how to. I am trying to use an arraylist but when I compile it in the console I don't it is not the same as the text file
this is my code
public static void main(String[] args) {
BufferedReader br = null;
FileReader fr = null;
String line = null;
ArrayList<String> list = new ArrayList<String>();
try {
fr = new FileReader("sample.txt");
br = new BufferedReader(fr);
while ((line = br.readLine()) != null) {
list.add(line);
line = br.readLine();
for(String s : list){
System.out.println(s);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
it looks to me like you're double advancing your position in the file by having line=br.readLine() both in your while condition and after adding to the ArrayList. Also, is there a reason that you're outputting the contents before you've processed the entire file instead of outside the while loop?
i followed the instructions from this question to set a ComboBoxCell in the TableView of my application. (How to put ComboBoxTableCell in a TableView?)
The declaration of the Cell works fine, but the comboBox doesn't appear in the table. I think it's like this, because only col1 and col2 are in my model. col3 is not written in my table-entry after the database connection.
I don't know how to takte the ComboBox in the TableView and need your help.
Here is my code:
controller:
package controller;
imports
public class main_controller implements Initializable {
private ObservableList<model> tableData = FXCollections.observableArrayList();
private ObservableList<String> cbValues = FXCollections.observableArrayList("1", "2", "3");
#FXML
private TableView<model> ComboTable;
#FXML
private TableColumn<model, String> col1;
#FXML
private TableColumn<model, String> col2;
#FXML
private TableColumn<model, String> col3;
public main_controller() {
}
#Override
public void initialize(URL location, ResourceBundle resources) {
tableData.clear();
col1.setCellValueFactory(new PropertyValueFactory<model, String>("rCol1"));
col2.setCellValueFactory(new PropertyValueFactory<model, String>("rCol2"));
col3.setCellFactory(ComboBoxTableCell.forTableColumn(new DefaultStringConverter(), cbValues));
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
System.out.println("*** Loaded Oracle-Driver ***");
} catch (ClassNotFoundException e1) {
System.out.println("Driver-Loading failed.");
e1.printStackTrace();
}
try {
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:lukas/1234#10.140.79.56:1521:OTTO");
Statement statement = conn.createStatement();
ResultSet resultset = statement.executeQuery("SELECT NUMMER, DATEN1, DATEN2 FROM LUKAS order by NUMMER");
String Daten1 = "empty";
String Daten2 = "empty";
// Zum einfügen kann man später auf diese Variable zurückgreifen.
int columnIndex;
System.out.println("*** Connected with Database ***");
while (resultset.next()) {
columnIndex = resultset.getInt("NUMMER");
System.out.println("Tabellenindex der Zeile:\t" + columnIndex);
Daten1 = resultset.getString("DATEN1");
Daten2 = resultset.getString("DATEN2");
System.out.println("Daten1:\t " + Daten1 + "\t\t\tDaten2: " + Daten2);
**model entry = new model(Daten1, Daten2);
tableData.add(entry);**
}
System.out.println("*** Database data saved to Observable List named 'data' ***");
ComboTable.setItems(tableData);
System.out.println("*** Table Items setted ***");
statement.close();
} catch (SQLException e) {
System.out.println("Login fehlgeschlagen.");
e.printStackTrace();
}
}
}
model:
package model;
import javafx.beans.property.SimpleStringProperty;
public class model {
private final SimpleStringProperty rCol1;
private final SimpleStringProperty rCol2;
public model(String sCol1, String sCol2) {
this.rCol1 = new SimpleStringProperty(sCol1);
this.rCol2 = new SimpleStringProperty(sCol2);
}
public String getRCol1() {
return rCol1.get();
}
public void setRCol1(String set) {
rCol1.set(set);
}
public String getRCol2() {
return rCol2.get();
}
public void setRCol2(String set) {
rCol2.set(set);
}
}
The application looks like this right now:
Picture
Hope you can help me!
The declaration of the Cell works fine, but the comboBox doesn't
appear in the table.
The combobox of ComboBoxTableCell will be appeared when this cell is in edit mode. To do that you need to set the tableview to editable and then double click the over mentioned cell.
The quote from the ComboBoxTableCell javadoc:
By default, the ComboBoxTableCell is rendered as a Label when not
being edited, and as a ComboBox when in editing mode. The ComboBox
will, by default, stretch to fill the entire table cell.
I would like to have the name of the chosen file from JFileChooser from the JMenuItem and show it in a JLabel when a JCheckBoxMenuItem is checked. I am able to choose the file but can't have its name. The important bits of the code is shown below,
private JFileChooser fc;
private JLabel currentDocPanel;
public JCheckBoxMenuItem viewOpt;
public String getFileName() {
String str = fc.getSelectedFile().getName();
return str;
}
private class ActionEventHandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == viewOpt) {
if (currentDocPanel.isVisible()) {
currentDocPanel = new JLabel(getFileName());
currentDocPanel.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));
add(currentDocPanel, BorderLayout.SOUTH);
}
}
}
Thank you for your reply..I tried the code you provided but did not see the file name on the label. I changed my code a bit and I am able to see the text within the label, but the problem is that I can only see it when I hold the window and expand it with mouse. I call this function in the actionPerformed when JCheckBoxMenuItem is clicked. This is what I did;
public void getFileName() throws Exception {
System.out.println("getFileName");
try {
File getfile = fc.getSelectedFile();
boolean check = getfile.exists();
if (check) {
System.out.println("File Name: " + getfile.getName()); //to check
String nameToLabel = "File Name: " + getfile.getName();
currentDocPanel = new JLabel(nameToLabel);
//currentDocPanel.setText(String.valueOf(fc.getSelectedFile()));
currentDocPanel.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));
add(currentDocPanel, BorderLayout.SOUTH);
}
} catch (Exception e) {
}
}
Fairly simple:
currentDocPanel.setText(String.valueOf(Your_JFileChooser.getSelectedFile()));
Should work. Here, I just get the selectedFile of the JFC and transform the output as String.