我有2个窗口。一个得到一个空的JList,另一个得到一个按钮。因此,每当我按下按钮时,我都希望将值添加到列表中。这是我的代码,但没有完成:
窗口1
final DefaultListModel<String> favouriteNames = new DefaultListModel<String>();
JList namesList = new JList(favouriteNames);
窗口2
public class button extends JFrame {
private JList namesList;
private DefaultListModel<String> favouriteNames;
this.namesList = namesList;
JButton addThis = new JButton("Add");
addThis.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
favouriteNames.addElement("Jack");
}
});
}
}
答案 0 :(得分:3)
在构造函数中将DefaultListModel的实例传递给Window 2.
编辑添加:以下是在构造函数中传递实例的方法。
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class ButtonFrame implements Runnable {
private JFrame frame;
private DefaultListModel favouriteNames;
public ButtonFrame(final DefaultListModel favouriteNames) {
this.favouriteNames = favouriteNames;
}
@Override
public void run() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton addThis = new JButton("Add");
addThis.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
favouriteNames.addElement("Jack");
}
});
frame.add(addThis);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new ButtonFrame(new DefaultListModel()));
}
}
答案 1 :(得分:0)
我制作了一个更简单的程序版本,但仍有问题,我相信ActionPerformed会发送数据,但JList无法识别它,或者基本上没想到会收到它。所以这就是我到目前为止所做的。所以这是我的研究和尝试的一点,也许它提供了有关问题的更多细节。
主窗口:
public class main {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
JFrame frame = new ClassA();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
ClassA的:
public class ClassA extends JFrame {
DefaultListModel<String> myList;
JList list;
public ClassA() {
setSize(300,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(2,1));
myList = new DefaultListModel<String>();
list = new JList(myList);
//ClassB sendsText = new ClassB(myList, list);
JButton find = new JButton("Find");
find.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
new ClassB().setVisible(true);
}
});
add(panel);
panel.add(find);
panel.add(list);
}
}
ClassB的:
public class ClassB extends JFrame {
DefaultListModel<String> myList;
JList list;
public ClassB(DefaultListModel<String> myList, JList list){
this.myList = myList;
this.list = list;
}
public ClassB() {
setSize(300,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(2,1));
JButton addMe = new JButton("Add Me");
addMe.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
myList.addElement("Danial");
}
});
add(panel);
panel.add(addMe);
}
}