Conversion of String to JComboBox - java

How do I convert string to JComboBox object model ?
Note: Im using NetBeans IDE 8.0.2

to change JComboBox from <String> to <Object>
right click on JComboBox and select properties
select code tab
click on ... button from type parameters
replace <String> to <Object> and click ok.

You don't convert a String to a ComboBoxModel. You add the String to the combo box or the ComboBoxModel.
For example:
JComboBox<String> comboBox = new JComboBox<String>();
comboBox.add( "One" );
comboBox.add( "Two" );
comboBox.add( "Three" );
Read the section from the Swing tutorial on How to Use Combo Boxes for more information and other examples.
You can also search the forum or web for other examples.

I solved the problem.
I needed to be able to grab each line independent of the other so I can use just one Text file but break it out to different j combo boxes. Below was what I did. Is there a shorter way of doing this? I will have 20 JComboBox with each having around 7 select entries. The entries for the drop down boxes are around 50 lines of selections.
public void inputFile() throws IOException{
//File reader method
FileReader file = new FileReader("c:\\jcboEntries.dat");
try (BufferedReader br = new BufferedReader(file)) {
String[] lines = new String [6];
String [] jcbo = new String [6];
try {
int i =0;
lines[0] = br.readLine();
jcbo[0] = lines[0];
jcbo0 = jcbo[0];
jcboNUMONE.addItem(jcbo0);
System.out.println(jcbo0);
lines[1] = br.readLine();
jcbo[1] = lines[1];
jcbo1 = jcbo[1];
jcboNUMONE.addItem(jcbo1);
System.out.println(jcbo1);
lines[2] = br.readLine();
jcbo[2] = lines[2];
jcbo2 = jcbo[2];
jcboNUMONE.addItem(jcbo2);
System.out.println(jcbo2);
lines[3] = br.readLine();
jcbo[3] = lines[3];
jcbo3 = jcbo[3];
jcboNUMONE.addItem(jcbo3);
System.out.println(jcbo3);
lines[4] = br.readLine();
jcbo[4] = lines[4];
jcbo4 = jcbo[4];
jcboNUMONE.addItem(jcbo4);
System.out.println(jcbo4);
lines[5] = br.readLine();
jcbo[5] = lines[5];
jcbo5 = jcbo[5];
jcboNUMONE.addItem(jcbo5);
System.out.println(jcbo5);
} catch (IOException e){}
} catch (IOException e){}
}

Related

Auto Refresh in Swing (Jtable)

I wrote a code which is get text from text area and save to file after that get data from file and show at jtable but I want to do that automatically when I add a new text to file it should be automatically show at the jtable does any one can help me?
try {
BufferedReader br = new BufferedReader(new FileReader(new File ("Member.txt")));
Object [] row = {id, firstname, lastname, age};
DefaultTableModel dtm = (DefaultTableModel) table.getModel();
Object[] tableLines = br.lines().toArray();
for(int i = 0; i < tableLines.length; i++)
{
String line = tableLines[i].toString().trim();
String[] dataRow = line.split(" ");
dtm.addRow(dataRow);
}
} catch (Exception ex) {
System.out.println(ex);
}
this code help me to show data from file at jtable.
Your starting point is: using a watch service to determine when that file changed on disk.
Then you have to read the whole file and figure what changed (for example by keeping a "copy" of all lines of the file in memory).
Then you extract the newly added lines and add them to your table model.

Storing 1D arrays inside 2D array from text file to jTable java

Hi I need to import a text file into a Jtable. I have to store each column into a separate array so I was thinking to create a 2D array for the table, and 1D array for each column inside. (9 columns, 20 rows total)
All i've managed to do so far is import the text file and display it in the Jtable.
The data types i have to use are int, string and double(or float) as I have to create as student table where their I.D numbers (int )names, address ect (string) and grades (double) will be shown and ill have to be able to do calculations with the grades.
private void formWindowOpened(java.awt.event.WindowEvent evt) {
// When the window is opened, the information from the text file will be loaded into the table (tblStudentDetails)
try {
BufferedReader br = new BufferedReader(new FileReader ("C:\\Users\\XXX\\NetBeansProjects\\StudentDetailsJava\\lib\\StudentDetails.txt"));
//Get the first line
//Get the columns name from the first line
// Set columns name to the tblStudentDetails model
String firstLine = br.readLine().trim(); // Reading the file line (row) of the text file
// while(firstLine !=null) {
String[] columnsName = firstLine.split("\t"); // The coloums are split by tab
DefaultTableModel model = (DefaultTableModel)tblStudentDetails.getModel();
model.setColumnIdentifiers(columnsName);
// Get lines from txt file
Object[] tableLines = br.lines().toArray();
// Extract data from lines
// Set data to tblStudentsData model
for (Object tableLine : tableLines) {
String line = tableLine.toString().trim();
String[] dataRow = line.split("\t");
{
model.addRow(dataRow);
}
}
br.close();
} catch (Exception ex) {
Logger.getLogger(StudentTable.class.getName()).log(Level.SEVERE, null, ex);
}
}
Here's what I have so far, and before you all kill me, i've spent the past 3 days trying to get this to work and i've tried nearly every solution I can find on this site to no avail.
I've been able to create a 2D array but I haven't been able to actually make it work when reading the text file, or importing it to the Jtable. Someone help!
first year student so I'm definitely a newbie and my assignment is due soon, I cant move on without solving this!
thanks! - Mrs x
Also
The text file looks like this (separated by tab so the first row is too long, but it imports into the Jtable just fine)
enter image description here
try this code:
Scanner input = new Scanner(new File(FILE_NAME));
int rows = 0;
String[] columnsName = null;
if (input.hasNext()) {
columnsName = input.nextLine().split("\t");
} else {
return;
}
while (input.hasNextLine()) {
input.nextLine();
++rows;
}
String[][] a = new String[rows][columnsName.length];
input.close();
input = new Scanner(new File(FILE_NAME));
if (input.hasNextLine()) {
input.nextLine();
}
for (int i = 0; i < rows; i++) {
a[i] = input.nextLine().split("\t");
}
JTable jt = new JTable(a, columnsName);

Populating a JTable with parsed information

I am trying to populate a JTable with information taken from a website (namely price and item name). I have a class that asks the user to input a URL and scans the page for the price and item name as well as the URL. Currently it takes all the parsed information and stores it in three different text files, one for price, one for item name, and one for the URL. I am trying to populate a JTable containing three columns (item name, price, and URL) with this information but every time I scan a new page the text files are overwritten and the previous information is lost. I don't necessarily need the JTable to be populated via the text file, I just need it to somehow get the information. Here is some of my code.
public BestBuy (JFrame frame){
super (frame, "Best Buy URL", true);
setLayout (new FlowLayout());
label = new JLabel ("Enter Best Buy URL");
add (label);
url = new JTextField ("Enter URL Here", 40);
add (url);
submit = new JButton ("Submit");
add (submit);
event b = new event ();
submit.addActionListener (b);
}
public class event implements ActionListener{
public void actionPerformed (ActionEvent b){
try {
String datab = url.getText(); //perform your operation
datab = datab.trim();
datab = datab.toLowerCase();
Document document = Jsoup.connect(datab).get();
String amountb = document.select(".amount").first().text();
String nameb = document.select(".product-title").first().text();
FileWriter stream = new FileWriter ("C:\\Users\\Daniel\\Desktop\\price.txt");
BufferedWriter out = new BufferedWriter (stream);
out.write(amountb + "\n");
out.newLine();
out.close();
FileWriter stream1 = new FileWriter ("C:\\Users\\Daniel\\Desktop\\itemName.txt");
BufferedWriter out1 = new BufferedWriter (stream1);
out1.write(nameb + "\n");
out1.newLine();
out1.close();
FileWriter stream2 = new FileWriter ("C:\\Users\\Daniel\\Desktop\\url.txt");
BufferedWriter out2 = new BufferedWriter (stream2);
out2.write(datab + "\n");
out2.newLine();
out2.close();
}
catch (Exception ex) {
}
setVisible (false);
}
This class asks the user for a Best Buy URL and parses the given page for item name, and price then writes it to files on my desktop.
public FirstGui (){
setLayout (new FlowLayout ());
String[] columnName = {"Item Name", "Price", "URL"};
Object [] [] data = {
};
table = new JTable (data, columnName);
table.setPreferredScrollableViewportSize(new Dimension (500, 300));
table.setFillsViewportHeight (true);
JScrollPane scrollpane = new JScrollPane (table);
add (scrollpane);
Now I am trying to get that parsed information onto my JTable but I have no idea how to do so. I tried to do
public getdatab() {
return datab;
}
public getnameb() {
return nameb;
}
public getamountb() {
return amountb;
}
but all these strings are within a void so that did not work. As you can probably see I am quite new to java and this might have an obvious solution but I have been stuck on this for a few days and cant figure it out. Thank you.
I'm not sure exactly how your getting your data, but you want to do something like this. Since you're trying to write the data to three different files, I will assume the data is coming in from three different streams. Here's the thing though. For this to work, all the data needs to be in parallel, Meaning that the first item, should correspond to the first price and first url, and so on. If this is the case, you can do something like this.
Have three separate lists.
List<String> names = new ArrayList<String>();
List<String> prices = new ArrayList<String>();
List<String> urls = new ArrayList<String>();
Then for each item you were going to add to a file, add to the list instead.
Use a DefaultTableModel as the model of your JTable
String[] columnName = {"Item Name", "Price", "URL"};
DefaultTableModel model = new DefaultTableModel(columnNames, 0);
table = new JTable(model);
Now you can just add rows, using the data from the lists. Use the method model.addRow(row), where row is an array of Objects
for (int i = 0; i < names.size(); i++) {
String name = names.get(i);
String price = prices.get(i);
String url = urls.get(i);
model.addRow(new Object[] { name, price, url });
}
That's all there is to it. The model will update the table for you dynamically. But remember, like I said, the data in the lists must be in sync with one another for you to get the desired result.
If you're getting data in one row at a time, instead of one column at a time, that makes it even easier. For each set of data, that comes in, just add it as a row like it did in step 5.

Getting JCheckBox selected box value

I want to ask is there a way to get information from JCheckBox without actionListener. In my code I scan a file of strings and each line has data which, if selected, should be added to an array in my program. Problem is that i will never know how many JCheckBoxes I will have, it depends from file.
So, my question is how to put selected strings to an array (or list) with a press of a button (ok) so i could do something else with them (in my case i need to get data from file or from hand input and put it in a red-black tree, so I will need to push selected strings to my putDataInTheTree method).
EDIT: Also, is it possible not to show those JCheckBoxes that already has been added to the program? I.E. if i choose fluids, next time I call input method fluids wont show in my panel?
Thanks in advance!
How it looks:
My code is so far:
public void input() {
try {
mainWindow.setEnabled(false);
fromFile = new JFrame("Input from file");
fromFile.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
fromFile.setLayout(new BorderLayout());
fromFile.setSize(300,200);
panelFromFile = new JPanel();
panelFromFile.setLayout(new java.awt.GridLayout(0,1));
JScrollPane scrollPane2 = new JScrollPane(panelFromFile);
scrollPane2.setMaximumSize(new Dimension(300, 180));
FileReader File = new FileReader(data);
BufferedReader Buffer = new BufferedReader(File);
while ((info = Buffer.readLine()) != null) {
if (info != null) {
JCheckBox check = new JCheckBox(info);
panelFromFile.add(check);
}
}
ok = new JButton("ok");
ok.addActionListener(this);
fromFile.add(scrollPane2, BorderLayout.CENTER);
fromFile.add(ok, BorderLayout.SOUTH);
fromFile.setLocationRelativeTo(null);
fromFile.setResizable(false);
fromFile.setVisible(true);
}
catch(Exception e) {
text.append("Error in INPUT method");
text.append(System.getProperty("line.separator"));
}
}
Add your checkboxes to a collection, and when the button is pressed, iterate through the checkboxes and get the text associated with each checked checkbox:
private List<JCheckBox> checkBoxes = new ArrayList<JCheckBox>();
...
while ((info = Buffer.readLine()) != null) {
if (info != null) {
JCheckBox check = new JCheckBox(info);
panelFromFile.add(check);
this.checkBoxes.add(check);
}
}
...
public void actionPerformed(ActionEvent e) {
List<String> infos = new ArrayList<String>();
for (JCheckBox checkBox : checkBoxes) {
if (checkBox.isSelected() {
infos.add(checkBox.getText());
}
}
// TODO do something with infos
}
If you store the checkboxes (e.g. in a List) you can loop over them and query their selected state when the OK button is pressed.
To obtain the String from the checkbox, you could opt to use the putClientProperty and getClientProperty methods, as explained in the class javadoc of JComponent

how to export the data in file using java

I need to export the values in 4 column.values for 3 columns are populating properly.
I am having trouble with 4th column which is organization column.it is multivalued column.i.e.: it has multiple values.
I have tried to convert from object to String for organization column but didnt help.
Please see the code below:
String appname = "abc";
String path = "//home/exportfile//";
String filename = path+"ApplicationExport-"+appname+".txt";
String ret = "false";
QueryOptions ops = new QueryOptions();
Filter [] filters = new Filter[1];
filters[0] = Filter.eq("application.name", appname);
ops.add(filters);
List props = new ArrayList();
props.add("identity.name");
//Do search
Iterator it = context.search(Link.class, ops, props);
//Build file and export header row
BufferedWriter out = new BufferedWriter(new FileWriter(filename));
out.write("Name,UserName,WorkforceID,organization");
out.newLine();
//Iterate Search Results
if (it!=null)
{
while (it.hasNext()) {
//Get link and create object
Object [] record = it.next();
String identityName = (String) record[0];
Identity user = (Identity) context.getObject(Identity.class, identityName);
//Get Identity attributes for export
String workforceid = (String) user.getAttribute("workforceID");
//Get application attributes for export
String userid="";
List links = user.getLinks();
if (links!=null)
{
Iterator lit = links.iterator();
while (lit.hasNext())
{
Link l = lit.next();
String lname = l.getApplicationName();
if (lname.equalsIgnoreCase(appname))
{
userid = (String) l.getAttribute("User Name");
List orgList = l.getAttribute("Organization");
}
}
}
//Output file
out.write(identityName+","+userid+","+workforceid+","+org);
out.newLine();
out.flush();
}
ret="true";
}
//Close file and return
out.close();
return ret;
The output of this code should be:
for ex:
Name,UserName,WorkforceID,organization
abc,abc,123,xy
qwe,q01,234,xy
any help correcting this code will be greatly appreciated.
EDIT:
This should give you the output you want:
out.write(identityName+","+userid+","+workforceid+","+Arrays.toString(orgList.toArray());
you probably want to declare List orgList outside the while loop since everytime it is being created and also you are using org and i havent seen any org elsewhere in your code

Categories