JPanel, jScrollPane, jLists and removing components

I have a method that when a textfield gets the focus, I want my jScrollPane to clear out. I don't want to removeAll, but I only want to remove the 2 jLists: listCheckBox and listDescription.
What I have below doesn't visually remove my jLists.
What can I do?
jScrollPane1.remove(listCheckBox);
jScrollPane1.remove(listDescription);
jPanel1.revalidate();
jPanel1.repaint();

This is the entire code. It should compile. I don't know if this counts as a SSCCE or not. I am using the JDK 1.5 & Swing Layout Extensions 1.0 libraries. With this code, I have my jScrollPane to clear out correctly. Now, the mouselistener only works every other time the find button is clicked.
import java.awt.Component;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Vector;
import javax.swing.JCheckBox;
import javax.swing.JList;
import javax.swing.ListCellRenderer;
import javax.swing.ListSelectionModel;
import javax.swing.UIManager;
* NewJFrame.java
* Created on November 3, 2006, 11:17 AM
* @author  a1025667
public class NewJFrame extends javax.swing.JFrame {
    /** Creates new form NewJFrame */
    public NewJFrame() {
        initComponents();
        this.jScrollPane1.requestFocus();
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">                         
    private void initComponents() {
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextField1 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        jTextField1.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                jTextField1FocusGained(evt);
        jButton1.setText("jButton1");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .add(131, 131, 131)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jPanel1Layout.createSequentialGroup()
                        .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 188, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(14, 14, 14)
                        .add(jButton1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 87, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 306, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(166, Short.MAX_VALUE))
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .add(25, 25, 25)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jButton1))
                .add(63, 63, 63)
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 147, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(117, Short.MAX_VALUE))
        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        pack();
    }// </editor-fold>                       
    private void jTextField1FocusGained(java.awt.event.FocusEvent evt) {                                       
// TODO add your handling code here:
        Vector listData = new Vector();
        JList emptylistCheckBox = new JList();
        JList emptylistDescription = new JList();
        emptylistCheckBox.setListData(listData);
        emptylistDescription.setListData(listData);
        jScrollPane1.setRowHeaderView(emptylistCheckBox);
        jScrollPane1.setViewportView(emptylistDescription);
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
// TODO add your handling code here:
        Vector listData = new Vector();
        listData.add("row1");
        listData.add("row2");
        listData.add("row3");
        listCheckBox.setListData(buildCheckBoxItems(listData.size()));
        listDescription.setListData(listData);
        listCheckBox.setCellRenderer(new CheckBoxRenderer());
        listCheckBox.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        listCheckBox.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent me) {
                int selectedIndex = listCheckBox.locationToIndex(me.getPoint());
                if (selectedIndex < 0)
                    return;
                CheckBoxItem item = (CheckBoxItem)listCheckBox.getModel().getElementAt(selectedIndex);
                item.setChecked(!item.isChecked());
                listDescription.setSelectedIndex(selectedIndex);
                listCheckBox.repaint();
        listDescription.setFixedCellHeight(20);
        listCheckBox.setFixedCellHeight(listDescription.getFixedCellHeight());
        jScrollPane1.setRowHeaderView(listCheckBox);
        jScrollPane1.setViewportView(listDescription);
        jScrollPane1.revalidate();
        jScrollPane1.repaint();
     * @param args the command line arguments
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NewJFrame().setVisible(true);
    private CheckBoxItem[] buildCheckBoxItems(int totalItems) {
        CheckBoxItem[] checkboxItems = new CheckBoxItem[totalItems];
        for (int counter=0;counter<totalItems;counter++) {
            checkboxItems[counter] = new CheckBoxItem();
        return checkboxItems;
    class CheckBoxItem {
        private boolean isChecked;
        public CheckBoxItem() {
            isChecked = false;
        public boolean isChecked() {
            return isChecked;
        public void setChecked(boolean value) {
            isChecked = value;
    class CheckBoxRenderer extends JCheckBox implements ListCellRenderer {
        public CheckBoxRenderer() {
            setBackground(UIManager.getColor("List.textBackground"));
            setForeground(UIManager.getColor("List.textForeground"));
        public Component getListCellRendererComponent(JList listBox, Object obj, int currentindex,
                boolean isChecked, boolean hasFocus) {
            setSelected(((CheckBoxItem)obj).isChecked());
            return this;
    // Variables declaration - do not modify                    
    private javax.swing.JButton jButton1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration                  
    public  JList listCheckBox = new JList();
    public  JList listDescription = new JList();
}

Similar Messages

  • Adding and Removing Components to/from a jPanel

    Hello,
    I am searching for a way to have a jButton create a remove and create some jComboBoxes, jLabels, and jButtons. I don't know how I could do this. I have some screenshots from NetBeans IDE to help illustrate my problem.
    I want the Add Shift button in here...
    [IMG]http://i271.photobucket.com/albums/jj132/Dunkmaster1992/javahelp1.jpg[/IMG]To do this...
    <a href="http://s271.photobucket.com/albums/jj132/Dunkmaster1992/?action=view&current=javahelp2.jpg" target="_blank"><img src="http://i271.photobucket.com/albums/jj132/Dunkmaster1992/javahelp2.jpg" border="0" alt="Photobucket"></a>And obviously I would like the remove buttons to remove a shift when clicked.
    Well, thanks for any help. I think this is pretty advanced if it's possible. I'm pretty sure I could manage doing this a slightly different way, but it would not look as pretty and I would have to limit the amount of shifts possible. I would otherwise approach this by doing this:
    <a href="http://s271.photobucket.com/albums/jj132/Dunkmaster1992/?action=view&current=javahelp3.jpg" target="_blank"><img src="http://i271.photobucket.com/albums/jj132/Dunkmaster1992/javahelp3.jpg" border="0" alt="Photobucket"></a>It just isn't as professional. I would do it by just making the components visible and not visible with the button clicks. And changing the attributes of the components is easy. But I would also be limited to however many shifts I placed originally on the jPanel.
    Duncan Calvert
    [email protected]
    Please, if it's not too much trouble, give me an e-mail when you respond.
    Edited by: dw.calvert on Jul 22, 2010 2:36 AM
    Edited by: dw.calvert on Jul 22, 2010 2:37 AM
    Edited by: dw.calvert on Jul 22, 2010 2:39 AM

    dw.calvert wrote:
    I'm not sure why it's a bad thing to post a question on two different forums. It only means more views on the question.Yes, and many people wasting their time answering your question. There is nothing wrong with it as long as you mention that you have done so and provide reference to the other thread.
    >
    And I included my e-mail so that someone could ensure that I read their response. So, if someone replies a month from now, I will know about it, and won't have to check this forum everyday for the rest of my life.So set a watch on this thread and you will get an email from the forums. The spam search engines are happy for your posted email address, however.
    And nowadays it would take less time to send a quick e-mail notification than to respond to this question.Thereby excluding everyone else that may have the same problem. Keeping the conversation here allows them to also get helped (if they bother to search, although most people don't seem to realise what Google and forum search functions are for).
    >
    I'm sorry if I'm not used to this forum, or it's traditions, but a picture is worth 1000 words and I always try to be efficient.As long as it is only "efficient" from your point of view. As it is more "effecient" for others to both keep the conversation here and to notify others of the cross-post.

  • Jscrollpane, jlist and forte

    hi, i putted a jlist into a jscrollpane into my form, but i can see all the elements into the jlist because scrollbars don't appear.
    i already saw some code into this forum, but i neet to know how to do it managing the properties of FORTE, not writing any code.
    can anyone help me?
    thanks
    sandro

    Follow this snippet
    JList list = new JList(model);
    list.setVisibleRowCount(4);
    The rowcount value should be less than the number of items in the list.
    For example,
    the number of items be 10 and visible row count is 4, then the scroll bar will automatically appear.
    Hope this will help you a lot

  • 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?

  • Problem with a JList and JScrollpane

    Hi,
    Im having a problem with horizontal scrolling in that I have a simple JList inside a panel and a text box below where the user enters text. Now the text box has a width of 15, but the user can type as many characters as they want..Now the Jlist only displays 15 characters, but the horizontal scroller does not come up, instead just displays for example abcdefghijkl... (the three dots in the end)..
    Isnt my scroller supposed to be automatically scrolling when there is more on the line then the screen displays?? I already have this so far..
    scroller = new JScrollPane(dataList, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);thanks!

    Try the following code:
    package sample;
    import java.awt.*;
    import javax.swing.*;
    public class MyDialog extends JDialog {
      public static void main( String[] args) {
        new MyDialog().setVisible(true);
      JPanel contentPanel = new JPanel();
      JScrollPane scrollPane = new JScrollPane();
      JList list = new JList( new Object[] {"abcdefghijklmnopqrstuvwxyz", "123456789012345678901234567890"});
      public MyDialog() {
        contentPanel.setLayout(new BorderLayout());
        getContentPane().add(contentPanel);
        contentPanel.add(scrollPane, BorderLayout.CENTER);
        scrollPane.getViewport().add(list, null);   
        setSize( 100,100);
        setLocation( 100,100);
    }Michael

  • I did everything lllaass suggested and removed most of the itunes related components, but when I tried to remove itunes, I got the message, "The feature you are trying to use is on a network resource that is unavailable" so I was not able to uninstall it.

    I did everything lllaass suggested and removed most of the itunes related components, but when I tried to remove itunes, I got the message, "The feature you are trying to use is on a network resource that is unavailable" so I was not able to uninstall it.

    (1) Download the Windows Installer CleanUp utility installer file (msicuu2.exe) from the following Major Geeks page (use one of the links under the "DOWNLOAD LOCATIONS" thingy on the Major Geeks page).
    http://majorgeeks.com/download.php?det=4459
    Here's a screenshot showing the particular links on the page that you should be clicking:
    After clicking one of the circled links, you should be taken to another page, and after a few seconds you should see a download dialog appear for the msicuu2.exe file. Here's a screenshot of what it looks like for me in Firefox:
    Choose to Save the file. If the dialog box does not appear for you, click the link on the page that says "CLICK HERE IF IT DOES NOT". Here's a screenshot of the page with the relevant link circled:
    When the dialog appears, choose to save the file.
    (2) Go to the Downloads area for your Web browser. Doubleclick the msicuu2.exe file and follow the prompts to install the Windows Installer CleanUp utility. (If you're on a Windows Vista or Windows 7 system and you get a Code 800A0046 error message when doubleclicking the msicuu2.exe file, try instead right-clicking on the msicuu2.exe file and selecting "Run as administrator".)
    (3) In your Start menu click All Programs and then click Windows Install Clean Up. The Windows Installer CleanUp utility window appears, listing software that is currently installed on your computer.
    (4) In the list of programs that appears in CleanUp, select any iTunes entries and click "Remove", as per the following screenshot:
    (5) Quit out of CleanUp, restart the PC and try another iTunes install. Does it go through properly this time?

  • On my MacBook with Lion Safari does start, does not react immediately after trying to open it. Installing a new Safari does not help. Removing parts of Safari in the Library did not help. Where can I find and remove all components (LastSession ...)?

    How can I reset Safari with all components? On my MacBook with Lion, Safari does not start, does not react immediately after trying to open it. Installing a new Safari does not help. Removing parts of Safari in the Library does not help. Where can I find and remove all components as LastSession and TopSites?

    The only way to reinstall Safari on a Mac running v10.7 Lion is to restore OS X using OS X Recovery
    Instead of restoring OS X in order to reinstall Safari, try troubleshooting extensions.
    From the Safari menu bar click Safari > Preferences then select the Extensions tab. Turn that OFF, quit and relaunch Safari to test.
    If that helped, turn one extension on then quit and relaunch Safari to test until you find the incompatible extension then click uninstall.
    If it's not an extensions issue, try troubleshooting third party plug-ins.
    Back to Safari > Preferences. This time select the Security tab. Deselect:  Allow plug-ins. Quit and relaunch Safari to test.
    If that made a difference, instructions for troubleshooting plugins here.
    If it's not an extension or plug-in issue, delete the cache.
    Open a Finder window. From the Finder menu bar click Go > Go to Folder
    Type or copy paste the following
    ~/Library/Caches/com.apple.Safari/Cache.db
    Click Go then move the Cache.db file to the Trash.
    Quit and relaunch Safari to test.

  • Quickest way to clone a JPanel and its components?

    Is there a quick method to clone a JPanel and its components?

    This has been tried before and not work.
    JVM reports errors :
    clone() has protected access in java.lang.Object.

  • JList and ListModel, can anyone explain the basics?

    Hi
    I have an object A containing a Vector X of objects. I want to display them in a JList. I could always use DefaultListModel and copy the items of the Vector X into the default list model using addElement. But that would create a copy of the information in vector X. That is exactly why one should use a custom list model to ensure that the data is in sync with the GUI .
    I want to add and remove items from the JList, and simultaious add and remove items from the Vector X. Can anyone proviede a samll example of how to do this.
    I have tryed myselfe, but I can not get the JList updated with the changes of the listmodel. I have read the documentation about ListDataListener, but I just don't get it. A small example would realy be appreciated!
    // Mattias

    Yse I have read the tutorial. But I don't understand it.
    Here is a small example program. Can anyone change the code so the list is updated with the canges that obviously take place (as one can see by pressing the "Dump button")
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.util.*;
    class ListTest extends JFrame implements ActionListener , ListDataListener {
        JList list;
        MyListModel myListModel;
        MyDataObject myDataObject;
        ListTest() {
            JPanel p = new JPanel();
            myDataObject = new MyDataObject();
            myListModel = new MyListModel(myDataObject.x);
            list = new JList(myListModel);
            myListModel.addListDataListener(this);
            JScrollPane listScrollPane = new JScrollPane(list);
            listScrollPane.setPreferredSize(new Dimension(200, 100));
            p.add(listScrollPane);
            JButton b1 = new JButton("Add");
            b1.addActionListener(this);
            p.add(b1);
            JButton b2 = new JButton("Remove");
            b2.addActionListener(this);
            p.add(b2);
            JButton b3 = new JButton("Dump");
            b3.addActionListener(this);
            p.add(b3);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            getContentPane().add(p);
            pack();
            show();
        public void actionPerformed(ActionEvent e) {
            if (e.getActionCommand().equals("Add")) {
                myListModel.addElement(""+ (1+myListModel.getSize()) );
                System.out.println("Added a row to the list");
            if (e.getActionCommand().equals("Remove")) {
                if (myListModel.getSize()>0) {
                    myListModel.remove(myListModel.getSize()-1);
                    System.out.println("Removed last element from the list");
                else {
                    System.out.println("No more elements to remove");
            if (e.getActionCommand().equals("Dump")) {
                System.out.println("\n\nData in the list model:");
                for (int i=0; i<myListModel.getSize() ; i++) {
                    System.out.println(myListModel.getElementAt(i));
                System.out.println("That should be the same as the vector x in the object myDataObject  :");
                for (int i=0; i<myListModel.getSize() ; i++) {
                    System.out.println(myDataObject.x.get(i));
        public void contentsChanged(ListDataEvent e) {
            System.out.println("contentsChanged");
        public void intervalAdded(ListDataEvent e) {
            System.out.println("intervalAdded");
        public void intervalRemoved(ListDataEvent e) {
            System.out.println("intervalRemoved");
        public static void main(String args[]) {
            new ListTest();
    class MyDataObject {
        Vector x;
        MyDataObject() {
            x=new Vector();
            x.addElement("1");
            x.addElement("2");
    class MyListModel extends AbstractListModel {
        Vector v;
        MyListModel(Vector v) {
            this.v=v;
        public void addElement(Object o) {
            v.addElement(o);
        public Object remove(int index) {
            return v.remove(index);
        public Object getElementAt(int index) {
            return v.get(index);
        public int getSize() {
            return v.size();
    </pre>

  • JScrollPane, JList, Resizing - How does it work?

    Hello NG,
    I have the following situation:
    3 JScrollpanes with 3 JLists to display. 2 Scrollpanes (on the right, 2. and 3.) are in a JPanel with GridBagLayout. This JPanel and the 3rd JScrollpane (on the left, 1.) are in another JPanel also with GridBagLayout. All components have a gridBagConstraints.fill = BOTH setting for resizing. The JLists will be filled from another Thread different from the EventDispatcherThread.
    The Problem:
    The JFrame with the components above will be displayed on the screen. Then the other thread fills the JList of JScrollpane(1), then the two other JScrollpanes (2 and 3). After that, a resizing occurs according to the gridBagConstraints.fill constraint to fill the space between the components. So, the 3 JScrollpanes change their size, it seem to the observer that this resizing occurs without intention.
    Is there a way to prevent this risizing? How does this resizing mechanism exactly works? Who fires which event? Does anybody knows where to find a good description of it?
    So far, I know it starts with the revalidate()-method in the JLists after changing the content of the lists. revalidate() adds the component to the RepaintManger invalidation queue for repainting. But who calls revalidate()? What will happen if the revalidate()-method will be overwritten to do nothing?
    Bye
    Raoul

    You gotta throw use a bone here... How does what work? More info please.

  • JTextArea as ListCellRenderer in JPanel with JSplitPane and text wrapping

    Hi.
    I have problem with JTextArea text wrapping. The JTextArea is used as ListCellRenderer in JList and it has set:
    textArea.setLineWrap(true);
    textArea.setWrapStyleWord(true);I can dynamically add new Notes, modify and remove notes on JList. The capacity of the Text is various so the size of cells is various.
    The JList is in JScrollPane configured like this:
    JList notesList = new JList();
    JScrollPane scrollPane = new JScrollPane(
                        JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                        JScrollPane.HORIZONTAL_SCROLLBAR_NEVER
    scrollPane.setViewportView(notesList);This scrollPane is put on the left component in the JSplitPane.
    When I put one note with any capacity I want, word wrapping works great even if I move the splitter. The size of cells in JList changes as I want. When JList has more width the cells have less height, when JList has less width the cells height grows because of text wrapping.
    Problem
    Sometimes and I don't know when and why the cells size is fixed.
    I put new note to the list, JList lays the cell, calculate the size and disply it. It is good but when I move splitter the size of the cell is the same. It seems that during moving the splitter the JTextArea doesn't calculate their size.
    I would like in every cell in JList to see whole text wrapped. When I make more width by slider I would like to see whole text with less number of rows. When I make less width with the slider I want to see whole text wrapped and more higher cells.
    Can someone help me where to looking for ideas.

    Hi.
    I have problem with JTextArea text wrapping. The JTextArea is used as ListCellRenderer in JList and it has set:
    textArea.setLineWrap(true);
    textArea.setWrapStyleWord(true);I can dynamically add new Notes, modify and remove notes on JList. The capacity of the Text is various so the size of cells is various.
    The JList is in JScrollPane configured like this:
    JList notesList = new JList();
    JScrollPane scrollPane = new JScrollPane(
                        JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                        JScrollPane.HORIZONTAL_SCROLLBAR_NEVER
    scrollPane.setViewportView(notesList);This scrollPane is put on the left component in the JSplitPane.
    When I put one note with any capacity I want, word wrapping works great even if I move the splitter. The size of cells in JList changes as I want. When JList has more width the cells have less height, when JList has less width the cells height grows because of text wrapping.
    Problem
    Sometimes and I don't know when and why the cells size is fixed.
    I put new note to the list, JList lays the cell, calculate the size and disply it. It is good but when I move splitter the size of the cell is the same. It seems that during moving the splitter the JTextArea doesn't calculate their size.
    I would like in every cell in JList to see whole text wrapped. When I make more width by slider I would like to see whole text with less number of rows. When I make less width with the slider I want to see whole text wrapped and more higher cells.
    Can someone help me where to looking for ideas.

  • Problem removing components not a problem of revalidate

    ello everybody i'm trying to make a chart made of buttons in which every button press removes the pressed button, adds a TextField saves the string that was entered and than adding it as a label of a new Button instead of the one removed. the problem with the code is when i a button it removes the last button that was added
    from the bottom right corner
    import javax.swing.JButton;
    import java.awt.GridLayout;
    import java.awt.TextField;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import javax.swing.JFrame;
    public class SudokoChart{
                    private JFrame frm;
                    private JButton btn;
         private TextField txt;
         private String label = null;
         private static final int DIMENSION = 9;
         private GridLayout chart;
      public class InnerHandler implements ActionListener{
            public void actionPerformed(ActionEvent e){
                    if (e.getSource() instanceof JButton) {
                         btn = (JButton)e.getSource();
                                                         frm.list();
                        //chart.removeLayoutComponent(btn);
                        frm.remove(btn);
                        frm.validate();
                        txt  = new TextField();
                         frm.add(txt);
                         frm.pack();
                         frm.setVisible(true);
                         txt.addKeyListener(new KeyListener(){
                              public void keyPressed(KeyEvent e) {
                                   if(e.getKeyChar() == KeyEvent.VK_ENTER){
                                   label  = txt.getText();
                                   txt.setText("");
                                   frm.remove(txt);
                                   frm.validate();
                                   btn.setText(label);
                                   frm.add(btn);
                                   frm.validate();
                                   frm.pack();
                                   frm.setVisible(true);
                                   public void keyReleased(KeyEvent arg0) {}
                                   public void keyTyped(KeyEvent arg0) {}
         public SudokoChart(){
              frm = new JFrame("Sudoko Solver");
              chart = new GridLayout(DIMENSION,DIMENSION);
              frm.setLayout(chart);
         public void launchFrame(){
                 boolean cont = true;
           for(int row = 0; row < DIMENSION; row++){
                for(int col = 0; col < DIMENSION; col++){
                     //compare between the action button point to  array button point (not related to
                     //the code)
                     btn = new JButton("Push to Enter");
                     //       butpoint[index] = btn; 
                    cont = frm.add(btn).contains(btn.getLocation());
                    System.out.println(cont);
                    //butpoint[index].setLocation(btn.getLocation());
                    // System.out.println(butpoint[index].getLocation());
                     //System.out.println(btn.getLocation());
                     //index++;
                    //  butpoint[index] = btn;
                     //System.out.println(myButton.objCnt);
                     //frm.add(btn,chart,myButton.objCnt);
                     frm.pack();
                     frm.setVisible(true);
                     btn.addActionListener(new InnerHandler());                
         public static void main(String args[]){
              SudokoChart sc = new SudokoChart();
              sc.launchFrame();

    It's an interesting way to go about this, but I'm not sure that I'd want to do it this way. Anyway, one way to possibly solve this problem is to use a 2D grid of JComponent that holds the JButtons, and then swap out your selected JButton for a JTextField, then remove all the JComponents from the container, and then re-add them using your GridLayout and your 2D array to add the components in the correct order.
    Another way to do the same thing is to use a grid of a class that holds a JPanel that uses CardLayout that displays a JButton and on button press swaps this for a JTextField.
    There are probably many ways to do what you want, and I'm not saying that either of my suggestions are best.
    Edit: by the way, don't mix Swing and AWT components in the same app. Your TextFields should be JTextFields.
    Edited by: Encephalopathic on Oct 16, 2009 2:39 PM

  • Problem removing components from JLayeredPane

    Hi all,
    I have a problem showing and hiding components on a JLayeredPane. It goes Something like this:
    In my application I have a button. When this button is pressed I use getLayeredPane to get the frames layered pane. I then add a JPanel containing a number of labels and buttons onto that layered pane on the Popup layer. The panel displays and funcitons correctly.
    The problem comes when I try to remove the panel from the layered pane. The panel does not dissappear and I am no longer able to click on anything else in the frame!
    If anyone has any ideas how to get around this or what the problem might be I'd be very greatful to hear it. Sample code follows:
          * Called when the button on the frame is pressed:
          * @param e
         public void actionPerformed(ActionEvent e)
                    JLayeredPane mLayredPane = getLayeredPane();
              int x = 0, y = 0;
              Container c = this;
              while (true)
                   c = c.getParent();
                   if (c != null)
                        x += c.getLocation().x;
                        y += c.getLocation().y;
                        if (c instanceof JRootPane)
                             break;
                   else
                        break;
              mPanel.setBounds(x, y, 235, 200);
              mLayredPane.add(mPanel, JLayeredPane.POPUP_LAYER);
    //And when a listener fires from the panel I use
    mLayredPane.remove(mPanel);
    //To remove it from the layered pane and in theory return the
    //app to the state it was before the panel was displayedThanks again...

    The problem is you only removed it within the program, without actually removing it from the display. If that makes any sense, or whether thats your problem at all.
    If you are only using this line.
    mLayredPane.remove(mPanel);
    I think if you tell it to repaint and revalidate it should work, though i have never used LayeredPane.
    mLayredPane.repaint();
    mLayredPane.revalidate();

  • Arrows in a text field / Common scroll for a jlist and a graphic field

    I am developing a software which requires me to dynamically add arrows from one list entry to another(depending on the users respone) in a jlist.
    Is there any method to do that directly or by means of two parralel fields(one for the list and other for the arrows) controlled by a single scroll????
    Cheers!!!

    I don't understand the question, but read the Swing tutorial on "How to Use Lists" which shows the proper way to add and remove items from a JList:
    http://java.sun.com/docs/books/tutorial/uiswing/components/list.html
    If you need further help then you need to create a "Short, Self Contained, Compilable and Executable, Example Program (SSCCE)", that demonstrates the incorrect behaviour.
    http://homepage1.nifty.com/algafield/sscce.html
    Don't forget to use the "Code Formatting Tags", so the posted code retains its original formatting.
    http://forum.java.sun.com/help.jspa?sec=formatting

  • JTree, JList and file selection

    I have a file selection JPanel that I'm creating that has a JTree on the left representing folders and a JList on the right that should have the files and folders listed to be able to select. I have two problems at this point. First, and more important, when a folder is selected, the JList doesn't update to the files in the new folder and I don't see what's keeping it from working. Second, when clicking on a folder in the JTree, it drops the folder to the end of the list and then lets you expand it to the other folders, also it shows the whole folder path instead of just the folder name.
    This is still my first venture into JTrees and JLists and I'm still really new at JPanel and anything GUI, so my code may not make the most sense, but right now I'm just trying to get it to work.
    Thank you.
    public class FileSelection extends JFrame{
              Container gcp = getContentPane();
              File dir=new File("c:/");
              private JList fileList;
              JTree tree;
              DefaultMutableTreeNode folders;
              String filePath,selectedFile="", path;
              TreePath selPath;
              FileListPanel fileLP;
              FolderListPanel folderLP;
              JScrollPane listScroller;
              public FileSelection(String name){
                   super(name);
                   gcp.setLayout(new BorderLayout());
                   fileLP = new FileListPanel();
                   folderLP = new FolderListPanel();
                   gcp.add(fileLP, BorderLayout.CENTER);
                   gcp.add(folderLP, BorderLayout.WEST);
                   setVisible(true);
              private class FileListPanel extends JPanel implements ActionListener{
                   public FileListPanel(){
                        final JButton selectItem = new JButton("Select");
                        final JButton cancel = new JButton("Cancel");
                        final JButton changeDir = new JButton("Change Directory");
                        //add buttons
                        add(selectItem);
                        add(changeDir);
                        add(cancel);
                        //instantiate buttons
                        selectItem.setActionCommand("SelectItem");
                        selectItem.addActionListener(this);
                        changeDir.setActionCommand("ChangeDirectory");
                        changeDir.addActionListener(this);
                        cancel.setActionCommand("Cancel");
                        cancel.addActionListener(this);
                        final String[] fileArr=dir.list();
                        fileList = new JList(fileArr);
                        fileList.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
                        fileList.setLayoutOrientation(JList.VERTICAL_WRAP);
                        fileList.setVisible(true);
                        fileList.setVisibleRowCount(-1);
                        fileList.setSelectedIndex(0);
                        listScroller = new JScrollPane(fileList);
                        listScroller.setPreferredSize(new Dimension(200,200));
                        listScroller.setAlignmentX(LEFT_ALIGNMENT);
                        add(listScroller);
                        MouseListener mouseListener = new MouseAdapter(){
                             public void mouseClicked(MouseEvent e){
                                  if(e.getClickCount()==2){
                                       int itemIndex = fileList.locationToIndex(e.getPoint());
                                       currFile=fileArr[itemIndex];
                                       dispose();
                        fileList.addMouseListener(mouseListener);
                   public void actionPerformed(ActionEvent e){
                        if("SelectItem".equals(e.getActionCommand())){
                             currFile=(String)fileList.getSelectedValue();
                             dispose();
                        }else{
                        if("Cancel".equals(e.getActionCommand())){
                             dispose();
                        }else{
                        if("ChangeDirectory".equals(e.getActionCommand())){
                             ChangeDir cd = new ChangeDir("Select Directory");
                             cd.setSize(new Dimension(300,275));
                             cd.setLocation(500, 225);
              private class FolderListPanel extends JPanel{
                   public FolderListPanel(){
                        String[] files = dir.list();
                        DefaultMutableTreeNode topNode = new DefaultMutableTreeNode("Files");
                        folders = new DefaultMutableTreeNode("C:/");
                        topNode.add(folders);
                        folders = getFolders(dir, folders);
                        tree = new JTree(topNode);
                        tree.setVisible(true);
                        JScrollPane treeScroller = new JScrollPane(tree);
                        treeScroller.setPreferredSize(new Dimension(500,233));
                        treeScroller.setAlignmentX(LEFT_ALIGNMENT);
                        add(treeScroller);
                        MouseListener mouseListener = new MouseAdapter(){
                             public void mouseClicked(MouseEvent e){
                                  try{
                                       if(e.getClickCount()==1){
                                            selPath = tree.getPathForLocation(e.getX(), e.getY());
                                            path=selPath.getLastPathComponent().toString();
                                            dir = new File(path);
                                            TreeNode tn=findNode(folders, path);                    
                                            if(tn!=null){
                                                 folders.add((MutableTreeNode) getTreeNode(dir, (DefaultMutableTreeNode) tn));
                                            tree.updateUI();
                                            final String[] fileArr=dir.list();
                                            fileList = new JList(fileArr);
                                            fileList.updateUI();
                                            listScroller.updateUI();
                                            fileLP = new FileListPanel();
                                  }catch(NullPointerException npe){
                        tree.addMouseListener(mouseListener);
                   public DefaultMutableTreeNode getFolders(File dir, DefaultMutableTreeNode folders){
                        File[] folderList = dir.listFiles();
                        int check=0;
                        for(int x=0;x<folderList.length;x++){
                             if(folderList[x].isDirectory()){
                                  folders.add(new DefaultMutableTreeNode(folderList[x]));               
                        return folders;
                   public TreeNode getTreeNode(File dir, DefaultMutableTreeNode folders){
                        File[] folderList = dir.listFiles();
                        int check=0;
                        for(int x=0;x<folderList.length;x++){
                             if(folderList[x].isDirectory()){
                                  folders.add(new DefaultMutableTreeNode(folderList[x]));               
                        return folders;
                   public TreeNode findNode(DefaultMutableTreeNode folders, String node){
                        Enumeration children = folders.postorderEnumeration();
                        Object current;
                        while(children.hasMoreElements()){
                             current = children.nextElement();
                             if(current.toString().equals(node)){
                                  return (TreeNode)current;
                        return null;
         }

    Wow! I changed the FolderListPanel's mouseListener to:
    tree.addTreeSelectionListener(new TreeSelectionListener(){
                             public void valueChanged(TreeSelectionEvent tse){
                                  DefaultMutableTreeNode node = (DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
                                  if(node==null)return;
                                  Object nodeInfo = node.getUserObject();
                                  dir=new File(nodeInfo.toString());
                                  folders.add((MutableTreeNode) getFolders(dir,node));
                        });and it's amazing how much better the tree is!!! But I still don't have the JList part working. I changed the JList and the FileListPanel to public from private, but that didn't change anything.

Maybe you are looking for

  • I have updated to a new version of firefox and lost all of my 'history' i need it back.. I had so much info there and now its gone.. please help me

    a update version of firefox came up.. tellingme to update to new version of firefox. So I did.. it loaded the current version. I always have my 'history' showing. (in the VIEW title on top of screen I go to SIDEBAR, and have history showing. It is on

  • Why can't I use my credit card in OVI store?

    After buying several apps in the Ovi Store using my credit card I was really surprised that Ovi Store does no longer accept my credit card because I'm not living in the US! (I'm requested to fill in a US address otherwise I cannot proceed.) **bleep**

  • What's happening to ML

    All of a sudden when I start ip my iMac the  Dock icons do not show what they are, the magnification does not woek, the cursor changes back to an arerow insted of the hand it used to be and sll sorts of other things are happening every time I start u

  • Accessing dictionary tables from dynpro?

    Hi all As far as i know, there are 4 approches to access dictionary tables from webdynpro. -entity bean -sqlj -jdbc what are the advantages and disadvantages for all above? and which one to go for?

  • Wireless options anyone?

    Hey guys, I've moved my desk to another room that has no internet or network access. What are my options for the Mac Mini now besides the Airport/Bluetooth upgrade kit? Currently, I have a PC running WindowsXP Pro that has a wireless Dlink G adapter