Addition in JList???

Can anyboty post a snippet on how to add numbers inside a JList?
(the list accepts only numbers)
In a textfield, the sum will be displayed.
thanks

You could use Integer objects I guess.
JList yourList = new JList(new DefaultListModel());
DefaultListModel mod = (DefaultListModel)yourList.getModel();
  // Just add some numbers
for(int i = 1; i <= 10; i++)
  mod.addElement(new Integer(i));

Similar Messages

  • Using a JList

    Hi everyone! Happy new year.
    Okay, I have some work for some keen programmer out there to do. There are 10 duke dollars avaliable to whoever can help me with this problem.
    I am using a JList to display a list of milestones which are required later on in my project. When no item is selected from the list, I want the 'Delete Milestone' button to automatically disable and when an item is selected from the list, I want it to auto enable. If the list is empty, then the button should remain disabled. For this to work I think I need some sort of ListSelectionListener but I am not sure how to do this. At the moment I get an exception whenever I click on the 'Delete Milestone' button and no selection has been made, which is understandable.
    Another thing that I need doing is that if a milestone is added to the list, and the 'Critical Milestone' is selected, then whenever that item is selected from the list, the background colour should be red; whenever a 'Non-critical Milestone' is created, then that should remain with a yellow background whenever selected from the list. At the moment, the background colour changes to whatever the last added milestone happened to be - either red or yellow for all entries that have been added to the list. If anyone can help me with this then that would be really appreciated and very helpful. The 4 files can be found below - just run the 'AddMilestoneTest' class to start the app. Thanks.
    * AddMilestoneTest.java
    * 29/12/02 (Date start)
    * This class is for iteration purposes for
    * the "Add Milestone" wizard
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    public class AddMilestoneTest extends JPanel
    private JButton addMilestoneButton;
    public JFrame addMilestoneFrame;
    static AddMilestoneTest instance;     
    public AddMilestoneTest()
         instance = this;
    // create new button
    addMilestoneButton = new JButton("Add Milestone");
    // create tooltip for every button
    addMilestoneButton.setToolTipText("Add Milestone");
    // add our button to the JPanel
    add(addMilestoneButton);
    // construct button action
    AddMilestoneListener listener1 = new AddMilestoneListener();
    // Add action listener to button
    addMilestoneButton.addActionListener(listener1);
    private class AddMilestoneListener implements ActionListener
    public void actionPerformed(ActionEvent evt)
    addMilestoneFrame = new JFrame("Add Milestone Wizard*");
    MilestoneSplitPanel milestoneSplitPanel = new MilestoneSplitPanel();
    addMilestoneFrame.getContentPane().add(milestoneSplitPanel);
    addMilestoneFrame.setSize(850, 305);
    addMilestoneFrame.setVisible(true);
    // Main entry point into the program
    public static void main(String[] args)
    // Create a frame to hold us and set its title
    JFrame frame = new JFrame("Add Milestone Iteration");
    // Set frame to close after user request
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    // Add our panel to the frame
    AddMilestoneTest amt = new AddMilestoneTest();
    frame.getContentPane().add(amt, BorderLayout.CENTER);
    // Resize the frame
    frame.setSize(680, 480);
    // Make the windows visible
    frame.setVisible(true);
    * MilestoneSplitPanel.java
    * 29/12/02
    * This class creates a split between the
    * AddMilestonePanel and the CurrentMilestonePanel
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    public class MilestoneSplitPanel extends JPanel
    // Declare a split panel
    JSplitPane splitPanel;
    // Declare the panels required here
    AddMilestonePanel addMilestonePanel;
    CurrentMilestonePanel currentMilestonePanel;
    public MilestoneSplitPanel()
    // Create the panels required
    addMilestonePanel = new AddMilestonePanel();
    currentMilestonePanel = new CurrentMilestonePanel();
    // Create the split panel with our two panels
    splitPanel = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, currentMilestonePanel, addMilestonePanel);
    splitPanel.setDividerLocation(200);
    //Provide minimum sizes for the two components in the split pane
    addMilestonePanel.setMinimumSize(new Dimension(350, 200));
    currentMilestonePanel.setMinimumSize(new Dimension(100, 100));
    //Add the split panel to this panel.
    add(splitPanel, BorderLayout.CENTER);
    * AddMilestonePanel.java
    * 29/12/02 (Date start)
    * This class is for iteration purposes for
    * the "Add Milestone" wizard
    import javax.swing.*;
    import javax.swing.border.*;
    import java.awt.*;
    import java.awt.event.*;
    public class AddMilestonePanel extends JPanel
    private JLabel milestoneNameLabel;
    private JLabel milestoneNameMaxChar;
    private JLabel milestoneECDLabel;
    private JLabel forwardSlash1;
    private JLabel forwardSlash2;
    private JLabel dateFormatLabel;
    private JLabel selectOne;
    private JTextField milestoneName;
    private JComboBox theDate;
    private JComboBox theMonth;
    private JComboBox theYear;
    private ButtonGroup group;
    private JRadioButton criticalMilestone;
    private JRadioButton nonCriticalMilestone;
    private JButton addMilestone;
    private JButton deleteMilestone;
    private JButton cancel;
    private JButton finish;
    private JList currentMilestones;
    static AddMilestonePanel instance;
    public String dateSelected;
    public String monthSelected;
    public String yearSelected;
    public AddMilestonePanel()
    instance = this;
    // create additional panels to hold objects
    JPanel topPanel = new JPanel();
    JPanel middlePanel = new JPanel();
    JPanel lowerPanel = new JPanel();
    JPanel buttonPanel = new JPanel();
    // Create a border around the "toppanel"
    Border etched = BorderFactory.createBevelBorder(BevelBorder.RAISED, Color.black, Color.blue);
    Border titled = BorderFactory.createTitledBorder(etched, "Provide a name for the milestone");
    topPanel.setBorder(titled);
    // Create a border around the "middlepanel"
    Border etched1 = BorderFactory.createBevelBorder(BevelBorder.RAISED, Color.black, Color.blue);
    Border titled1 = BorderFactory.createTitledBorder(etched1, "Enter an estimated completion date of the milestone");
    middlePanel.setBorder(titled1);
    // Create a border around the "lowerpanel"
    Border etched2 = BorderFactory.createBevelBorder(BevelBorder.RAISED, Color.black, Color.blue);
    Border titled2 = BorderFactory.createTitledBorder(etched2, "Choose whether the milestone is critical or non-critical");
    lowerPanel.setBorder(titled2);
    // initialise JLabel objects
    milestoneNameLabel = new JLabel("Milestone Name: ");
    milestoneNameMaxChar = new JLabel("(Max 20 chars)");
    milestoneECDLabel = new JLabel("Estimated Completion Date: ");
    forwardSlash1 = new JLabel("/");
    forwardSlash2 = new JLabel("/");
    dateFormatLabel = new JLabel("(Date/Month/Year)");
    selectOne = new JLabel("(Select One)");
    // create textfield for the milestone name
    milestoneName = new JTextField(20);
    milestoneName.setColumns(15);
    topPanel.validate();
    // create the combo boxes for the date
    theDate = new JComboBox(new String[]
    "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16",
    "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31"
    theDate.setEditable(false);
    theMonth = new JComboBox(new String[]
    "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"
    theMonth.setEditable(false);
    theYear = new JComboBox(new String[]
    "2001", "2002", "2003", "2004", "2005", "2006", "2007", "2008", "2009", "2010", "2011", "2012"
    theYear.setEditable(false);
    // create the radio buttons and add them to the group
    group = new ButtonGroup();
    criticalMilestone = new JRadioButton("Critical Milestone", true);
    nonCriticalMilestone = new JRadioButton("Non-critical Milestone", false);
    group.add(criticalMilestone);
    group.add(nonCriticalMilestone);
    // create the buttons
    addMilestone = new JButton("Add Milestone", new ImageIcon("D:/My Uni Work/Final Year Project/Graphics/addMilestoneIcon.JPG"));
    deleteMilestone = new JButton("Delete Milestone", new ImageIcon("D:/My Uni Work/Final Year Project/Graphics/deleteMilestone.JPG"));
    cancel = new JButton("Cancel", new ImageIcon("D:/My Uni Work/Final Year Project/Graphics/StopControl.gif"));
    finish = new JButton("Finish", new ImageIcon("D:/My Uni Work/Final Year Project/Graphics/bluearrow.gif"));
    // set tooltips for buttons
    addMilestone.setToolTipText("Add Milestone");
    deleteMilestone.setToolTipText("Delete Milestone");
    cancel.setToolTipText("Cancel");
    finish.setToolTipText("Finish");
    // set the state of the buttons when first run
    deleteMilestone.setEnabled(false);
    finish.setEnabled(false);
    // add objects to panels
    topPanel.add(milestoneNameLabel);
    topPanel.add(milestoneName);
    topPanel.add(milestoneNameMaxChar);
    middlePanel.add(milestoneECDLabel);
    middlePanel.add(theDate);
    middlePanel.add(forwardSlash1);
    middlePanel.add(theMonth);
    middlePanel.add(forwardSlash2);
    middlePanel.add(theYear);
    middlePanel.add(dateFormatLabel);
    lowerPanel.add(criticalMilestone);
    lowerPanel.add(nonCriticalMilestone);
    lowerPanel.add(selectOne);
    buttonPanel.add(addMilestone);
    buttonPanel.add(deleteMilestone);
    buttonPanel.add(cancel);
    buttonPanel.add(finish);
    // use Box layout to arrange panels
    Box hbox1 = Box.createHorizontalBox();
    hbox1.add(topPanel);
    Box hbox2 = Box.createHorizontalBox();
    hbox2.add(middlePanel);
    Box hbox3 = Box.createHorizontalBox();
    hbox3.add(lowerPanel);
    Box hbox4 = Box.createHorizontalBox();
    hbox4.add(buttonPanel);
    Box vbox = Box.createVerticalBox();
    vbox.add(hbox1);
    vbox.add(Box.createGlue());
    vbox.add(hbox2);
    vbox.add(Box.createGlue());
    vbox.add(hbox3);
    vbox.add(Box.createGlue());
    vbox.add(hbox4);
    this.add(vbox, BorderLayout.NORTH);
    // create instance of cancelButtonListener
    CancelButtonListener cancelListen = new CancelButtonListener();
    // create instance of AddMilestoneListener
    AddMilestoneListener milestoneListener = new AddMilestoneListener();
    // create instance of DeleteMilestoneListener
    DeleteMilestoneListener deleteListener = new DeleteMilestoneListener();
    // add actionListener for the buttons
    cancel.addActionListener(cancelListen);
    addMilestone.addActionListener(milestoneListener);
    deleteMilestone.addActionListener(deleteListener);
    private class CancelButtonListener implements ActionListener
    public void actionPerformed(ActionEvent event)
    Object source = event.getSource();
    if(source == cancel)
    AddMilestoneTest.instance.addMilestoneFrame.setVisible(false);
    private class AddMilestoneListener implements ActionListener
    public void actionPerformed(ActionEvent event)
    String milestoneNameText = milestoneName.getText().trim();
    int textSize = milestoneNameText.length();
    dateSelected = (String)theDate.getSelectedItem();
    monthSelected = (String)theMonth.getSelectedItem();
    yearSelected = (String)theYear.getSelectedItem();
    if(textSize > 20)
    //display a JOptionPane
    JOptionPane.showMessageDialog(AddMilestonePanel.instance, "You have entered a title that is greater than 20 characters.",
    "Text too Long", JOptionPane.ERROR_MESSAGE);
    else if(textSize == 0)
    //display a JOptionPane
    JOptionPane.showMessageDialog(AddMilestonePanel.instance, "You have not entered a milestone name. Please do so (Maximum 20 Characters).",
    "No Project Name Entered", JOptionPane.ERROR_MESSAGE);
    else if(dateSelected == "30" && monthSelected == "02" || dateSelected == "31" && monthSelected == "02" || dateSelected == "31" && monthSelected == "04" ||
    dateSelected == "31" && monthSelected == "06" || dateSelected == "31" && monthSelected == "09" || dateSelected == "31" && monthSelected == "11")
    JOptionPane.showMessageDialog(AddMilestonePanel.instance, "You have selected an invalid date. Re-check that the date is valid.",
    "Invalid Date Selected", JOptionPane.ERROR_MESSAGE);
    } // ANOTHER CHECK IS REQUIRED HERE WHEN INTEGRATING - IF DATE ENETERED IS WITHIN THE START DATE AND END DATE OF THE PROJECT
    else
    deleteMilestone.setEnabled(true);
    finish.setEnabled(true);
    if(criticalMilestone.isSelected())
    CurrentMilestonePanel.instance.listModel.addElement(milestoneNameText);
    CurrentMilestonePanel.instance.currentMilestoneList.setSelectionBackground(Color.red);
    else if(nonCriticalMilestone.isSelected())
    CurrentMilestonePanel.instance.listModel.addElement(milestoneNameText);
    CurrentMilestonePanel.instance.currentMilestoneList.setSelectionBackground(Color.yellow);
    private class DeleteMilestoneListener implements ActionListener
    public void actionPerformed(ActionEvent event)
    if(CurrentMilestonePanel.instance.listModel.size() > 0)
    int selectedItemIndex = CurrentMilestonePanel.instance.currentMilestoneList.getSelectedIndex();
    CurrentMilestonePanel.instance.listModel.remove(selectedItemIndex);
    * CurrentMilestonePanel.java
    * 29/12/02 (Date start)
    * This class is for iteration purposes for
    * the "Add Milestone" wizard
    import javax.swing.*;
    import javax.swing.border.*;
    import java.awt.*;
    import java.awt.event.*;
    public class CurrentMilestonePanel extends JPanel
    public JList currentMilestoneList;
    private JLabel currentMilestonesAdded;
    // List Model that will hold the data for the list
    public DefaultListModel listModel;
    // Scroll pane that will contain the list
    private JScrollPane scrollPaneList;
    static CurrentMilestonePanel instance;
    // Constructor
    public CurrentMilestonePanel()
    instance = this;
    // create label
    currentMilestonesAdded = new JLabel("Current Milestones Added");
    listModel = new DefaultListModel();
    //listModel.addElement("No Milestones Added");
    // Create the list
    currentMilestoneList = new JList(listModel);
    // Set single selection, and select the first item
    currentMilestoneList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    currentMilestoneList.setSelectedIndex(0);
    // Create a scroll panel to hold list
    scrollPaneList = new JScrollPane(currentMilestoneList);
    // Set the preferred size
    scrollPaneList.setPreferredSize(new Dimension(130, 200));
    //Add the scroll pane to this panel.
    add(currentMilestonesAdded, BorderLayout.NORTH);
    add(scrollPaneList, BorderLayout.CENTER);

    I suggest that you look into the swing tutorial. There are some samples of how to write ListSelectionListener.
    I quickly scanned your code for the DeleteMilestoneListener. You get an exception here because you don't check if an item is selected in the list.

  • Using an embedded driver instead of client, and refreshing JList

    I am finishing up a simple database interface program that I need to do in order to graduate. There are a couple issues I need to address.
    1. This program is meant to be on one computer with one connection to a database. Currently, when I build the program and run the .jar file, it will not work unless I have manually started the server in Netbeans. Once the server is on, it works like a champ. But since I have to send this to my professor it must work without him doing any additional setup. For this I figured I could use the embeddedDriver, but unfortantely I cant get that to work.
    In netbeans I can right click on the main database icon and select "New Connection" and i have the option of choosing the embedded driver yet when i put the database name in and the user and password it gives me the
    error: "Unable to add connection. Cannot establish a connection to jdbc:derby:MaxxTrax using org.apache.derby.jdbc.EmbeddedDriver (Database 'MaxxTrax' not found).
    Why is it that I can use the client driver without a problem yet not the embedded one? And if I cant use the embedded one, how can I set up the client driver so it will automatically start the server (does the end user need to have the server installed or will the clean and build do that)?
    2. Using the netbeans gui builder, i created a jList that I bound to my database's name query. I then have multiple textFields that i bound to whatever jList selection there is and tell it to update with the specified data. My problem is, that I cannot get the jList to "refresh". Right now when I add somebody to the database it visually writes over another persons record, but doesn't actually delete record. So if i could just figure out how to make it look at the database again I could do it automatically after entering in a new record. I've tried nameList.validate(), updateUI() and even tried to copy the ide generated code that actually binds the data but no go.
    Once I get these two little things taken care of I am done!! Please help, its greatly appreciated.

    I'm not getting much help out there.....anyone??
    I need to make the database seem invisible to the end user application.
    When I try to use an embedded driver I keep getting errors. In netbeans, I can see the "Java DB(Embedded)" link under drivers, and when I hit connect using.. I input all the correct data and it gives me the following error:
    Error: Unable to add connection. Cannot establish a connection to jdbc:derby:MaxxTrax using org.apache.derby.jdbc.EmbeddedDriver (Database 'MaxxTrax' not found).
    Under the Database setting the pointer for the java db installation and database location are correct. Why can't I connect using the embedded driver, cause using that would make my life so much easier for a single application.

  • A list that's not a JList

    Hi all,
    I'm trying to create what is effectively a list of panels - where each panel (ie list entry) added to the list will contain additional subcomponents (progress bars, buttons, labels, etc).
    I could implement this by creating a custom ListCellRenderer for a JList, but I need the panels to be fully interactive, so I'm trying to come up with a solution involving a main JPanel within a JScrollPane, then adding additional subpanels as needed.
    However, I'm having a hell of a time trying to get it right - I want each subpanel entry to have a fixed height (say 100px) but to be as wide as the main window is wide (the JScrollPane shouldn't scroll horizontally) (just like in a JList).
    Can anyone suggest recommended layout managers to achieve this? Most things I've tried have always just made each subpanel fill the entire available space, or fixed their width so they don't resize to fit horizontally.
    To complicate matters, I need to be able to add and remove entries from the list at runtime. A JList is obviously designed for this, but won't let you add interactive panels as entries - unless I've missed something?
    Thanks in advance
    Iain

    You can do this with a JList by using a custom editor in addition to a custom
    renderer.
    As far as a layout, you have some choices. Some people would suggest
    SpringLayout for this, but I'm more comfortable with GridBagLayout, so try
    wrapping the (untested) code below in a JFrame. I'm setting the preferred
    height to 100 for each panel separately because there's no way for any
    layout to do that for you. The width can be any value.
    final JPanel pane1 = new JPanel();
    pane1.setBackground(Color.RED);
    pane1.setPreferredSize(new Dimension(0, 100));
    final JPanel pane2 = new JPanel();
    pane2.setBackground(Color.GREEN);
    pane2.setPreferredSize(new Dimension(0, 100));
    final JPanel listPane = new JPanel(new GridBagLayout());
    final GridBagConstraints gbc = new GridBagConstraints();
    gbc.weightx = 1;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    gbc.anchor = GridBagConstraints.EAST;
    gbc.gridx = 0;
    gbc.gridy = 0;
    listPane.add(pane1, gbc);
    gbc.gridy++;
    listPane.add(pane2, gbc);

  • Indicate most recently selected item in JList

    When a JList is set for multiple item selection,
    is there any way to visually indicate to the user
    which item has been most recently selected?
    I notice that in a JTable, a coloured border
    gets painted around the cell most recently
    clicked on (this is in addition to any cell
    background colouring which may be done). This would
    be sufficient in my case for a JList, but I
    cannot tell that JList supports this.
    Any suggestions?
    b.c

    Good point. I've just tried the following:
    Implement a custom cell renderer. In the method,
    getListCellRendererComponent(), when the cell
    has focus, add a coloured border to it. If the
    cell does not have focus, make the border null.
    Works beautifully.
    b.c

  • Selecting a JList with right-click

    What's the best way for a JList to select its value with a right-click. I plan on bringing up a JPopupMenu on the same right click too.

    You would probably add the standard listener for this sort of thing
    with the addition of selecting the item under the mouse.
    class PopupListener extends MouseAdapter {
        public void mousePressed(MouseEvent e) {
            maybeShowPopup(e);
        public void mouseReleased(MouseEvent e) {
            maybeShowPopup(e);
        private void maybeShowPopup(MouseEvent e) {
            if (e.isPopupTrigger()) {
                // Make selection
                JList list = (JList) e.getComponent();
                Point p = e.getPoint();
                int index = list.locationToIndex( p );
                if ( index != -1 ) {
                     Rectangle r = list.getCellBounds( index, index );
                     if ( r.x <= p.x && p.x <= r.x + r.width &&
                          r.y <= p.y && p.y <= r.y + r.height )
                         list.setSelectedIndex( index );
                // show popup
                popup.show(e.getComponent(),
                           e.getX(), e.getY());
    }If you want more advanced selection capabalities with the right click,
    I'd look at implementing your own MouseInputHandler which checks for
    isMouseLeftButton() || isPopupTrigger(); see BasicListUI.MouseInputHandler.

  • JList and ListSelectionEvent : How to get the deselected Value

    Hi,
    All of you know:
    The ListSelectionEvent occurs two times:
    1.) An Enty is deselected
    2.) The new Entry is selected.
    I wanted to use the first occurence to save some data from the deselected Entry (from an Editor to a Record), and the second occurence to load the Data from the selected Entry to an Editor.
    (Until now, i use a additional lastSelectedIndex Property for that, but i dont find this very elegant.)
    Now i found that the index is allways the same. The output of the code is:
    Event 0 Index:2
    Event 1 Index:2
    Has anybody an idea how to get the deselected Value ??
    public void valueChanged(javax.swing.event.ListSelectionEvent listSelectionEvent) {
    JList list=(JList)listSelectionEvent.getSource();
    int selectedIndex = list.getSelectedIndex();
    System.out.println("Event " + count + " Index:" + selectedIndex);
    count = count+1;
    // Drop one oft them...
    if (listSelectionEvent.getValueIsAdjusting()) return;
    count=0;
    }

    Thanks, but thats not exactly what i wanted.
    I have a selectedIndex: 5
    Now i select a other item in the List, say Index: 2.
    The ListSelection-Event occurs two times:
    My understand was:
    The first occures, because an Item was deselected: index should be:5
    The second occures, because an Item was selected : index should be:2
    Is my thinking wrong?
    The code above allways gets only Index 2.
    How can i get the Index/Value 5,

  • JTable Cell grays out when I click the cell below (JList editor & renderer)

    Click on any cell, then click on the cell immediately below.. and the first cell u clicked on goes gray... After repaints and stuff, it stills stays gray
    * TimetableCellGui.java
    * Created on April 12, 2007, 7:21 PM
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package timetable.gui;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Font;
    import java.util.ArrayList;
    import java.util.EventObject;
    import javax.swing.DefaultListModel;
    import javax.swing.JList;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.event.CellEditorListener;
    import javax.swing.table.TableCellEditor;
    import javax.swing.table.TableCellRenderer;
    * @author jay
    public class TimetableCellGui extends JList implements TableCellRenderer, TableCellEditor {
         * Creates a new instance of TimetableCellGui
        public TimetableCellGui() {
            this.setFont(new Font("Nice",Font.PLAIN,10));
            this.setForeground(new Color(150,150,250));
        private static String courseFilter = "";
        private static String roomFilter = "";
        private static boolean filterCourse = false;
        private static boolean filterRoom = false;
        public static String getCourseFilter() {
            return courseFilter;
        public static String getRoomFilter() {
            return roomFilter;
        public static boolean isFilterCourse() {
            return filterCourse;
        public static boolean isFilterRoom() {
            return filterRoom;
        public static void setCourseFilter(String c) {
            courseFilter = c;
        public static void setFilterCourse(boolean f) {
            filterCourse = f;
        public static void setFilterRoom(boolean filter) {
            filterRoom = filter;
        public static void setRoomFilter(String r) {
            roomFilter = r;
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            if(value == null) {
                return null;
            } else {
                DefaultListModel model = new DefaultListModel();
                String addition = "some addition";
             model.add(addition);          
                model.add(addition);                
                this.setModel(model);
                return new JScrollPane(this);
        public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
            if(value == null) {
                return null;
            } else {
                DefaultListModel model = new DefaultListModel();
                String addition = "some addition";
             model.add(addition);                          
                this.setModel(model);
                return new JScrollPane(this);
        public Object getCellEditorValue() {
            return "helllo";
        public boolean isCellEditable(EventObject anEvent) {
            return true;
        public boolean shouldSelectCell(EventObject anEvent) {
            return true;
        public boolean stopCellEditing() {
            return true;
        public void cancelCellEditing() {
            super.clearSelection();
        public void addCellEditorListener(CellEditorListener l) {
        public void removeCellEditorListener(CellEditorListener l) {
    }

    I'm doing up a timetable. And so far, I've found that is the best way to display it. However if you can think of a better way, I'm willing to listen, but if u havn't gotten a better suggestion... Plz try and help me tweak this one to work... Because I've done quite a bit of work on this one so far

  • Update chat client JList

    I have a client and server app and Want to update the JList evertime a client joins or leaves.
    I also want to implement private chat later on. I know i can send a vector with the names of the clients to each client and update the list, but if im gonna do private chat, how can I enable clients to click on the list and when they select a peer to chat with, thier able to make and i/o stream and that with that person.
    I was thinking that I can make and additional ObjectInputStream/ObjectOutputStream and send the entire client object from the server side. That object would be "SocketThread" which is a class i made to handle each multiple client connection. The server side has Server.java, SocketThread.java, ChatProtocol.java
    This is the Thread that represents each client on the server side.
    vsockets is a Vector that adds each client object to the vector so the server can echo each client message to every other client.
    public SocketThread(Socket socket) {
                this.socket = socket;
                start();
            public void run()
            try {
                socket.setSoTimeout(60*1000);   // Client sends "alive" message in keep alive thread every
                out = new PrintWriter(socket.getOutputStream(), true);
                in = new BufferedReader( new InputStreamReader( socket.getInputStream()));
                ChatProtocol cp = new ChatProtocol();
                inputLine = in.readLine();
                UserID = cp.processInput(inputLine);
                out.println("Rabbit's Socket Server, NY!");    // Welcome Message
                System.out.println("* "+UserID + " joined the server!");
                for ( i=0;i<Server.vsockets.size();i++)
                    SocketThread temp  = (SocketThread)Server.vsockets.elementAt(i);
                    temp.out.println("* "+UserID + " joined the server!"); //no "\n" server tokenizer adds it already
                while ((inputLine = in.readLine()) != null)
                    if(!inputLine.equals("alive")){
                    outputLine = cp.processInput(inputLine);
                    for (i = 0; i< Server.vsockets.size(); i++)
                        SocketThread temp = (SocketThread)Server.vsockets.elementAt(i);
                        temp.out.println(outputLine);
            }How would I go about implementing private chat. I think it has something to do with object serialization. Not sure how to do it.
    thanx

    Hello Jino!
    I think u r working in the right direction.
    I think it is better to have a vector there at client to represent the current users and u fill its elements when u send the notification for newuser logged in and remove the entry when any user left notification is there.
    I hope u got the idea.
    Best of Luck.
    Ahmad Jamal.

  • JLIst and ListModel

    I have a class which implements the ListModel interface which I am trying to use. It works fine when I initialize a JList with it (new JList(myModel)), but when I use the JList.setModel() method to change to another one of my models, it gets messed up. For some reason the addListDataListener() method of my model is not even called. So as a result I have a JList which thinks it has a model, but is not listening for events from that model. Can anyone help me out?

    I meant a site where I could upload it, but I geuss I can put the it here.
    It is sort of a weird class, about 100 lines and the formatting got messed up, sorry.
    public class VectorListModel extends Vector implements ListModel {
          private Vector listeners;     // The ListDataListeners that are listening to this
       private Vector bound; // Vector whose contents should match these
          /** Default no options constructur */
          public VectorListModel() {
         super();
               listeners = new Vector();
          /** Add a ListDataListener to listen for ListDataEvents from this
          * ListDataListener to add.
          public void addListDataListener(ListDataListener l) {
               listeners.add(l);
         System.err.println("DEBUG: VLM adding LDL "+l.toString()+" to "+this.toString());
         System.err.println("DEBUG: VLM new size of listeners "+listeners.size());
       public int getSize() {
         return size();
       public Object getElementAt(int index) {
         return get(index);
          /** Remove a ListDataListener
          * @param l ListDataListener to remove.
          public void removeListDataListener(ListDataListener l) {
               listeners.remove(l);
          /** Adds the specified Object to the data Vector
          * @param o Object to add
          public boolean add(Object o) {
               ListDataEvent lde = new ListDataEvent(this, ListDataEvent.INTERVAL_ADDED, size()+1, size()+1);
               super.add(o);
         System.err.println("DEBUG: VLM adding "+o.toString());
         System.err.println("DEBUG: VLM going to notify "+listeners.size()+" listeners of addition");
         /* Notify all listeners */
               Iterator it = listeners.iterator();
               while(it.hasNext()) {
                    ListDataListener ldl = (ListDataListener)it.next();
           System.err.println("DEBUG: VLM Notifying "+ldl.toString()+" of addition of "+o.toString());
                    ldl.intervalAdded(lde);
         /* Duplicate the change for all bound Vectors */
         if(bound != null)
           bound.add(o);
         return true;
          /** Removes the specified Object from the data Vector
          * @param o The Object to remove
          public boolean remove(Object o) {
               ListDataEvent lde = new ListDataEvent(this, ListDataEvent.INTERVAL_REMOVED, indexOf(o), indexOf(o));
               super.remove(o);
         /* Notify all listeners */
               Iterator it = listeners.iterator();
               while(it.hasNext()) {
                    ListDataListener ldl = (ListDataListener)it.next();
                    ldl.intervalRemoved(lde);
         /* Duplicate the change for all bound Vectors */
         if(bound != null)
           bound.remove(o);
         /* FIXME: This should only be true if the vector actually contained o */
         return true;
          /** Replace oldObj with newObj in the data array
          * @param oldObj Old Object to be replaced
          * @param newObj New Object to take oldObj's place
          public void replace(Object oldObj,  Object newObj) {
         ListDataEvent lde = new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, indexOf(oldObj), indexOf(oldObj));
               int index = indexOf(oldObj);
               if(index != -1)
                    setElementAt(newObj, index);
         /* Notify all listeners */
         Iterator it = listeners.iterator();
               while(it.hasNext()) {
                    ListDataListener ldl = (ListDataListener)it.next();
                    ldl.contentsChanged(lde);
         /* Duplicate the change for all bound Vectors */
         if(bound != null)
           bound.setElementAt(newObj, index);
       /** Associates <CODE>v</CODE> with this VectorListModel such that
         * any changes made to this VectorListModel through the add(), remove(),
         * or replace() methods will also be applied to <CODE>v</CODE>
         * @param v The Vector to associate.
       public void bind(Vector v) {
         bound = v;
       /** Disassociate <CODE>v</CODE> from this VectorListModel
         * @param v The Vector to disassociate.
       public void unbind(Vector v) {
         bound = null;
    }

  • DnD between Jlist and Canvas...

    Is it all possible to drag the list item from JList and drop it inside the Canvas and place a reference (e.g. lsit item name ) at the exact coordinates where the drop is performed?
    Additionally, for the purpose of my project the Canvas already contains an image of a model space and would need to stay in the background all along!
    Please if anyone have any thoughts, recomendations, suggestions post these here.
    Thanks

    Please, is drag and drop possible between JList and Canvas components so that the inserted item from JList is displayed over the image displayed in the Canvas component?

  • Reposition scrollbar when updating JList

    I'm not sure how to approach this problem. I have a JList which resides in a JScrollPane. This list is updated every few seconds with setListData(). The list only has 5 viewable items so the user must scroll to see any additional. However when the list is updated it causes the Scrollbar (Knob) to reset to the top position. Forcing the user to scroll down every few seconds to see the additional items. I'm looking for a way to reposition the the view to the users last scrolled position. Or get the scrollbar to ignore the refresh and remain at the previous position.
    Any thoughts?

    Theres still some inconsistentency with it. But youfolks set me on the right track.
    Does that mean it works or it doesn't work?
    Sometimes you need to wrap methods in a
    SwingUtilties.invokeLater() to make sure the code
    gets execute in the correct order. So you can try
    wrapping the ensureIndexIsVisible(..) method to make
    sure it executes after all the code invoked by the
    setListData() method.Well I think what I've done is crafted a well hidden bug in my code. Using ensureIndexIsVisible() will properly position the scroll bar for a random number of setListData() cycles. Then the scrollbar returns to the top. I think I may be inadvertantly setting another or an invalid index.

  • Can't view data in IT302 - Additional Actions

    Hi Gurus,
    I cannot view any data in IT302 using Ad Hoc Query.
    Correct infoset was set up which include Additional actions infotype.
    IT302 was also properly set up in t77S0> ADMIN-EVSUP set to 1.
    And in T529A all Actions set to be updated in IT302.
    There are also Additional Action entries in table PA0302 but when I search it in Ad Hoc Query for a personnel number the fields (Action Type, Reason) turn up blank.
    Do I still have to make other configurations?
    Any ideas?
    Kindly help.
    Points will be given out
    Thanks,
    Olekan Babatonde

    I was in the need of getting the output based on Additional actions, and was able to figure out the way as how to do it., I am writing this here not that you would still in need but some one in future might come to this thread and get away with the answer.
    1. First we need to add Infotype 0302 to our infoset (Going toSQ02, Menu bar, Edit -> Change infotype selection.
    2. Once you have the infotype under the Data fields.
    3. Try adding each individual field under the field group/data fields by right clicking on the necessary infotype field and selecting Add field to Field group.
    4. Once you got all your IT0302 fields under field group/data fields right side of the window, save your infoset and run the  infoset query.
    5. Now you have the input fields and output fields to be selected from infoset query.
    6. Select input fields as Pernr, and action start date and end date from IT0000
    7. Select output fields from 0302 infotype fields, you may select all the necessary fields in the output, but the required one is "Counter Field"
    8. Once you have your hitlist from the ad hoc query, refresh the list from bottom of the screen and picks up all the ones who have the counter field as 1 - they are the ones, who has additional actions on specific date.
    Hope it helps to the viewers.
    Warm Regards!
    -Kanuku

  • Locked out of additional internal drives... Help please

    Any help would be more then welcomed as I did something stupid and need a bit of help to fix it please.
    Had an issue today on my Mac Pro (2.8, Quad 5.1). All was running fine until I went to update a piece of 3rd party software (Fetch). After the download I went to drag new version into my apps folder and was told I didn't have permission to instal the app.
    Now to be clear, I've had a bit of an issue with this before as I'm running 2 mac pros in different locations and drag and copy files and folders from here to there on a regular basis via FTP and external drives. I also have all 4 slots filled on both systems with various drives set up for a particular function along with a number of externals. I've set permissions on both systems and all drives to "read and write" for both my accounts to have full access and each time "apply to enclosed items" was selected.
    But for some reason, from time to time, I have to authorise the file transfer. Haven't figured out the reason but it's not a huge deal so have left it.
    Today was the first time I have had access denied for my home folder when working from same system. Not thinking and while on the phone to someone (this is where I did the stupid part), I opened the info on my boot (startup) drive and decided to add both of my user accounts and change permissions for each in addition to the system, admin and everyone that was already there. This was done while working from it directly and then set options to "apply to enclosed items". Yea, smart I know.
    About 20 minutes passed and then it told me that it didn't like any of my system extensions. I was forced to do a restart and got the spinning wheel for about 30 minutes. Had to do a force quit and open in single user. Applejack wouldn't help at all, nothing. Had to then open cd drive through terminal just to get systems disk inside.
    Restarted from systems disk and tried a simple disk utility repair. System restarted fine but I noticed that I was then locked out of all of my additional internal drives, iDisk included (padlock shown on all drive icons excluding my Boot/Startup drive). Tried opening info on the various drives with apple i option and "permissions denied" popped up each time.
    I then took the step to restore from time machine. Set my restore selection to about 2 hours before I became an idiot. After it was finished I restarted the system hoping that would clear up my mistake but same thing, still locked out of all of my drives aside from boot/startup drive.
    All user accounts that I have added to the boot drive are still showing, I have yet to try and remove them... Figured I would ask for help before I messed it up any further. Spoke to apple care and they have advised me to do what I have done so far.
    Aside from an erase and instal, what steps should I take from this point? Will removing the added accounts clear up the issue?
    Also, any idea as to why I was refused permissions to begin with...?
    Thanks in advance and sorry for the book, just wanted to be as clear as possible.

    Force iPad into Recovery Mode. Follow step 1 to step 3 very closely.
    http://support.apple.com/kb/HT1808

  • Hi Guys,  I am using the full width video widget on a site. The widget was working perfectly however I have just added additional content to the site and re-uploaded and now the video is not working! Please help I have tried everything and am freaking out

    Hi Guys,
    I am using the full width video widget on a site. The widget was working perfectly however I have just added additional content to the site and re-uploaded and now the video is not working! Please help I have tried everything and am freaking out as this web-site has been payed for by my client.
    Alex

    Many thanks.
    With those symptoms, I'd try the following document:
    Apple software on Windows: May see performance issues and blank iTunes Store
    (If there's a SpeedBit LSP showing up in Autoruns, it's usually best to just uninstall your SpeedBit Video Accelerator.)

Maybe you are looking for

  • Thinkpad Yoga - touch screen on left half of the screen unresponsive

    Hi guys! On my new TPY the touch screen on the left hand side (the side where the charger is connected) is unresponsive. The pen however works perfectly fine. I have already run the lenovo software update tool and updated/installed all the drivers so

  • Unattended Kickstart

    Is it possible to run the kickstart command without user interaction, either in the form of a .sh script, an applescript, or a package? I'm trying to avoid touching the machines after they have been imaged. Thanks for the help guys. David

  • Can we set no range as mm/dd/yyyy format?

    Is it possible to configure purchasing document number in such a fashion that system should start fresh numbering for each financial year. E.g for year 2008- 2009 PO number should start with 0809/000001 and so on and for year 2009- 2010 numbering sho

  • Sennheiser mic is not working on audigy 2

    i have a sennheiser headset with mic,the mic used to work but windows no longer recognizes it,when i test hardware or the audigy 2 zs dosent.i know the mic works as when i plug it into mic socket on the audigy card,i can hear the jack going in replay

  • Pen Pressure Greyed out CS6

    When attempting to set the brush to "pen pressure" it is greyed out. I have uninstalled and reinstalled the driver with the latest driver. I have rebooted multiple times. Reconnected the tablet multiple times. Cleared out the options cache on the tab