public void setForm(mhs m)
{
String[] jurusan = {"TI","SI"};
JComboBox<String> cjurusan = new JComboBox<String> (jurusan);
String st;
st = ((String)m.getJurusan()).toUpperCase();
for(int i = 0; i < cjurusan.getItemCount(); i++)
{
String jur = ((String) cjurusan.getItemAt(i)).toUpperCase();
if(jur.equals("SI"))
{
cjurusan.setSelectedIndex(1);
}
else
{
cjurusan.setSelectedIndex(0);
}
}
tnim.setText(m.getNim());
tnama.setText(m.getNama());
cjurusan.setBounds(110,70,90,20);
add(cjurusan);
}
}
I want to set jcombobox's value according the data record in jtable, till now, I just get the data value at the first time, for second time the jcombobox's value is the same with last. please help. many thanks.
This is my sample image program : screenshoot
Related
I am suing multi select spinner to update languages to the server using retrofit. but when i select multi options from spinner it returns a boolean array and the selected value returns as true and the others as false. now i need to get the value against each title using the index and store them into an array and send that array to server to update my record. here is the image that explain it.
This image is showing the boolean array which returns true against each selected value and the other array is my data i have to show the user the title and on the back end i have to send the value against each title .
this is the code i which i have to not able to get the array of values against each selected title. please help
Call<List<EnglishLevel>> call_english = RetrofitClient.getInstance().getApi().getenglishlist("english_levels");
call_english.enqueue(new Callback<List<EnglishLevel>>() {
#Override
public void onResponse(Call<List<EnglishLevel>> call, Response<List<EnglishLevel>> response) {
arrayList_english =response.body();
for (EnglishLevel C:arrayList_english){
if (C.getTitle() != null){
Log.d("English level" , C.getTitle());
final String[] levelName = new String[arrayList_english.size()];
for (int i=0 ; i<arrayList_english.size() ; i++){
levelName[i]= arrayList_english.get(i).getTitle();
}
ArrayAdapter<String> adapter= new ArrayAdapter <String>(SearchActivity.this,
android.R.layout.simple_list_item_multiple_choice,
levelName);
english.setListAdapter(adapter).setListener(new MultiSelectSpinner.MultiSpinnerListener() {
#Override
public void onItemsSelected(boolean[] selected) {
ArrayList<String> toSend = new ArrayList<>();
for(int j = 0; j < arrayList_english.size(); j++){
if(selected[j]) {
toSend.add(arrayList_english.get(j).getValue());
}
}
//
}
})
.setSelectAll(false).setMinSelectedItems(0);
}
}
}
#Override
public void onFailure(Call<List<EnglishLevel>> call, Throwable t) {
Toast.makeText(SearchActivity.this , t.getMessage() , Toast.LENGTH_SHORT).show();
}
});
In the above code that i have issue with some part of it...
english.setListAdapter(adapter).setListener(new MultiSelectSpinner.MultiSpinnerListener() {
#Override
public void onItemsSelected(boolean[] selected) {
ArrayList<String> toSend = new ArrayList<>();
for(int j = 0; j < arrayList_english.size(); j++){
if(selected[j]) {
toSend.add(arrayList_english.get(j).getValue());
}
}
//
}
in onItemSelected i have to get array of each selected title's value.
in this problem you need to define your ArrayList toSend = new ArrayList<>(); as a globally in existing scenario you are creating new array list every time when you select one language from spinner
is there a loop for each I can use as array
as if the value changed that will change the color and if else then color will be back to normal
btw i am really new in java
private void bt1MouseClicked(java.awt.event.MouseEvent evt)
{
if (txt1.getText().equals("6652") ) {
txt1.setBackground(Color.yellow);
}
if (txt2.getText().equals("6652") ) {
txt2.setBackground(Color.yellow);
}
if (txt3.getText().equals("6652") ) {
txt3.setBackground(Color.yellow);
}
}
You could a structure of data where you associate a JTextField to a String.
You could use a Map<JTextField, String> object :
Map<JTextField, String> map = new HashMap<>();
// add elements in
map.put(textField1, "6652");
map.put(textField2, "1142");
map.put(textField3, "2231");
...
private void bt1MouseClicked(java.awt.event.MouseEvent evt)
// iterate on it
for (Entry<JTextField, String> entry : map.entrySet()) {
JTextField field = entry.getKey();
String value = entry.getValue();
if (field.getText().equals(value)) {
field.setBackground(Color.yellow);
}
}
}
You should generate the textboxes from an iterable of model objects. That way, you have full control over all textboxes generated. For this scenario, davidxx's answer is much better, but since you are a beginner ...
You can have two arrays
TextBox[] tbs = new TextBox[35];
String[] vals = new String[];
public void initStrings()
{
// fill vals here, manually or automatically
}
public void setProperties(String[] vals1)
{
for(int i = 0; i < tbs.length; i++)
{
tbs[i] = new TextBox();
vals[i] = vals1[i];
// Do more with your textbox here
}
}
public void refreshTextBoxes()
{
for(int i = 0; i < tbs.length; i++)
{
if (tbs[i].getText().equals(vals[i])
{
tbs[i].setBackground(Color.yellow);
}
}
}
private void bt1MouseClicked(java.awt.event.MouseEvent evt)
{
refreshTextBoxes();
// Do more here, if you like.
}
Save all the Text Boxes in an List of Text Boxes and then you can loop through all of them to update them. Like this.
List<TextBox> text_boxes = new ArrayList<>();
Then add all the Text boxes you want to check like this,
text_boxes.add(text_box1);
text_boxes.add(text_box2);
...
text_boxes.add(text_box34);
Then have a method to change the value of a text box that matches the condition like this
private void changeColor(TextBox tex1)
{
if (txt1.getText().equals("6652") ) {
txt1.setBackground(Color.yellow);
}
if (txt2.getText().equals("1142") ) {
txt2.setBackground(Color.yellow);
}
if (txt3.getText().equals("2231") ) {
txt3.setBackground(Color.yellow);
}
}
Then in the clicked handler of the button you can loop through all the text boxes to update the color
private void bt1MouseClicked(java.awt.event.MouseEvent evt)
{
//loop through the list
for (TextBox text_box : text_boxes) {
changeColor(text_box);
}
}
string [] txtfield = {"1122","2231","3344"} and use it in a loop
Ok this might seem easy but its been bugging my mind for days and I honestly don't know why it the index wont increase and get the other data. I dont know where to but the return. I placed it in 2 lines and the first one only gives the first row of data from the database and the second one only gives the last one from the database. (See commented out lines below). How to get each row that fits the if-statements?
Here's my code:
public Object[] populateTable(ArrayList<Outlet> outletList, String selection, int size, int monthCtr, String selDay){
for(int i = 0; i<outletList.size(); i++){
if(outletList.get(i).getCity().equalsIgnoreCase(selection)){
if(outletList.get(i).getStatus().equals("ACTIVE")){
bar = outletList.get(i).getBarangay();
code = Integer.toString(outletList.get(i).getCode());
name = outletList.get(i).getName();
data = new Object[]{bar, name, code};
//return data ->gives the first one in the database
}
}
}
}
//return data -> gives the last one in the database
}
You need to save all your results in another array and return that instead.
public Object[] populateTable(ArrayList<Outlet> outletList, String selection, int size, int monthCtr, String selDay)
{
List<object> result = new List<object>();
for(int i = 0; i<outletList.size(); i++)
{
if(outletList.get(i).getCity().equalsIgnoreCase(selection))
{
if(outletList.get(i).getStatus().equals("ACTIVE"))
{
bar = outletList.get(i).getBarangay();
code = Integer.toString(outletList.get(i).getCode());
name = outletList.get(i).getName();
data = new Object[]{bar, name, code};
result.Add(data);
}
}
}
return result.ToArray();
}
try this:
public List<Outlet> populateTable(ArrayList<Outlet> outletList, String selection, int size, int monthCtr, String selDay){
List<Outlet> data = new ArrayList<Outlet>();
for(int i = 0; i < outletList.size(); i++){
if(outletList.get(i).getCity().equalsIgnoreCase(selection) &&
outletList.get(i).getStatus().equals("ACTIVE")){
data.add(outletList.get(i));
}
}
return data;
}
Your problem here is as follow:
Your first return statement, will exit the for loop, and return
the first object, as your results have shown.
Your second return statement, will, as you have explained, only
return the last record that was iterated over in the for loop.
Your third problem is on this line data = new Object[]{bar, name,
code};. After every loop, you instantiate the data object to a new
array of objects, instead of adding the values to the array, so essentially, you are always creating an array of objects with 1 item in it, the last one that was iterated.
If you want to return all objects in the array, you should try the following:
public Object[] populateTable(ArrayList<Outlet> outletList, String selection, int size, int monthCtr, String selDay)
{
Object[] result = new Object[outletList.size()];
for (int i = 0; i < outletList.size(); i++)
{
if (outletList.get(i).getCity().equalsIgnoreCase(selection))
{
if (outletList.get(i).getStatus().equals("ACTIVE"))
{
bar = outletList.get(i).getBarangay();
code = Integer.toString(outletList.get(i).getCode());
name = outletList.get(i).getName();
var data = new { bar, name, code };
result[i] = data;
}
}
}
return result;
}
I'm currently working on a simple GUI system in Java using Swing and I am trying to edit a Passenger. The passenger is an object that is stored in an arrayList. There is inheritance involved so there is also multiple classes involved. The code I currently have for the edit method is for from perfect eg If/Elses may not actually work but all I require is advice on how to get the actual method going/working.
Firstly, the Passenger inherits its details from 3 classes, Person, Date and Name. The details of the passenger are the unique ID which auto increments, the Title, Firstname, Surname, DOB (Day, month, year), number of bags and priority boarding. Here is the code where the passenger inherits the details.
public Passenger(String t, String fN, String sn, int d, int m, int y, int noB, boolean pB)
{
// Call super class constructor - Passing parameters required by Person
super(t, fN, sn, d, m, y);
// And then initialise Passengers own instance variables
noBags = noB;
priorityBoarding = pB;
}
I then have a PassengerFileHandler class that has all the methods that I will need for the GUI aspect of things eg Add/Delete passenger etc etc. Here is my edit method that I have in my PassengerFileHandler class. This is most likely where the problem starts, I believe this is the correct way to make a method for the purpose of editing an object.
public Passenger editForGUI(int id, Passenger passenger)
{
for (Passenger passengerRead : passengers)
{
if (id == passengerRead.getNumber())
{
passengers.set(id, passenger);
}
}
return null;
}
I then go into my actual frame class that I have where I make the GUI and call the methods. To call the methods I made an instance of the passengerFileHandler class by typing the following
final PassengerFileHandler pfh = new PassengerFileHandler();
Here is where I make the Edit button and do the ActionListener for the JButton.
btnEditAPassenger.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
editPanel = new JPanel();
editPanel.setLayout(new GridLayout(9, 2));
editPanel.setPreferredSize(new Dimension(280, 280));
//Add radiobutton for priority
JRadioButton yes1 = new JRadioButton();
yes1.setText("Yes");
JRadioButton no1 = new JRadioButton();
no1.setText("No");
ButtonGroup group1 = new ButtonGroup();
group1.add(yes1);
group1.add(no1);
//Make an panel for the RadioButtons to be horizontal
radioButtonPanel1 = new JPanel();
radioButtonPanel1.setLayout(new GridLayout(1, 2));
radioButtonPanel1.setPreferredSize(new Dimension(40, 40));
radioButtonPanel1.add(yes1);
radioButtonPanel1.add(no1);
//title is a comboBox that is auto filled
editPanel.add(new JLabel("Title : "));
editPanel.add(editTitleComboBox = new JComboBox<String>());
editTitleComboBox.addItem("Mr");
editTitleComboBox.addItem("Ms");
editTitleComboBox.addItem("Mrs");
editTitleComboBox.addItem("Miss");
//Add the firstName textfield
editPanel.add(new JLabel("First name : "));
editPanel.add(editFirstNameText = new JTextField(20));
//Add the surname textfield
editPanel.add(new JLabel("Surname : "));
editPanel.add(editSurNameText = new JTextField(20));
//Day is a comboBox that is auto filled
editPanel.add(new JLabel("Day : "));
editPanel.add(editDayComboBox = new JComboBox<Integer>());
int days = 0;
for(int i = 0; i < 31; i++)
{
days++;
editDayComboBox.addItem(days);
}
//Month is a comboBox that is auto filled
editPanel.add(new JLabel("Month : "));
editPanel.add(editMonthComboBox = new JComboBox<Integer>());
int months = 0;
for(int i = 0; i < 12; i++)
{
months++;
editMonthComboBox.addItem(months);
}
//Year is a comboBox that is auto filled
editPanel.add(new JLabel("Year : "));
editPanel.add(editYearComboBox = new JComboBox<Integer>());
int yearNum = 2014 + 1 ;
for(int i = 1900; i < yearNum; i++)
{
editYearComboBox.addItem(i);
}
//NumberOfBags is a comboBox that is auto filled
editPanel.add(new JLabel("Number of Bags : "));
editPanel.add(editBagsComboBox = new JComboBox<Integer>());
int bags = 0;
for(int i = 0; i < 10; i++)
{
bags++;
editBagsComboBox.addItem(bags);
}
//Priority booking is a button group
editPanel.add(new JLabel("Priority boarding : "));
editPanel.add(radioButtonPanel1);
String input1 = JOptionPane.showInputDialog(null,"Enter the ID of the passenger you wish to edit: ");
if (input1 == null)
{
JOptionPane.showMessageDialog(null,"You have decided not to edit a Passenger");
}
if (input1.length() <1)
{
JOptionPane.showMessageDialog(null,"Invalid entry");
}
if (input1 != null)
{
// Put a Border around the Panel
editPanel.setBorder(new TitledBorder("Edit Passenger Details"));
//Make custom buttons
Object[] customButtonSet1 = {"Edit Passenger", "Cancel"};
int customButtonClick1 = JOptionPane.showOptionDialog(null,editPanel,"Edit", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, customButtonSet1, customButtonSet1[1]);
if(customButtonClick1 == JOptionPane.YES_OPTION)
{
try
{
if(pfh.passengers.contains(Integer.valueOf(input1)))
{
Passenger myObj = pfh.passengers.get(Integer.valueOf(input1));
//Passenger passenger1 = pfh.list().get(String.valueOf(pfh.passengers.equals(input1))))
//JOptionPane.showMessageDialog(null, "Succesfully edited the Passenger");
String title1 = String.valueOf(editTitleComboBox.getSelectedItem());
String firstName1 = String.valueOf(editFirstNameText.getText());
String surName1 = String.valueOf(editSurNameText.getText());
int day1 = Integer.valueOf(editDayComboBox.getSelectedItem().toString());
int month1 = Integer.valueOf(editMonthComboBox.getSelectedItem().toString());
int year1 = Integer.valueOf(editYearComboBox.getSelectedItem().toString());
int numBags1 = Integer.valueOf(editBagsComboBox.getSelectedItem().toString());
boolean priority1;
//Method to get the boolean
if(yes1.isSelected())
{
priority1 = true;
}
else
{
priority1 = false;
}
myObj.setName(new Name(title1, firstName1, surName1));
myObj.setDateOfBirth(new Date(day1, month1, year1));
myObj.setNoBags(numBags1);
myObj.setPriorityBoarding(priority1);
//Makes the toString clean
String formatedString = (pfh.passengers.toString().replace("[", "").replace("]", "").trim());
//refreshes the textArea and auto fills it with the current ArrayList
textArea.setText("");
textArea.append(formatedString);
}
else
{
JOptionPane.showMessageDialog(null, "Passenger does not exist");
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
else
{
JOptionPane.showMessageDialog(null, "Passenger does not exist");
}
if(customButtonClick1 == JOptionPane.CANCEL_OPTION || customButtonClick1 == JOptionPane.NO_OPTION)
{
JOptionPane.showMessageDialog(null, "You have decided not to Edit a Passenger");
}
}
}
catch (Exception ex)
{
// do nothing
}
}
});
I am pretty sure that one of the bigger issues is that when I do the code where I ask the user for the ID of the passenger they wish to edit it doesn't actually check if the Passenger exists correctly. I also understand that I don't actually even call the edit method but I couldn't get it working using the method either.
Here are images to help you understand what the GUI looks like and what the code may/may not be doing. Image 1 is the GUI and how it looks with the buttons. Image 2 is when you click the "Edit" button, the ID request pops up. Image 3 is where the user attempts to set the new passenger data.
Simple enough it's with strings but I think the issue is you don't know how to really use an arraylist.
public String[] currentArray = { "temp", "temp1", "temp3"};
public void addToList(String tobeadded) {
ArrayList<String> temp = new ArrayList<String>();
for(String s: currentArray) {
temp.add(s);
}
temp.add(tobeadded);
currentArray = temp.toArray(new String[temp.size()]);
}
public void removeFromList(String toRemove) {
ArrayList<String> temp = new ArrayList<String>();
for(String s: currentArray) {
if(!toRemove.equals(s))
temp.add(s);
}
currentArray = temp.toArray(new String[temp.size()]);
}
public void edit(String orginal, String new1) {
ArrayList<String> temp = new ArrayList<String>();
for(String s: currentArray) {
if(!orginal.equals(s))
temp.add(s);
}
temp.add(new1);
currentArray = temp.toArray(new String[temp.size()]);
}
i am not sure about your editForGUI method a it is not very clear. I am assuming that when you update the passenger details and click on edit passenger, it should update list.. If that is the case then try this..
If you are using updatedPassenger and Passsenger list as parameters in your method then the following will work
`
void editForGUI(Passenger updatedObject, List passengers){
for(int i=0; i<passengers.size; i++){
Passenger p = passengers.get(i);
if( p.getId() == updatedPassenger.getId()){
passengers.set(i, updatedObject);
return;
}
}
}
`
Why don't you use HashMap in place of list? In-place update would be more efficient. id will be key and Passenger object will be the value in HashMap..
I believe your ArrayList problem is in this line:
passengers.set(id, passenger);
At this point, you have found the passenger that matches the id and you want to replace it. If you take a look at the ArrayList documentation, the method signature for set is
set(int index, E element)
The first parameter you pass is the index you want to set, not the id. However, since you used the enhanced for loop to iterate through the ArrayList, you don't know the index. You can call the indexOf() method to get the index using the passenger that you found, but that would be inefficient since you just iterated through the array and the method call would basically repeat everything you just did to get the index. Instead you can keep a counter that increments after the if check, and once you have found it, the counter is set to the index of your item. Inside your if block, you can immediately set your passenger using that index and return right after.
i want to add a cloumn to a jtable when a radio button is being clicked. but when i click it twice two columns are being added to the table. here's my code
dtm = (DefaultTableModel) viewTable.getModel();
dtm.setRowCount(0);
TableColumnModel model=viewTable.getColumnModel();
boolean found=false;
for (int i = 0; i < viewTable.getColumnCount(); i++) {
if (model.getColumn(i).getIdentifier().equals("customer Id")) {
found=true;
break;
}
if (found==false) {
dtm.addColumn("customer Id");
}
don't know how to fix it..
This code would help you. Call the below method on actionPerformed of the check box and if it is true. Validating it based on the column header.
private static void addColumn( final JTable table, final String newColumnHeader )
{
final JTableHeader header = table.getTableHeader();
final int columnCount = header.getColumnModel().getColumnCount();
boolean addColumn = true;
for( int index = 0; index < columnCount; index ++ )
{
final Object headerValue = header.getColumnModel().getColumn(index).getHeaderValue();
if( newColumnHeader.equals( headerValue ) )
{
JOptionPane.showMessageDialog(null, "Column already exists" );
addColumn = false;
break;
}
}
if( addColumn )
{
final TableColumn newCol = new TableColumn();
newCol.setHeaderValue(newColumnHeader);
table.getColumnModel().addColumn(newCol);
}
}
It is good to disable the checkbox if it is already clicked ;) if you do not want a huge code.
This is a clumsy solution but it will work.
You can create a new boolean variable in your class and this variable represents if a column was set or not.
Like:
class MyClass{
boolean isColumnAdded
public MyClass(){
isColumnAdded = false;
}
private void radioButtonActionPerformed(java.awt.event.ActionEvent evt){
if(!isColumnAdded){
//add column
isColumnAdded = true;
}
}
}
To start with, JRadioButton has a selected property. You should be checking this state to determine if the column needs to be removed or added...
Assume that each column name is unique, you could use something like...
TableColumnModel model = viewTable.getColumnModel();
int index = -1;
try {
index = model.getColumnIndex("customer Id");
} catch (IllegalArgumentException e) {
// I know, sucks...
}
if (index < 0) {
// Add new column, if JRadioButton.isSelected
} else {
// Remove old column...
// JRadioButton.isSelected is false...
}
To find and add/remove the column.
Have a look at How to Use Buttons, Check Boxes, and Radio Buttons for some more details