I have generated a GUI from netbeans in which I have placed a combobox too.
By default, the items in combobox are item1, item2, item3, item4.
But I want my own items. Netbeans doesn't allow editing generated code so how can i edit the comnbobox according to me.
Note: I know one method by editing the "model" property of that jComboBox but I don't want to do it like that because I want various items (which are in an array) in that jComboBox so I want to pass that array in that jComboBox like as follows:
jComboBox2 = new javax.swing.JComboBox();
String [] date = new String[31];
for(int i = 0; i < 31; i++) {
date[i] = i + 1;
}
jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(date));
There are 2 approaches I am aware of:
Simple approach - After the call to initComponents() in the constructor add you code to build your model and call jComboBox2.setModel(myModel) to set it. So the constructor would look something like:
public SomeClass() {
initComponents();
String [] date = new String[31];
for(int i = 0; i < 31; i++) {
date[i] = i + 1;
}
jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(date));
}
Complex approach - add a readable property that holds the desired model. For example:
private ComboBoxModel getComboBoxModel()
{
String[] items = {"Item A", "Item B", "Item C"};
return new DefaultComboBoxModel(items);
}
Then, in the jComboBox2 property sheet, click the button to edit the model.
In the editor panel change the dropdown from Combo Box Model Editor to Value from existing component.
Select Property. Choose the comboBoxModel property. Click OK
I tried the second way once. Never really used it again. Too much work, no real much gain. Plus it displays an empty combo box in the designer which just makes layout harder.
I use the first approach, plus use NetBean's model editor to supply some representative values for the model. That gives me the sensible size behavior in the designer at the cost of one unnecessary line in initComments().
Using Netbeans NEON and other netbeans version
1. Go to the properties of the combobox
2. Then go to model
you can inject your code by using "custom code" feature in the GUI editor for the "model" of combobox
public NewJFrame() {
initComponents();
reformatComboBox();
}
private void reformatComboBox() {
JComboBoxName.removeAllItems();
JComboBoxName.addItem("item1");
JComboBoxName.addItem("item2");
}
Completing blurec answer (I cannot comment yet), in the GUI editor select the comboxbox, go properties, then model, then hit the three dots. Then select Custome Code and add your code, for instance:
new DefaultComboBoxModel<>(functionThatReturnsAnStringArray())
For the posterity:
Right click the ComboBox and select Customize Code. Here at the comboBox.setModel, in the left select custom property.
After new String, add your values in the following form:
Value 1: Integer.toString(myInt1)
Value 2: Integer.toString(myInt2)
If your variables are int of course. If not just put the String variable and you are done.
Hope it helps.
Related
well i am making this system that has a table, and i have to put buttons in the last column. i've been researching but all the codes i saw are really confusing. there is one tho, but there are still some parts that i didn't understand. here's the site where i got it http://www.javaquery.com/2013/05/how-to-implement-jbutton-in-jtable.html
String[] InvoiceArray = new String[20];
//Declare above variable globally. Used by two-three methods. Change variable name as per your need.
/*
* import the ButtonColumn class if you are not working in IDE
* I used formWindowOpened event to load content in Jtable but you can use other event.
* All you need is put the code with in that event.
*/
private void formWindowOpened(java.awt.event.WindowEvent evt) {
Object[][] rowData = new Object[4][2]; // 4: is number of row ; 2: is number of column
Object columnNames[] = {"Invoice No", "View Report"}; // Name of columns
for (int i = 0; i < 4; i++) {
InvoiceArray[i] = i + "-2345";
rowData[i][0] = i + "-2345";
rowData[i][1] = "View Order " + i; // Can change the text of button.
}
DefaultTableModel tm = new DefaultTableModel(rowData, columnNames);
jTable1.setModel(tm);
ButtonColumn buttonColumn = new ButtonColumn(jTable1, showOrder, 1); // 1: is column number. column count starts with 0,1,2...
}
what's the InvoiceArray for? and should i make the showOrder from the last line? and also, i didn't understand the code he posted on how to make a listener on it. here it is:
Action showOrder = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
//JTable table = (JTable) e.getSource(); // If you have multiple component following the ActionEvent
int modelRow = Integer.valueOf(e.getActionCommand());
if (InvoiceArray[modelRow] != null) {
/* We are placing invoice no in array
* And track the button click index
* And fetch index in invoice no
*/
System.out.println("Your Invoice No:" + InvoiceArray[modelRow]);
} else {
JOptionPane.showMessageDialog(rootPane, "No records found!");
}
}
};
i know there are some explanations already. i understand some of them but not all. just a simplier way to add jbutton on jtable and also listeners for the jbutton. thank you so much
just a simplier way to add jbutton on jtable and also listeners for the jbutton.
There is no simple way. You need to understand how renderers and editors work in a JTable. Read the section from the Swing tutorial on Concepts: Renderers and Editors for the basics.
Then you can check out Table Button Column which does the hard work for you. You only need to provide the Action to be invoked when you click on the button.
what's the InvoiceArray for?
It is used to load data into the JTable. This is basic usage of a JTable and has absolutely nothing to do with adding a button to a column of the table.
After the data is loaded you should forget about the invoiceArray. The Action you write should access the data via the TableModel or the JTable.
I have been trying to determine why my JComboBox is displaying the 1st item in the list through numerous Google searches, but I'm struggling to find relevant help. It could be that I don't know the correct terminology (hence the overly specific title of this question) and thus not finding the information that would explain my issue. I checked out the JComboBox API, and few of the listeners and models that it uses, but they did not seem likely candidates.
The JComboBox in question is inside a JTable, so I am not aware if that changes the default behaviour of it. The code I am using is as below:
//row and col are final due to usage inside anonymous inner class
public TableCellEditor getCellEditor(final int row, final int col)
{
String[] listItems = new String[arrayList.getSize()];
int i = -1;
for(String s : arrayList)
{
i++;
listItems[i] = s;
}
JComboBox<String> box = new JComboBox<>(listItems);
box.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
if(e.getStateChange() == ItemEvent.SELECTED)
{
if(e.getItem().equals("Add/Edit Projectile"))
{
//Where Editor is a JFrame that will be opened
new Editor();
}
}
}
});
DefaultCellEditor list = new DefaultCellEditor(box);
}
Please note that the Arraylist in my program does not contain Strings, but instead a more complicated set of custom objects that I believe would distract from the main issue.
I haven't included a Renderer for JComboBox's in the JTable as I was happy enough with the way it appeared, and figured that my problem was more going to be something I have neglected to implement in the model/implemented wrong.
I've also provided a couple of screenshots to better portray my problem. The first image is when the JComboBox is not selected, and simply displaying the currently selected item.
The second image is when I have just clicked the JComboBox to bring up the list. As depicted, it will immediately bring up that first item, no matter what it is.
If anyone has any suggestions as to where to look/solutions, I would be very grateful.
EDIT
My particular table has two columns, where the left column is a variable name, and the right column is the value associated with the variable. The tables role is to display the properties of a selected object, where each value for different variable for different objects are likely to not be the same.
In this particular case, the cell displays a JComboBox with all the available Projectiles in the game we are making. Each enemy has a different type of projectile it defaults to. So when I click on a different enemy in our game area, the table will display all of their current properties (defaults if they have not been changed).
Enemies do have a getter for the Projectile, so I could determine what the currently selected enemy is, get it's projectile, do a toString() to find how it is to be represented in the list, and do a setValueAt().
The only problem is at the moment it is always selecting the first item in the list when the list is expanded.
Unless the values for the JComboBox are dynamically generated for each row, you should be able to just prepare the CellEditor ahead of time, for example...
JComboBox cb = new JComboBox(new String[]{"1", "2", "3", "4"});
DefaultCellEditor editor = new DefaultCellEditor(cb);
JTable table = new JTable(new DefaultTableModel(5, 1));
table.getColumnModel().getColumn(0).setCellEditor(editor);
This will set the selected value of the editor to the value of the cell when the editing process starts
Updated
In the case where the combobox values are dynamically generate per row, you could do something more like...
JComboBox cb = new JComboBox();
DefaultCellEditor editor = new DefaultCellEditor(cb) {
#Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
JComboBox editor = (JComboBox) getComponent();
String[] listItems = new String[arrayList.getSize()];
int i = -1;
for (String s : arrayList) {
i++;
listItems[i] = s;
}
DefaultComboBoxModel model = new DefaultComboBoxModel(listItems);
editor.setModel(model);
editor.setSelectedItem(value);
return editor;
}
};
JTable table = new JTable(new DefaultTableModel(5, 1));
table.getColumnModel().getColumn(0).setCellEditor(editor);
Note the use of editor.setSelectedItem(value);, this will set the selected value to the cells current value...
You could also re-use the model, clearing it each time and re-filling it with new values. You might find this more efficient if you have a large number of rows as you won't need to constantly create a new model each time a cell is edited
Thow this is an oldie...
Your problem is most likely you don't implement "equals" in the class used in the combo.
The Combo needs to select the current item when it is being prepared and does so by iterating through the elements of the model and selects the first one that is equal to the value in the cell. If none is encountered then it leaves the combo as is (either first element or the last used element in a previous cell edit)
This is how you should default to the previously selected element:
//...
Object selectedItem = box.getSelectedItem();
//Add some elements to the jComboBox
box.setSelectedItem(selectedItem);
I have an ArrayList called conditionList which stores condition names.
Whenever one is added/edited or deleted, the Lists on my GUI update no problems.
You can see below that i use 2 models... a DefaultListModel called condListModel and a DefaultComboBoxModel called conditionModel.
The code i have below is for the method editCondition(), at this stage the text is already changed on the GUI and is being submitted here. On my GUI, after ive submitted the change, the ComboBox and JList change no problem so im sure that the model changes are correct.
HOWEVER MY PROBLEM IS: When i save the ArrayList conditionList through serialization, and then load it back up, the change is gone. SO I think there is problem in my code with changing the String Value in the ArrayList(named conditionList), can anyone have a look and see if u notice an issue
String conString = jListCondition.getSelectedValue().toString();
for(String c: conditionList)
{
if(conString.compareTo(c) == 0)
{
String temp = entConName.getText();
c = temp;
//edit the Condition jList model
int x = condListModel.indexOf(conString);
condListModel.setElementAt(temp, x);
jListCondition.setModel(condListModel);
//edit the Condition comboBox model
int i = conditionModel.getIndexOf(conString);
conditionModel.insertElementAt(temp, i);
conditionModel.removeElement(conString);
entCondition.setModel(conditionModel);
//reset buttons
editConConfirm.setEnabled(false);
editCon.setEnabled(false);
deleteCon.setEnabled(false);
entConName.setText("");
addCon.setEnabled(true);
}
}
I'm very new to Java and am having some issues looping through JCheckBoxes on a UI. The idea is that I have a bunch of checkboxes (not in a group because more than one can be selected.) When I click a JButton, I want to build a string containing the text from each selected checkbox. The issue I'm having is that our instructor told us that the checkboxes need to be created via a method, which means (see code below) that there isn't a discrete instance name for each checkbox. If there were, I could say something like
if(checkBox1.isSelected()) {
myString.append(checkBox.getText());
}
That would repeat for checkBox2, checkBox3, and so on. But the method provided to us for adding checkboxes to a panel looks like this:
public class CheckBoxPanel extends JPanel {
private static final long serialVersionUID = 1L;
public CheckBoxPanel(String title, String... options) {
setBorder(BorderFactory.createTitledBorder(BorderFactory
.createEtchedBorder(), title));
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
// make one checkbox for each option
for (String option : options) {
JCheckBox b = new JCheckBox(option);
b.setActionCommand(option);
add(b);
}
}
}
This is called like this:
toppingPanel = new CheckBoxPanel("Each Topping $1.50", "Tomato", "Green Pepper",
"Black Olives", "Mushrooms", "Extra Cheese",
"Pepperoni", "Sausage");
So I now have a panel that contains a border with the title "Each Topping $1.50", and 7 visible checkboxes. What I need to do is get a list of all the selected toppings. We are not supposed to use an ActionListener for each checkbox, but rather get the list when a button is clicked. I'm feeling really clueless here, but I just can't figure out how to get the isSelected property of the checkboxes when the individual checkboxes don't have instance names.
Ideally I'd like to somehow add all the checkboxes to an array and loop through the array in the button's action listener to determine which ones are checked, but if I have to check each one individually I will. I just can't figure out how to refer to an individual checkbox when they've been created dynamically.
I'm assuming you're not allowed to alter the CheckBoxPanel code at all. Which seems like a useless exercise, because in the real world, you'd think that if CheckBoxPanel where a class being provided to you (e.g. in a library) it would include a way of getting the selected options. Anyway, due to the limitation, you could do something like this:
for( int i=0; i<checkBoxPanel.getComponentCount(); i++ ) {
JCheckBox checkBox = (JCheckBox)checkBoxPanel.getComponent( i );
if( checkBox.isSelected() ) {
String option = checkBox.getText();
// append text, etc
}
}
I suggest you maintain a list of checkboxes:
List<JCheckBox> checkboxes = new ArrayList<JCheckBox>();
and before add(b) do:
checkboxes.add(b);
You may then iterate through the list of checkboxes in the buttons action-code using a "for-each" loop construct:
for (JCheckBox cb : checkboxes)
if (cb.isSelected())
process(cb.getText()); // or whatever.
Alternatively, if you need to keep track of the specific index:
for (int i = 0; i < checkboxes.size(); i++)
if (checkboxes.get(i).isSelected())
....
I would suggest that you dont put each of the checkboxes in a List when you create them. Instead, in your shared ActionListener, you maintain a Set of all selected checkboxes. Use the getSource method on the ActionEvent to identify which checkbox the user selected and then cast it to a JCheckBox. If isSelected() returns true for the item in question, attempt to add it to your selectedItems Set. If it is not, then attempt to remove it.
You can then just iterate over the subset of all items (only those that are selected) and print them to the console.
I got a doubt regarding pre-selecting(setSelectedIndex(index)) an item in a ListBox, Im using Spring + GWT.
I got a dialog that contains a panel, this panel has a FlexPanel, in which I've put a couple ListBox, this are filled up with data from my database.
But this Panel is for updates of an entity in my database, thus I wanted it to pre-select the current properties for this items, allowing the user to change at will.
I do the filling up in the update method of the widget.
I tried setting the selectedItem in the update method, but it gives me an null error.
I've searched a few places and it seems that the ListBox are only filled at the exact moment of the display. Thus pre-selecting would be impossible.
I thought about some event, that is fired when the page is displayed.
onLoad() doesnt work..
Anyone have something to help me out in here?
I really think you can set the selection before it's attached and displayed, but you have to have added the data before you can select an index. If this is a single select box you could write something like this:
void updateListContent(MyDataObject selected, List<MyDataObject> list){
for (MyDataObject anObject : list) {
theListBox.addItem(anObject.getTextToDisplay(), anObject.getKeyValueForList());
}
theListBox.setSelectedIndex(list.indexOf(selected));
}
If this is a multiple select box something like this may work:
void updateListContent(List<MyDataObject> allSelected, List<MyDataObject> list){
for (MyDataObject anObject : list) {
theMultipleListBox.addItem(anObject.getTextToDisplay(), anObject.getKeyValueForList());
}
for (MyDataObject selected : allSelected) {
theMultipleListBox.setItemSelected(list.indexOf(selected), true);
}
}
(Note I haven't actually compiled this, so there might be typos. And this assumes that the selected element(s) is really present in the list of possible values, so if you cant be sure of this you'll need to add some bounds checking.)
I've been happily setting both the values and the selection index prior to attachment so as far as I'm aware it should work. There's a bug however when setting the selected index to -1 on IE, see http://code.google.com/p/google-web-toolkit/issues/detail?id=2689.
private void setSelectedValue(ListBox lBox, String str) {
String text = str;
int indexToFind = -1;
for (int i = 0; i < lBox.getItemCount(); i++) {
if (lBox.getValue(i).equals(text)) {
indexToFind = i;
break;
}
}
lBox.setSelectedIndex(indexToFind);
}
Pre-selection should work also with setValue()-function. Thus, no complicated code is needed.