Jlist question

i was wondering if there is a way to format the information in a jlist into columns so that each piece of data is aligned correctly? example output:
Name Age Weight
John 15 150
Kyle 17 175
Christopher 14 160
i cant just hard code where the age/weight should print out since the user will be specifying what name will be entered, age, ect. any information will be helpful

any reason you're not using a JTable? - looks ideal for your data
anyway, if you want to use a JList, a multi column might do the trick
experiment with the horizontal alignment - change Kyle's weight to 99 to see
import javax.swing.*;
import java.awt.*;
class Testing extends JFrame
  String[][] data = {{"Name","Age","Weight"},{"John","15","150"},{"Kyle","17","175"},{"Christopher","14","160"}};
  DefaultListModel dlm = new DefaultListModel();
  JList list = new JList(dlm);
  public Testing()
    setLocation(400,300);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    list.setCellRenderer(new MyRenderer());
    JScrollPane sp = new JScrollPane(list);
    sp.setPreferredSize(new Dimension(200,200));
    getContentPane().add(sp);
    pack();
    for(int x = 0; x < data.length; x++) dlm.addElement(data[x]);
  public static void main(String[] args){new Testing().setVisible(true);}
class MyRenderer extends JPanel implements ListCellRenderer
  JLabel[] lbl = new JLabel[3];
  public MyRenderer()
    setLayout(new GridLayout(0,3));
    for(int x = 0; x < lbl.length; x++)
      lbl[x] = new JLabel();
      if(x > 0) lbl[x].setHorizontalAlignment(JLabel.CENTER);//<-----experiment with this
      lbl[x].setOpaque(true);
      add(lbl[x]);
  public Component getListCellRendererComponent(JList list,Object value,
                      int index,boolean isSelected,boolean cellHasFocus)
    for(int x = 0; x < lbl.length; x++)
      lbl[x].setText((String)((String[])value)[x]);
      if(cellHasFocus) lbl[x].setBackground(Color.CYAN);
      else lbl[x].setBackground(Color.WHITE);
    return this;
}

Similar Messages

  • JList question, pls help!

    Hi friends,
    I am trying to creat a table with JList in a JPanel, the table has a form like:
    1 a b c d
    2 e f g h
    3 i j k l
    As much as i know, JList represent here rows which means that a complete row e.g. "1 a d c d" is a cell of this JList. But how can I display each cell when it is not a single Object but a Vector (here "1 a b c d")?
    This is part of my code, and thanks for any suggestions!
    class MyCellRenderer extends javax.swing.JPanel
    implements javax.swing.ListCellRenderer
    javax.swing.JLabel[] elementsLine;
    // This is the only method defined by ListCellRenderer. We just
    // reconfigure the Jlabel each time we're called.
    public MyCellRenderer()
    setLayout(new javax.swing.BoxLayout(this, javax.swing.BoxLayout.X_AXIS));
    setPreferredSize(new java.awt.Dimension(40, 19));
    setMinimumSize(new java.awt.Dimension(40, 19));
    setMaximumSize(new java.awt.Dimension(32767, 19));
         setBackground(combinedList.getBackground());
    // foreground is set for each JLabel, see below
    elementsLine = new javax.swing.JLabel[numOfElements];
    for(int i = 0; i < numOfElements; ++i) {
    elementsLine[i] = new javax.swing.JLabel();
    elementsLine.setPreferredSize(new java.awt.Dimension(40, 19));
    elementsLine[i].setMaximumSize(new java.awt.Dimension(32767, 19));
    elementsLine[i].setMinimumSize(new java.awt.Dimension(40, 19));
    elementsLine[i].setFont(combinedList.getFont());
    add(elementsLine[i]);
    public java.awt.Component getListCellRendererComponent(
    javax.swing.JList list,
    Object value, // value to display
    int index, // cell index
    boolean isSelected, // is the cell selected
    boolean cellHasFocus) // the list and the cell have the focus
    /*PROBLEM!!! because here value is a unique "1" in stead of "1 a b c d" */
    java.lang.Object[] sa = (java.lang.Object[])value;
    for(int i = 0; i < elementsLine.length; ++i) {
    elementsLine[i].setText(((java.lang.String)sa[i]));

    First the obvious question - can't you use a JTable?
    Next - to do what you want with a JList you need to create your own list cell renderer. If you look at the Javadoc for JList, there's some example code for a renderer there (that one adds an icon to list elements, but you'll get the idea...).
    For your particular case, you could make the renderer return a JPanel with an X-axis BoxLayout (or it could even return a Box object), into which it has put the elements of your vector.

  • Jlist Question. Please guide

    Chaps
    I HAVE A QUESTION Regarding JList
    1 have a Jlist composing of 8 elements
    So,
    This is displayed as :
    1 [ListenerFocus is here]
    2
    3
    4
    5
    6
    7
    8
    Now,I want this list to be displayed as
    [Gap in the layout]
    1 [Listener Focus is here]
    2
    3
    4
    5
    Is this possible? Can I have a gap in this layout?

    how about putting empty elements first and then actual data???

  • Should I be using an IO Stream? Also a mouseClick/JList question.

    I've gotten a lot better with debugging my code, however, there's still a lot in Java I don't know anything about yet. My current problem is this:
    I have a NewMemberFrame that is basically a form to collect data from the User and write it to a database when the user hits Submit. It then resets all the fields, closes the NewMemberFrame, and is supposed to open up a MemberFrame with all of the new information printed in it. The problem I'm having is that the program is writing to the database and then reading it before the written material shows in the database. This leaves me with a MemberFrame with no new information on it. I have added the following for loop after writing to the database:
            for (int i=1; i<=59999; i=i+1) {
               System.out.println(i);
      }This stalls the reading method long enough for the Database to register the new information, however, I'm betting it's a huge waste of resources as it lags the hell out of my computer. So should I be using the IO Streams in order to have access to the wait(); method or is there better way to accomplish this pause?
    Also, I can't seem to figure out what to do with the mouseClick in a JList... The JList API ( http://java.sun.com/j2se/1.4.1/docs/api/javax/swing/JList.html ) suggests the following code:
    final JList list = new JList(dataModel);
    MouseListener mouseListener = new MouseAdapter() {
         public void mouseClicked(MouseEvent e) {
             if (e.getClickCount() == 2) {
                 int index = list.locationToIndex(e.getPoint());
                 System.out.println("Double clicked on Item " + index);
    };But I can't figure out what to do with index after this point. I'm aware that it makes the int index = the line that the User double clicked but how do you use that information? I'm trying to make the double clicked line open the above MemberFrame using that line's contents to pull the necessary data from the database.
    Is there any suggestions out there?

    Ok,
    I understand your problem. I was stuck in the same place.
    Do one thing ... You must be having a primary key for each row in the Table.
    1. Initialize a Vector.
    2. When adding the DB Data to the JList add the Primary Key to the Vector. ( Now the Index of the JList Element and the Vector Element Point to the same Primary Key )
    3. When DoubleClicked on the JList, Get the Index and search the Primary Key in the Vector based on that index.
    4. On that primary key get the required record from the Database.
    e.g.
    Suppose student_code is the primary key.
          Vector miData = new Vector(5);
          // Your loop for pulling the data into the JList
                listModel.addElement(...... ;
                miData.add(rs.getInt("student_code"));
          // Jlist is Double Clicked
             // Get Index of the selected Item
             i = listModel.getSelected.....;
             miData.getElementAt(i);
             // You get the corresponding primary key
             rs = stmt.executeQuery("SELECT * FROM ..... WHERE student_code=" + i + "); 
    OR ( to all 1....4 )
    1. Create a class that has parellal fields to the Table.
    2. In the Loop, After adding the a..b..c..d to the JList, create a instance of the Class, Fill it with the Info and Store it in the vector.
    3. Then from based on the JList Index ( DblClick ) the Vector will have the corresponding class stored into it on the same index.
    4. Retrive it and show the info.
    Short Example.
    student table
    Fields are ...
    student_code int,
    student_name varchar(20)
      // Create a corresponding class
      class student
         public student(int s_code, string s_name)
             // Get the information into the class
             stu_code = s_code;
             stu_name = s_name;
         public int stu_code;
         public string stu_name;
      // Init a Vector
      Vector miData = new Vector(5);
      // In your JList filling loop after you add the item to the JList
      student s = new student(rs.getInt("student_code"), rs.getString("student_name"));
      miData.add(s);
      // While retriving, retrive the entire class by the index of the JList
      student s2 = (student) miData.getElementAt(jlist_index);
      // Access and show the individual fields
      System.out.println("" + s2.stu_code);
      System.out.println("" + s2.stu_name);Tell me if the first one doesnt work.
    Regards ,
    Karan

  • JList to JTable questions

    Hi, from looking at discussion groups and forums it appears that JList does not support the editability function; therefore, people suggest using a one column table instead.
    In changing the code around, I have a few questions
    Originally, I have the following for JList so that I can detect whenever
    an item has been deleted or added to the list
    activeModelList.getModel()
    .addListDataListener(new ListDataListener() {
    Now, the activeModelList is actually a JTable with a model that is a DefaultTableModel instead of DefaultListModel. How can I still be able to detect changes? what type of Listener can I use?
    Then, originally I had indicated default selections in the JList using the following activeModelList.setSelectedIndex(1); The only thing that I could think of to do the same for the table was activeModelList.setRowSelectionInterval(1,0); Is this good programming practice? Is this correct?
    Thank you very much for your inputs and advice.

    I think i figured out the .addListDataListener(new ListDataListener() equivalent... anyone know how to convert activeModelList.addListSelectionListener(new ListSelectionListener() {
    to one that would work the same in JTable
    someJTableFormerActiveModelList.add?

  • Jlist / JScrollPane simple question

    Hi all.
    I have a question in general about JList, and in particular about this simple code. The code sets up a list in which the first entry is too long for the width I want the list to be. Is there any way at all to get it to wrap lines? Even if it made that one entry several lines? Would JList be able to handle that at all? Note: I can't make this a JApplet because I want to include this in some larger code that stops working if it's a JApplet. Don't know if that means anything.
    Any help at all is appreciated. If you need clarification, I am happy to try to provide it. I'm a total n00b so you go ahead and patronize me.
       import javax.swing.*;
       import java.awt.*;
       import java.awt.event.*;
       public class StreamsApplet extends java.applet.Applet implements ActionListener {
          private static final String CHARSET = "UTF-8";
          Button add;
          Button remove;
          JList list;
          private DefaultListModel listModel;
          public void init() {
            listModel = new DefaultListModel();
            listModel.addElement("Debbie Scott blablablablablablablablablabla");
            listModel.addElement("Scott Hommel");
            listModel.addElement("Sharon Zakhour");
            listModel.addElement("Debbie Scott");
            listModel.addElement("Scott Hommel");
            listModel.addElement("Sharon Zakhour");
            listModel.addElement("Debbie Scott");
            listModel.addElement("Scott Hommel");
            listModel.addElement("Sharon Zakhour");
            listModel.addElement("Debbie Scott");
            listModel.addElement("Scott Hommel");
            listModel.addElement("Sharon Zakhour");
            listModel.addElement("Debbie Scott");
            listModel.addElement("Scott Hommel");
            listModel.addElement("Sharon Zakhour");
            list = new JList(listModel);
            list.setSelectionMode(
              ListSelectionModel.SINGLE_SELECTION);
            JScrollPane pane = new JScrollPane(list);
            add(pane, BorderLayout.CENTER);
            add = new Button("To 10");
            remove = new Button("To 2");
            JPanel bottomPanel = new JPanel();
            bottomPanel.add(add);
            bottomPanel.add(remove);
            add(bottomPanel, BorderLayout.SOUTH);
            add.addActionListener(this);
            remove.addActionListener(this);
              public void actionPerformed(ActionEvent e) {
                   if (e.getSource() == add)
                     list.setSelectedIndex(10);
              list.ensureIndexIsVisible(10);
              if (e.getSource() == remove)
                   list.setSelectedIndex(2);
                   list.ensureIndexIsVisible(2);
    }

    Everything you need to know, you can find right here:
    http://java.sun.com/docs/books/tutorial/uiswing/components/list.html

  • Very Simple question about JList

    Hi,
    I am newbie to Java, and I want to show a couple of items in JList Control, but it doesn't show up, anyone can help me. When I use system.out to printout the contents of the ListModel, it does tell me that those items are in it.
    Thanks a lot!!!!
    Code are like this:
    import java.lang.*;
    import javax.swing.*;
    public class listExample extends javax.swing.JApplet {
    public void init(){
    String[] data={"one", "two", "three", "four"};
    jList1=new JList(data);
    for(int i=0; i<jList1.getModel().getSize(); i++)
    System.out.println(jList1.getModel().getElementAt(i));
    public listExample() {
    initComponents();
    private void initComponents() {
    jList1 = new javax.swing.JList();
    getContentPane().add(jList1, java.awt.BorderLayout.CENTER);
    // Variables declaration - do not modify
    private javax.swing.JList jList1;
    // End of variables declaration

    The objects in your list probably don't know how to display themselves. To do this you must overload the toString method that is originally in java.lang.Object. So basically if you have an object with a String for a first name and last name, for example, you would write a toString() method that looks something like this:
    public String toString() {
    return firstName + " " + lastName;
    When you put this object in a list the JList will use the toString method automatically to place text in teh JList object.
    Hope it helps.

  • A question about JList (URGENT)

    I have a jtextfield that you can write anything on, another jtextfield that only accepts integers that are greater than 0 , a Jbutton, and a JList.
    I wanna add a listener for the JButton so that whenever it is pressed, the String in the first textfield will be put in the list in x number of times.
    x = the integer in the second textfield
    THANKS SO MUCH!!!

    In the actionlistener for the button:
    get the value from the Text JTextField, if empty exit.
    get and convert the value from the Integer JTextField, if 0 or not a number then exit.
    get the model (DefaultTableModel) from the JList.
    call the model.addElement(Object) passing the value from the Text JTextField in a loop controlled by the value in the Integer JTextField.
    Dave

  • Scrolling question when using JLists

    I have a JList inside of a JScrollPane that I add items to dynamically. When a new item is added to the bottom of the list I would like the JList to somehow scroll so that the newest item is always displayed. Basically I want to anchor the vertical scroll bar to the bottom instead of the top. Anyone know how to do this?

    From the JList API:
    ensureIndexIsVisible(int index)

  • Simple Question: JList and JDesktopPane in the same Swing app?

    Hi,
    I'm really inexperienced with Swing and so have hit what I think is quite a simple problem that I hope someone here can help me with.
    I have a class Frame which extends JFrame, I would like to have it contain a JTree running down the left hand side, with the rest of the JFrame taken up by a JDesktopPane. I have sorted out the code for both the JDesktopPane and the JTree independently, and can get them displaying on their own, but how can I display them side by side?
    I have a feeling that I have to use some layout manager of some sort and add the JTree and JDesktopPane to it, then add the layout to the JFrame or something but as you can tell I'm a little lost.
    I hope that this is a simple problem, it certainly seems quite fundamental and so I hope that someone can help!
    Thanks in advance
    Richard

    JFrame by default has a BorderLayout Manager
    so to add these two componets for the center one add it as usual, but for the other u have to add it
    JFrame.getContentPane().add(instance, BorderLayout.WEST);
    or any one of three other values.
    hope this is what u ask about

  • 2 new question concerning JList

    Hello!
    Thx for solving my first problem. But i have two more :(:
    I'm trying to write an own calendar for a special program, and the days of the week (monday, tuesday...) must be set unselectable.
    1. How can i change the background-color of one entry?
    2. Is it possible to draw a line between the days of the week and the rest of the calendar?
    The calendar looks like this:
    Mo 01 08 ...
    Tu 02 09 ...
    We 03 10 ...
    Th 04 11 ...
    Fr 05 12 ...
    Sa 06 13 ...
    Su 07 14 ...
    But should look like this (with one line, not with several like here):
    Mo | 01 08 ...
    Tu | 02 09 ...
    We | 03 10 ...
    Th | 04 11 ...
    Fr | 05 12 ...
    Sa | 06 13 ...
    Su | 07 14 ...

    1) You can achieve this using a custom cell renderer.
    2) You might want to use a JTable instead. It is possible to do it with a ListCellRenderer but kinda painful in a way.

  • Questions on events in a multi-class GUI

    I have a GUI application that is constructed as follows:
    1. Main Class - Actually creates the JFrame, contains main method, etc.
    2. MenuBar Class - Constructor creates a new JMenuBar structure and populates it with various JMenus and JMenuItems. A new instance of this class is instantiated in the Main Class to be used in the setMenuBar() method.
    3. ContentPane Class - Constructor creates a vertical JSplitPane. A new instance of this class is instantiated in the Main Class to be used in the setContentPane() method.
    4. BottomPane Class - Constructor creates a JPanel and populates it with various stuff. A new instance of this class is instantiated in the Content Pane Class to be used as the bottom pane in the vertical JSplitPane.
    5. TopPane Class - Constructor creates a horizontal JSplitPane and populates the left pane with a JScrollPane containing a JList. A new instance of this class is instantiated in the Content Pane Class to be used as the top pane in the vertical JSplitPane.
    6. TabbedPane Class - Constructor creates a JTabbedPane. A new instance of this class is instantiated in the Top Pane Class to be used as the right pane in the horizontal JSplitPane.
    7. DisplayPane Class - Constructor creates a JPanel. A new instance of this class is instantiated in the Tabbed Pane Class as the first tab. The user has the ability to click at points in this pane and a dialog box will pop up prompting the user for a string. Once the user enters something and clicks "OK", an instance of a custom Java2D component that I've created will be added to the DisplayPane where the user had clicked, with the string the user inputted being used as its name. The user can then drag the component around, enter a key combination to display all the names, etc.
    8. Custom Java2D Component Class - Constructor creates my custom Java2D component. Instances of this are added to the Display Pane Class, as I have described.
    Now, originally, I was going to ask "How do you work with events between these multiple classes?" but I have solved half of that problem myself with the following class:
    9. Listener Class - A new instance of this class is declared in the constructor of the Main Class, and is thus passed down through the GUI hierachy via the constructors of the various classes. I then use the addActionListener() method on various components in the other classes, and then the Listener Class can capture an event using the getActionCommand() method to figure out what fired the event.
    So that covers the "How do I capture events in multiple classes?" question. Now I'm left with "How do I affect changes on those classes based on events?"
    For example: In my MenuBar class, I have a "Save" menu item. When this is clicked, I want to declare a new JFileChooser and then use the showSaveDialog() method, which throws up a dialog for saving a file. The problem is, the showSaveDialog() method takes a Component which is the parent frame. Obviously the Listener Class is not a frame. I want to use the Main Class as the parent frame. How would I do this sort of thing?
    Another example: In my MenuBar class, I have a "New" menu item. For now, I want this to invoke a method in the DisplayPane Class that erases all of my custom Java2D components that have been made, thus giving the user a clean slate. How would I give my Listener Class access to that method?
    A final example: Every time the user adds one of my custom Java2D components, I want that component's name to be added to the JList that is in my TopPane class. Vice versa with deleting a component: its name should be removed from the JList. How would I listen for new components being added? (A change listener on the pane? One on the ArrayList<> that contains all of the components? Something else?) And, of course, how would I give the Listener Class the ability to change the contents of the JList?
    One idea I've come up with so far is to instantiate a new instance of each of my GUI classes in the Listener class, but that doesn't really make much sense. Wouldn't those be new instances that are totally separate from the instances the rest of my program is using? Another thought is to make the Listener Class an internal class inside the Main Class so that it can use the accessor methods of the GUI classes, but a.) I would like to avoid stuffing everything in one class and b.) this brings up the question of "How would I get an accessor method that is in a class that is two or three deep in the hierarchy?" (.getSomething().getSomethingInsideThat().getSomethingInsideTheInsideThing()?)
    Help with answering any or all of my questions would be much appreciated.

    Hrm. At the moment, for my first attempt, I'm doing something similar, it just strikes me as quite unwieldy.
    Start of Listener class, with method for setting what it listens to. (I can't use a constructor for this because the MenuBar and the ContentPane take an instance of
    this Listener class in through their constructors. You can't pass the Listener in through their constructors while simultaneously passing them in through this
    Listener's constructor. That would be an endless cycle of failure. So I just instantiate an instance of this Listener class, then pass it in through the MenuBar and
    ContentPane constructors when I instantiate instances of them, and then call this setListensTo() method.)
    public class Listener implements ActionListener
      private MenuBar menuBar;
      private ContentPane contentPane;
      public void setListensTo(MenuBar menuBar, ContentPane contentPane)
        this.menuBar = menuBar;
        this.contentPane = contentPane;
      }The part of my actionPerformed() method that does some rudimentary saving, which I will make more complicated later:
    else if (evt.getActionCommand() == "saveMenuItem")
      JFileChooser fileChooser = new JFileChooser();
      int returnVal = fileChooser.showSaveDialog(menuBar.getTopLevelAncestor());
      if (returnVal == JFileChooser.APPROVE_OPTION)
        File file = fileChooser.getSelectedFile();
        ArrayList<Node> nodes = contentPaneClass.getTopPaneClass().getTabbedPane().getDisplayPane().getNodes();
        try
          BufferedWriter out = new BufferedWriter(new FileWriter(file));
          for (int i = 0; i < nodes.size(); i++)
            Node node = nodes.get(i);
            out.write(node.getIndex() + "," + node.getXPos() + "," + node.getYPos() + "," + node.getName());
            out.newLine();
          out.close();
        catch (IOException e)
          //To be added                    
    }That part that seems unwieldy is the
    ArrayList<Node> nodes = contentPaneClass.getTopPaneClass().getTabbedPane().getDisplayPane().getNodes();The reason I'm using a separate Listener class is because if I put, say, the actions for the MenuBar in the MenuBar class, and then want to save stuff in the JPanel
    at the bottom of the hierachy, I would have to go up from the MenuBar into the JFrame, and then back down the hierachy to the JPanel, and vice versa. Kind of like
    walking up a hill and then down the other side. I imagine this would be even more unwieldy than what I'm doing now.
    On the plus side, I am making progress, so thanks all for the help so far!

  • I need help, I have alot of questions too (swing, code, optimizing...)

    Hi, I'm having a little trouble with aligning my GUI correctly. Here are screenshots from my laptop which runs OS 10.4 & my PC running Windows 2000:
    http://kavon89.googlepages.com/clipper.png <= On the laptop
    http://kavon89.googlepages.com/clipper_windows2000.jpg <= On the PC
    I don't know why the OS 10.4 looks almost perfect and the win 2k is a disaster. I played with it on my laptop and once i came over to my PC to post a problem about somthing else, i noticed this issue on my windows box. My guess is that either the JButton on OS 10.4 is smaller than the one for win2k and causing the automatic organizing to malfunction... or maybe the pixels are larger on my PC then on my laptop.
    I was thinking that I should make diffrent .jar's for each OS since there are GUI issues.... or is there a way to make it universal? (i read somwhere about GridBag?)
    Next off, Is there any way to reduce the size of the space between the JList box closest to the top of the frame & the buttons & text box below it? I tried all sorts of resizing and it seems stuck on some sort of space there which i would like to make compact.
    Those are all the swing questions i have ^
    About my code:
    I recently added 2 buttons which are at the bottom of the OS 10.4 screenshot, Clear Box & Drop All. Clear Box is the one I made work, or so I thuoght. I wrote this for my Clear Box button (by the way, the button is sapose to just clear the text box directly to the upper left of itself.)
           if(e.getSource() == buttonc)
               textfield.setText("");
           }I thought that was the best way to go about clearing the text box. just setting it to blank. But after some testing to ensure there were no reprocussions, I found a problem... When i select somthing from my JList and hit Clear Box, it deletes the entry in the JList when it is not sapose to. It also does it when there is text in the textbox and i have selected somthing in my JList. I haven't been able to figure out why. Here is my full source code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class winclipstart
      JButton buttona, buttond, buttonc, buttonda;
      DefaultListModel clippedtxt = new DefaultListModel();
      JTextArea textfield;
      JList ClippedLines;
      public static void main(String[] cheese){new winclipstart().buildGUI();}
      public void buildGUI()
        JFrame frame;
        Container contentPane;
        JPanel Bottom = new JPanel();
        JPanel Top = new JPanel();
        frame = new JFrame();
        frame.setTitle("Clipper 0.1 Beta");
        contentPane = frame.getContentPane();
        ClippedLines = new JList(clippedtxt);
        JScrollPane scroll2 = new JScrollPane(ClippedLines, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        scroll2.setPreferredSize(new Dimension(400,150));
        textfield = new JTextArea(3,20);
        JScrollPane scroll1 = new JScrollPane(textfield, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        buttona = new JButton("Clip");
        buttond = new JButton("Drop");
        buttonc = new JButton("Clear Box");
        buttonda = new JButton("Drop All");
        Bottom.add(scroll1);
        Bottom.add(buttona);
        Bottom.add(buttond);
        Bottom.add(buttonc);
        Bottom.add(buttonda);
        Top.add(scroll2);
        Box All = Box.createVerticalBox();
            All.add(Top);
            All.add(Box.createVerticalStrut(5));
            All.add(Bottom);
        contentPane.add(All);
        buttonL cl = new buttonL();
        buttona.addActionListener(cl);
        buttond.addActionListener(cl);
        buttonc.addActionListener(cl);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setResizable(false);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        frame.setSize(424,314);
        ClippedLines.setDragEnabled(true);
      public class buttonL implements ActionListener
        public void actionPerformed(ActionEvent e)
           if(e.getSource() == buttona)
              String elementToAdd = textfield.getText();
              if(elementToAdd.equals("")==false) clippedtxt.addElement(textfield.getText());
           else
             int index = ClippedLines.getSelectedIndex();
             if(index > -1) clippedtxt.remove(index);
           if(e.getSource() == buttonc)
               textfield.setText("");
    }There is a stray dragenabled true line in there which on my ibook showed that it drags after holding the mouse button down a little longer than expected, and it shows im dragging , but obiously not dropping because i haven't configured dropping yet. but on my windows machine it shows nothing of it. oh and, on the ibook it shows it with a green "+" and then makes it look like im trying to put it inbetween two other lines but does nothing when dropped like expected
    Another question: In the beginning of my code i have it loading the entire library with the *, and i noticed after turning it into a .jar that it loads slower than i expected... would a way to speed it up be to specify exactly what i need loaded after the program is finished or would it make no diffrence?
    :-/ seems my program isn't as cross platform as i exptected java to be

    I solved the code problem myself after a careful run through of the code, the "else" in my subclass made it so that every button other than the Add button deleted a selected entry, i quickly fixed it and made it an if statement.
    Thank you for the link cotton.m
    My question bout optimizing still remains though:In the beginning of my code i have it loading the entire library with the *, and i noticed after turning it into a .jar that it loads slower than i expected... would a way to speed it up be to specify exactly what i need loaded after the program is finished or would it make no diffrence?

  • How To : Get subdirectories and show them in a JList()

    Hello again ..
    Some of you might have noticed it: I already had a question yesterday.
    Today it's a problem of the same kind. This time there are Dukes assigned to it !
    The problem :
    - I'm pretty new to Java ( following a course @ school for 2 months now)
    - I'm working on an application that gives me a view of all the movies I have in a directory.
    What I want : My application has to search in that directory ( "D:\\Movies\" ) and display the name of each subdirectory in a JList()
    (don't forget that I need the full path saved somwhere so that I can open it later. Why? So that I can watch the movie by just clicking on a button)
    What I do now is: Fill a Db with all the details and then put it into a JList --> .equals("NOT THE BEST WAY ME THINKS");
    Any ideas/tutorials ...
    Thanks

    I told you I would read it later but I forgot :X
    I've read it now ... and to create the list I just use this :
    public String[] setListTitles()
              File directory = new File("D:\\Movies\\");
              if(!directory.exists())
                   return null;
              return directory.list();
         }I'm also using a JFileChooser someone recommended me on this forum. First time I use this and it causes problems hehe
    public void chooseDirectory()
              JFileChooser chooser = new JFileChooser();
              chooser.setDialogTitle("Choose The Directory That Conatains The Movies");
              chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
              chooser.showOpenDialog(this);
              System.out.println(chooser.getCurrentDirectory());
         }I've learned all methods of that class and ... when I select for example : D:\Movies\ ---> It prints D:\
    What am I doing wrong AGAIN?
    Thanks

  • How to get default color of a selected row in a JLIst

    I have a JList that I am changing the font color for based on a certian situation so I created my own MyCellRenderer to do this. However, when I select an item in the list the row is no longer highlighted. I used the isSelected method to determine if a row was selected and then change the background color of that row. However, I would like the color to be the default color that you get when you select a row in a default JList. I can't seem to figure out how to get that color. How do I obtain what that color is? I found an example where you can get the default color for the background of a button and use that color so I would guess it is something similar to that. My code is below so I hope someone can tell me how to get that color that I want.
    Thanks...Chris
    class MyCellRenderer extends JLabel implements ListCellRenderer {
         public MyCellRenderer() {
              setOpaque(true);
         public Component getListCellRendererComponent(
             JList list,
             Object value,
             int index,
             boolean isSelected,
             boolean cellHasFocus)
             int index1 = value.toString().indexOf("-");
               String errors = value.toString().substring(index1 + 1, index1 + 6).trim();
             int numErrors = Integer.parseInt(errors);
               if (numErrors > 0)
                      setForeground(Color.red);
                      setBackground(Color.white);          
             else
                  setBackground(Color.white);
                  setForeground(Color.black);
             if(isSelected)
                  //ColorUIResource col = (ColorUIResource)UIManager.getDefaults().get("JButton.background");
                  ColorUIResource col = (ColorUIResource)UIManager.getDefaults().get("Button.background");
                  setBackground(col);
             setText(value.toString());
             return this;
    }

    Swing related questions should be posted in the Swing forum.
    I would like the color to be the default color that you get when you select a row in a default JList. I can't seem to figure out how to get that colorlist.getSelectionBackground();

Maybe you are looking for

  • Desktop and windows have all capital A's (AAAA...) instead of normal labels

    Hi, folks. While having trouble getting my AC power supply cord to power up the 'book (the cord wires were broken and the power would only flow if the cord were held in one position) the battery eventually was exhausted and the 'book shut down. This

  • How left-click "mouse" on MacBook Pro retina display?

    A video I want to download to my rMBP says I need to left-click my mouse on a screen icon. How do I left-click a trackpad so it does the job? Do I need to change any settings or what?

  • Designerd does not generate Order BY code for Sort Order on a lookup tabel column.

    I am setting the Sort Order on a column which is based on a lookup table. When generate the the module, designer does not generate the code for the Sort Order that I set on the lookup table column. Is there a work around for this problem or is there

  • Hotspot VM crash on Solaris

    Hello everyone, I am seeing this error when running an app on Solaris. HotSpot Virtual Machine Error, Internal Error Please report this error at http://java.sun.com/cgi-bin/bugreport.cgi Error ID: 53414645504F494E540E4350500366 01 Problematic Thread:

  • Differencial backup, Log backup and restore

    Hi Team, A scenario: If I have backups as below. FullBackup1 LogBackup1 LogBackup2 DiffBackup1 LogBackup3 LogBackup4 If our database crash after logBackup4, Is it really required the DiffBackup1 to recover the db? or will it be possible to recover us