JButton btnAdd = new JButton("add");
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Main selectedValue = (Main)courseList.getSelectedValue();
if(selectedValue !=null){
orderList.addElement(chosenList);
}
}
});
i have created a addButton which adds elements from one Jlist to another Jlist. However, when i run my applction and click the add buttton it gives me this error in my chosenList Jlist:
javax.swing.JList[,-2008,0,2255x182,alignmentX=0.0,alignmentY=0.0,border=,flags=50332008,maximumSize=,minimumSize=,preferredSize=,fixedCellHeight=-1,fixedCellWidth=-1,horizontalScrollIncrement=-1,selectionBackground=javax.swing.plaf.ColorUIResource[r=184,g=207,b=229],selectionForeground=sun.swing.PrintColorUIResource[r=51,g=51,b=51],visibleRowCount=8,layoutOrientation=0]
I believe addElement method should be called on an instance of class DefaultListModel.
If you previously has added a DefaultListModel instance as the model for your orderList, you should use following code to add the element to your orderList.
Object selectedValue = courseList.getSelectedValue();
DefaultListModle listModel = (DefaultListModle)orderList.getModel();
listModel.addElement(selectedValue);
If you haven't set any instance of class which implements ListModel, you should initialize your orderList in this way:
DefaultListModel listModel = new DefaultListModel();
orderList = new JList(listModel);
// or
orderList.setModel(listModel);
Take a look at How to Use Lists from Java Tutorials.
What you are seeing in your list is not an error, but the toString() value for your chosenList object. Perhaps you mean to do the following instead:
orderList.addElement(selectedValue);
Instead of:
orderList.addElement(chosenList);
Related
alright.,ive already tried every trick off my sleeves..but couldnt figure out how to update the comboBox w/glazedList..if the input is coming from other class..ive tried passing the value to the methods,declaring it first to a string..and such..but none has work..tho it does work if the new item will just gonna come from same class..via click of a button..
so far ive got this code..
values = GlazedLists.eventListOf(auto);//auto is an array..
AutoCompleteSupport.install(comboSearch,values);//comboSearch is the comboBox
//"x" is the value coming from another class.
public void updateCombo(String x){
List<String> item = new ArrayList<>();
item.add(x)
value.addAll(item);
}
i hope this codes are enough to interpret what im trying to ask..
It's not possible to see how you've created your combobox and your eventlist. Therefore I'll just create a simple example application from scratch that shows you the essentials.
Just in case you're not familiar the general concepts the main take home points are:
Try and avoid using standard Java collections (eg ArrayList, Vector) and use the EventList class as soon as possible. All the goodness that comes with sorting/filtering/auto-complete relies on the EventList foundation so set one up asap and then simply manipulate (add/remove/etc) and then the GlazedLists plumbing will take care of the rest.
Once you've got your collection of objects in an EventList and you want to leverage a swing component then look in the ca.odell.glazedlists.swing module which contains everything you need. In this instance you can use an EventListComboBoxModel - pass in your eventlist, and then set your JComboBox model to use the newly created EventListComboBoxModel and from that point GlazedLists will take care of ensuring your list data structure and combobox stay in sync.
So in my example I create an empty combobox and an button. Clicking the button will add an item per click into the combobox. The magic is simply the creation of the EventList and the use of EventListComboBoxModel to link the list to the combobox.
Please note that the code below was only tested against GlazedLists 1.8. But I'm pretty sure it'll work fine with 1.9 or 1.7 too.
public class UpdateComboBox {
private JFrame mainFrame;
private JComboBox cboItems;
private EventList<String> itemsList = new BasicEventList<String>();
public UpdateComboBox() {
createGUI();
}
private void createGUI() {
mainFrame = new JFrame("GlazedLists Update Combobox Example");
mainFrame.setSize(600, 400);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton addButton = new JButton("Add Item");
addButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
itemsList.add("Item " + (itemsList.size()+1));
}
});
// Use a GlazedLists EventComboBoxModel to connect the JComboBox with an EventList.
EventComboBoxModel<String> model = new EventComboBoxModel<String>(itemsList);
cboItems = new JComboBox(model);
JPanel panel = new JPanel(new BorderLayout());
panel.add(cboItems, BorderLayout.NORTH);
panel.add(addButton, BorderLayout.SOUTH);
mainFrame.getContentPane().add(panel);
mainFrame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new UpdateComboBox();
}
});
}
}
I have few JFrames. Using one of them (it contains textBox) I want to transfer inputed data to the variable in another class. This variable is used to build JComboBox choose list. I try to transfer inputed data via JButton, but in the end nothing is transferred and JComboBox stays empty. Do I need to somehow refresh JComboBox or something? My code:
...
DataBase toTable = new DataBase();
...
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent click) {
toTable.data[0] = textField.getText();
}
});
Variable from DataBase class:
....
String data[] = {"","","","",""};
....
And the Main Class (it contains JComboBox):
...
DataBase data0 = new DataBase();
final JComboBox list0 = new JComboBox(data0.data);
list0.setBounds(10, 61, 110, 22);
contentPane.add(list0);
That's correct. The JComboBox doesn't notice that you updated the array. You will need to use the addItem or setModel method of JComboBox.
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent click) {
toTable.data[0] = textField.getText();
list0.setModel(new DefaultComboBoxModel(toTable.data));
}
});
Of course, this code won't run unless you can reference list0 in the same scope as your button. I would recommend putting button and list0 in the same class, if possible.
i would like to know, how can i add a new item by new panel in Java GUI.
I have class Program
public class Program extends javax.swing.JFrame {
public ArrayList<Contact> contacts = new ArrayList<Contact>();
public int pos;
public Program() {
contacts.add(new Contact("John Tavares", "736426436", "Prague"));
contacts.add(new Contact("John Doe", "725847896", "NY"));
contacts.add(new Contact("Damien Smith", "725589963", "London"));
pos = 0;
initComponents();
}
and then some labels which show content of ArrayList, it works fine. In class Contact have name, tel and city.
And i have JButton New Contact which opened new Panel NewContact with text fields for name, tel and city and of course OK JButton. This works fine, too.
Can anybody help me, please, how can i get texts from text fields in NewContact and add them to ArrayList?
Thanks for any advices
If I understand right, u waant to add contacts with a button.
At first you have to make a new button:
private JButton mybutton = new JButton("Add");
Then you have to override the actionListener
private void addActionListener() {
mybutton.addActionListener(this);
}
Then you have to sreach what kind of button you pressed:
#Override
public void actionPerformed (ActionEvent e) {
Object source = e.getSource();
if(source == mybutton)
contacts.add(something);
}
I would suggest a JTable should be used to display your data. Read the section from the Swing tutorial on How to Use Tables for more information.
In you new contact form you would then add the data to the TableModel directly. The DefaultTableModel supports an addRow(...) method.
For a more complex solution that lets you add a Contact to the TableModel you will need to create a custom model. You could use a Bean Table Model.
how can i get texts from text fields
You use the getText() method. Read the Swing tutorial. Maybe start with the section on How to Write an Action Listener. An ActionListener gets invoked when you click on a button.
Here is my code to create a Jlist and filling it up using action listener
At the first place I used an array of string to fill up the Jlist and I had scroller.
Then for upating Jlist I need to change the mode of the Jlist to DefaultListModel and as soon as I did that change I lost my scroller.
I donot know what went wrong
Can any one help me please
private Component makeListView() {
final DefaultListModel<String> listModel = new DefaultListModel<String>();
final JList<String> list = new JList<String>(listModel);
list.setModel(listModel);
updateCourseListPanel(listModel);
notifyObserverInModelForClickingOnListItem(list);
list.setPreferredSize(getSize());
list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
list.setLayoutOrientation(JList.HORIZONTAL_WRAP);
list.setVisibleRowCount(-1);
list.setFixedCellWidth(80);
JScrollPane listScroller = new JScrollPane(list);
listScroller.setPreferredSize(getMaximumSize());
setVisible(true);
return list;
}
hard to tell from your snippet (as you didn't show the code that calls it): on face value, the issue is that you return the list instead of the scrollPane it's added to.
The deeper issue is that you seem to (guessing only, though, for lack of details :-) re-create the list whenever the data needs to be updated. A better approach is to separate the creation of the list and its model from its update and only update the model as needed:
private Component makeListView() {
final DefaultListModel<String> listModel = new DefaultListModel<String>();
final JList<String> list = new JList<String>(listModel);
list.setModel(listModel);
list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
list.setLayoutOrientation(JList.HORIZONTAL_WRAP);
list.setFixedCellWidth(80);
JScrollPane listScroller = new JScrollPane(list);
return listScroller;
}
private void update(Jlist list) {
updateCourseListPanel(list.getModel());
notifyObserverInModelForClickingOnListItem(list);
}
BTW, never-ever call any of the setXXSize methods, some reasons
My main frame contains JScrollPane which lists some objects. Through menu (pop up frame) I create new object and I want to list this object in the JScrollPane (which is created in a constructor of DemoFrame class). How can I do it?
Part of my constructor in DemoFrame
ArrayList<Item> i = g.getAllItems();
Vector allItemsVector = new Vector(i);
JList items = new JList(allItemsVector);
panel.add( new JScrollPane( items ))
In pop up frame I add new object to 'g' object in that case. Have I designed it wrong?
A lot depends on information that you haven't told us, for instance just what is the JScrollPane holding? A JTable? A JList? The key will be to update the component being held by the JScrollPane and then revalidate and repaint this component.
Edit
You need to have a reference to the JList, so it should be declared outside of your constructor. For instance:
// GUI class
public class GuiClass {
private JList items; // declare this in the *class*
// class's constructor
public GuiClass() {
ArrayList<Item> i = g.getAllItems();
Vector allItemsVector = new Vector(i);
// JList items = new JList(allItemsVector); // don't re-declare in constructor
items = new JList(allItemsVector);
panel.add( new JScrollPane( items ))
}
Then later in your menu's listener code you can add an item to the items JList as needed.
This was a problem for me as well. A quick workaround is remove the JScrollPane from the panel, make your changes then readd it. Many may deem it inefficient, but it works with no significant change to runtime
JPanel panel = new Jpanel();
JList list = new JList({"this", "is", "a test", "list"});
JScrollPane sPane = new JScrollPane();
public void actionPerformed(ActionEvent e) {
if (resultsPane!=null){
panel.remove(sPane);
}
sPane = updatePane(list);
panel.add(sPane);
}
public void updatePane(String[] newListItems) {
DefaultListModel model = new DefaultListModel();
for(int i = 0; i < newListItems.length; i++) {
model.addElement(newListItems[i]);
}
JList aList = new JList(model);
JScrollPane aPane = new JScrollPane(aList);
}
Assuming I understood the question correctly:
You have a JFrame with a JScrollPane. And the JScrollPane has a JList.
The JList has a set of strings in it and this shows fine, but later you want to update the list and have it update in the JFrame view, but when you do update the list nothing happens to visualisation?
I had the same problem and how I got it to work was to set the content of the JList using a DefaultListModel. Instead of updating the contents of the JList, I update the contents in the DefaultListModel and then set the JList content to the model content when everything has been added. Then call the JScrollPane repaint function
//Declare list and pane variables up here so that we have a reference
JList<String> list;
JScrollPane pane;
//Set up the frame content
void SetupFrame() {
//instantiate the list
list = new JList();
//sets up the scroll pane to take the list
pane = new JScrollPane();
pane.setViewportView(list);
pane.setBounds(10, 10, 200, 80);
//adds the scrollpane to the frame
add(pane);
//update the list of strings
UpdateList();
}
//Updates the contents of the list (call this whenever you want to update the list)
void UpdateList() {
//model used to update the list
DefaultListModel model = new DefaultListModel();
//Update the contents of the model
for (int i = 0; i < 10; i++)
model.addElement("Test value");
//update the list using the contents of the model
connectionLabels.setModel(model);
//repaint the scrollpane to show the new list content
pane.repaint();
}