在Swing Java中向JList添加元素

在Swing Java中向JList添加元素,java,swing,jlist,Java,Swing,Jlist,我有一个在点击按钮时执行的函数。假设有一个循环将1到10添加到JList。我将该数据添加到DefaultListModel。它工作得很好,数字也会被添加。然后我在循环中添加了一个线程。sleep(1000)。但结果是不同的。我想每秒添加1个元素。但现在它等待10秒,并在第10秒结束时将所有1到10相加。我哪里错了 List processList = listNumbers.getSelectedValuesList(); DefaultListModel resultList = new De

我有一个在点击按钮时执行的函数。假设有一个循环将1到10添加到
JList
。我将该数据添加到
DefaultListModel
。它工作得很好,数字也会被添加。然后我在循环中添加了一个
线程。sleep(1000)
。但结果是不同的。我想每秒添加1个元素。但现在它等待10秒,并在第10秒结束时将所有1到10相加。我哪里错了

List processList = listNumbers.getSelectedValuesList();
DefaultListModel resultList = new DefaultListModel();
listResult.setModel(resultList);

for (int i = 0; i < processList.size(); i++) {
    resultList.addElement(String.valueOf(i));
    try {
        Thread.sleep(1000);
    }
    catch (InterruptedException ex) {
    }
}
List processList=listNumbers.getSelectedValuesList();
DefaultListModel resultList=新的DefaultListModel();
setModel(resultList);
对于(int i=0;i
您应该在一个单独的线程中更新列表,否则最终会阻塞事件调度线程

请尝试以下操作:

final DefaultListModel model = new DefaultListModel();
final JList list = new JList(model);

//another thread to update the model
final Thread updater = new Thread() {
    /* (non-Javadoc)
     * @see java.lang.Thread#run()
     */
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            model.addElement(i);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
};
updater.start();
final DefaultListModel=new DefaultListModel();
最终JList列表=新JList(型号);
//另一个线程更新模型
最终线程更新程序=新线程(){
/*(非Javadoc)
*@see java.lang.Thread#run()
*/
@凌驾
公开募捐{
对于(int i=0;i<10;i++){
模型.补充件(i);
试一试{
睡眠(1000);
}捕捉(中断异常e){
抛出新的运行时异常(e);
}
}
}
};
updater.start();

eventdispashtread
期间,不要使用,实际上不要使用
Thread.sleep(int)
,因为sleep锁定了当前
Thread
,在这种情况下,
eventdispashtread
,将非预期输出到GUI,更多信息

如果需要处理某些内容,则将项目包装到
Runneble#Thread
,将GUI输出包装到
invokeLater
,或者最好的方法是使用

先编辑。示例如何使用Thread.sleep(int)以编程方式阻止EDT,因为Otherwise无法处理预期的GUI输出(代码非常冗长,因为我想编写代码)

import java.awt.*;
导入java.awt.event.*;
导入javax.swing.*;
公共类ShakingButtonDemo实现Runnable{
私人按钮;
私人JRadioButton radioWholeButton;
仅限私人JRadioButton radioTextOnly;
公共静态void main(字符串[]args)引发异常{
调用器(新的ShakingButtonDemo());
}
@凌驾
公开募捐{
radioWholeButton=新的JRadioButton(“整个按钮”);
radioTextOnly=新的JRadioButton(“仅按钮文本”);
radioWholeButton.setSelected(真);
ButtonGroup bg=新建ButtonGroup();
背景添加(无线全屏按钮);
背景添加(仅限RadioText);
按钮=新的JButton(“用此按钮摇动”);
addActionListener(新建ActionListener()){
@凌驾
已执行的公共无效操作(操作事件e){
shakeButton(radioWholeButton.isSelected());
}
});
JPanel p1=新的JPanel();
p1.设置顺序(BorderFactory.createTitledBorder(“抖动选项”);
p1.设置布局(新网格布局(0,1));
p1.添加(radioWholeButton);
p1.添加(仅限无线文本);
JPanel p2=新的JPanel();
p2.设置布局(新网格布局(0,1));
p2.添加(按钮);
JFrame=新JFrame();
frame.setTitle(“抖动按钮演示”);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
框架。添加(p1,边界布局。北);
框架。添加(p2,边界布局。南部);
框架设置尺寸(240160);
frame.setLocationRelativeTo(空);
frame.setVisible(true);
}
私有void shakeButton(最终布尔shakeWholeButton){
最终点=button.getLocation();
最终插入页边距=button.getMargin();
最终整数延迟=75;
Runnable r=新的Runnable(){
@凌驾
公开募捐{
对于(int i=0;i<30;i++){
试一试{
如果(晃动整个按钮){
移动按钮(新点(点x+5,点y));
睡眠(延迟);
移动按钮(点);
睡眠(延迟);
移动按钮(新点(点x-5,点y));
睡眠(延迟);
移动按钮(点);
睡眠(延迟);
}else{//仅限文本
setButtonMargin(新插图(margin.top、margin.left+3、margin.bottom、margin.right-2));
睡眠(延迟);
setButtonMargin(边缘);
睡眠(延迟);
setButtonMargin(新插图(margin.top,margin.left-2,margin.bottom,margin.right+3));
睡眠(延迟);
setButtonMargin(边缘);
睡眠(延迟);
}
}捕获(中断异常例外){
例如printStackTrace();
}
}
}
};
螺纹t=新螺纹(r);
t、 start();
}
专用无效移动按钮(终点p){
SwingUtilities.invokeLater(新的Runnable(){
@凌驾
公开募捐{
按钮设置位置(p);
}
});
}
专用空白收进边距(最终插入边距){
SwingUtilities.invokeLater(新的Runnable(){
@凌驾
公开募捐{
按钮。设置页边距(页边距);
}
});
}
}
编辑第二。用@camickr的善良的hepl(看起来像similai
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ShakingButtonDemo implements Runnable {

    private JButton button;
    private JRadioButton radioWholeButton;
    private JRadioButton radioTextOnly;

    public static void main(String[] args) throws Exception {
        SwingUtilities.invokeLater(new ShakingButtonDemo());
    }

    @Override
    public void run() {
        radioWholeButton = new JRadioButton("The whole button");
        radioTextOnly = new JRadioButton("Button text only");
        radioWholeButton.setSelected(true);
        ButtonGroup bg = new ButtonGroup();
        bg.add(radioWholeButton);
        bg.add(radioTextOnly);
        button = new JButton("  Shake with this Button  ");
        button.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                shakeButton(radioWholeButton.isSelected());
            }
        });
        JPanel p1 = new JPanel();
        p1.setBorder(BorderFactory.createTitledBorder("Shake Options"));
        p1.setLayout(new GridLayout(0, 1));
        p1.add(radioWholeButton);
        p1.add(radioTextOnly);
        JPanel p2 = new JPanel();
        p2.setLayout(new GridLayout(0, 1));
        p2.add(button);
        JFrame frame = new JFrame();
        frame.setTitle("Shaking Button Demo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(p1, BorderLayout.NORTH);
        frame.add(p2, BorderLayout.SOUTH);
        frame.setSize(240, 160);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    private void shakeButton(final boolean shakeWholeButton) {
        final Point point = button.getLocation();
        final Insets margin = button.getMargin();
        final int delay = 75;
        Runnable r = new Runnable() {

            @Override
            public void run() {
                for (int i = 0; i < 30; i++) {
                    try {
                        if (shakeWholeButton) {
                            moveButton(new Point(point.x + 5, point.y));
                            Thread.sleep(delay);
                            moveButton(point);
                            Thread.sleep(delay);
                            moveButton(new Point(point.x - 5, point.y));
                            Thread.sleep(delay);
                            moveButton(point);
                            Thread.sleep(delay);
                        } else {// text only
                            setButtonMargin(new Insets(margin.top, margin.left + 3, margin.bottom, margin.right - 2));
                            Thread.sleep(delay);
                            setButtonMargin(margin);
                            Thread.sleep(delay);
                            setButtonMargin(new Insets(margin.top, margin.left - 2, margin.bottom, margin.right + 3));
                            Thread.sleep(delay);
                            setButtonMargin(margin);
                            Thread.sleep(delay);
                        }
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();
                    }
                }
            }
        };
        Thread t = new Thread(r);
        t.start();
    }

    private void moveButton(final Point p) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                button.setLocation(p);
            }
        });
    }

    private void setButtonMargin(final Insets margin) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                button.setMargin(margin);
            }
        });
    }
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

public class ShakeComponents1 {

    private JFrame frame = new JFrame();
    private final String items[] = {"One", "Two", "Three"};
    private Timer timer;
    private JPanel panel = new JPanel();
    private JPanel buttonPanel = new JPanel();
    private JButton button = new JButton("  Exit  ");
    private boolean repeats = true;
    private boolean runs = false;
    private Color clr[] = {Color.red, Color.blue, Color.magenta};
    private Insets initMargin;

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                new ShakeComponents1().makeUI();
            }
        });
    }

    public void makeUI() {
        buttonPanel = new JPanel();
        buttonPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
        buttonPanel.setLayout(new BorderLayout());
        button.setPreferredSize(new Dimension(100, 45));
        button.setForeground(Color.darkGray);
        button.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent event) {
                Runnable doRun = new Runnable() {

                    @Override
                    public void run() {
                        System.exit(0);
                    }
                };
                SwingUtilities.invokeLater(doRun);
            }
        });
        button.addMouseListener(new java.awt.event.MouseListener() {

            @Override
            public void mouseClicked(MouseEvent e) {
            }

            @Override
            public void mousePressed(MouseEvent e) {
            }

            @Override
            public void mouseReleased(MouseEvent e) {
            }

            @Override
            public void mouseEntered(MouseEvent e) {
                if (runs) {
                    SwingUtilities.invokeLater(new Runnable() {

                        @Override
                        public void run() {
                            runs = false;
                            timer.stop();
                            changePnlBorder(new EmptyBorder(5, 5, 5, 5));
                            changeBtnForegroung(Color.darkGray);
                        }
                    });
                }
            }

            @Override
            public void mouseExited(MouseEvent e) {
                if (!runs) {
                    timer.start();
                    runs = true;
                }
            }
        });
        buttonPanel.add(button);
        final Insets margin = button.getMargin();
        panel.add(buttonPanel);
        for (int i = 0; i < 2; i++) {
            JComboBox combo = new JComboBox(items);
            combo.setMinimumSize(new Dimension(50, 25));
            combo.setMaximumSize(new Dimension(150, 25));
            combo.setPreferredSize(new Dimension(100, 25));
            combo.addActionListener(new ShakeAction());
            panel.add(combo);
        }
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(panel);
        frame.pack();
        frame.setLocation(50, 50);
        frame.setVisible(true);
        timer = new Timer(500, new ShakeAction());
        timer.setRepeats(repeats);
        initMargin = button.getMargin();
    }

    private class ShakeAction extends AbstractAction {

        private static final long serialVersionUID = 1L;
        private int noColor = 0;
        private Border border;
        private int count = 0;

        @Override
        public void actionPerformed(ActionEvent e) {
            timer.start();
            if (count > 5) {
                new Thread(new Runnable() {

                    @Override
                    public void run() {
                        try {
                            Thread.sleep(750);
                            changeBtnForegroung(Color.darkGray);
                            Thread.sleep(750);
                            count = 0;
                            Thread.sleep(750);
                        } catch (Exception e) {
                            System.out.println(e);
                        }
                    }
                }).start();
            } else {
                new Thread(new Runnable() {

                    @Override
                    public void run() {
                        try {
                            runs = true;
                            if (noColor < 2) {
                                noColor++;
                                changeBtnForegroung(clr[noColor]);
                            } else {
                                noColor = 0;
                                changeBtnForegroung(clr[noColor]);
                            }
                            changeBtnMargin(new Insets(initMargin.top, initMargin.left + 10, initMargin.bottom, initMargin.right - 10));
                            border = new EmptyBorder(0, 5, 10, 5);
                            changePnlBorder(border);
                            Thread.sleep(100);
                            changeBtnMargin(new Insets(initMargin.top, initMargin.left - 10, initMargin.bottom, initMargin.right + 10));
                            border = new EmptyBorder(0, 0, 10, 10);
                            changePnlBorder(border);
                            Thread.sleep(100);
                            changeBtnMargin(new Insets(initMargin.top, initMargin.left + 10, initMargin.bottom, initMargin.right - 10));
                            border = new EmptyBorder(5, 10, 5, 0);
                            changePnlBorder(border);
                            Thread.sleep(100);
                            changeBtnMargin(new Insets(initMargin.top, initMargin.left - 10, initMargin.bottom, initMargin.right + 10));
                            border = new EmptyBorder(10, 10, 0, 0);
                            changePnlBorder(border);
                            Thread.sleep(100);
                            changeBtnMargin(new Insets(initMargin.top, initMargin.left, initMargin.bottom, initMargin.right));
                            border = new EmptyBorder(5, 5, 5, 5);
                            changePnlBorder(border);
                            Thread.sleep(100);
                            count++;
                        } catch (Exception e) {
                            System.out.println(e);
                        }
                    }
                }).start();
            }
        }
    }

    private void changePnlBorder(final Border b) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                buttonPanel.setBorder(b);
                buttonPanel.revalidate();
                buttonPanel.repaint();
            }
        });
    }

    private void changeBtnForegroung(final Color c) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                button.setForeground(c);
            }
        });
    }

    private void changeBtnMargin(final Insets margin) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                button.setMargin(margin);
            }
        });
    }
}
import java.awt.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;

public class DelayedComboBoxTest extends JFrame {

    private static final long serialVersionUID = 1L;
    private JCheckBox chkA = new JCheckBox("A");
    private JCheckBox chkB = new JCheckBox("B");
    private JCheckBox chkC = new JCheckBox("C");
    private JComboBox cboItems = new JComboBox();

    public DelayedComboBoxTest() {
        super("Delayed ComboBox Test");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        JPanel p = new JPanel();
        p.add(chkA);
        p.add(chkB);
        p.add(chkC);
        p.add(cboItems);
        Container c = getContentPane();
        c.setLayout(new BorderLayout());
        c.add(p);
        pack();
        cboItems.addPopupMenuListener(new MyPopupMenuListener());
    }

    private void rebuildList() {
        setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        Vector<String> items = new Vector<String>();
        if (chkA.isSelected()) {
            items.add("A");
        }
        if (chkB.isSelected()) {
            items.add("B");
        }
        if (chkC.isSelected()) {
            items.add("C");
        }
        cboItems.setModel(new DefaultComboBoxModel(items));
        try {
            new Thread().sleep(2500); // simulate a long transaction
        } catch (InterruptedException ex) {
        }
        setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
    }

    public static void main(String[] args) {
        JFrame f = new DelayedComboBoxTest();
        f.setVisible(true);
    }

    private class MyPopupMenuListener implements PopupMenuListener {

        @Override
        public void popupMenuCanceled(PopupMenuEvent e) {
        }

        @Override
        public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
        }

        @Override
        public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
            int items = cboItems.getItemCount();
            rebuildList();

            if (items != cboItems.getItemCount()) {
                cboItems.hidePopup();
                cboItems.showPopup();
            }
        }
    }
}
try
    {
        CreateConnection();
        st=con.prepareStatement(QueryString);
        rs=st.executeQuery();
        int i = 0;  
        rs.last(); 
        final String[] strings = new String[rs.getRow()]; 
        rs.first();
        strings[i]="Send to All";i++;
        while (rs.next()) {  
          strings[i] = rs.getString(1); i++; 
        } 
        ToBeFilled.setModel(new javax.swing.AbstractListModel() {

        public int getSize() { return strings.length; }
        public Object getElementAt(int i) { return strings[i]; }
        });
        con.close();
    }
    catch(Exception ex)
    {    
        JOptionPane.showMessageDialog(null, ex.toString());
    }
jList1.setModel(new javax.swing.AbstractListModel() {
String[] strings = { "Send to All", "ABC", "DEF" };
public int getSize() { return strings.length; }
public Object getElementAt(int i) { return strings[i]; }
final DefaultListModel model = new DefaultListModel();


    final Thread updater = new Thread() {

        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                model.addElement(i);
                listData.setModel(model);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    };
    updater.start();