我希望这个 JScrollPane 每次调用 Action Listener 时都将其列表更改为完全不同的列表。我不完全确定如何去做。我尝试更改 JList,重新绘制 ScrollPane 并重新验证它,但它并没有带来预期的效果。我写了一个可编译的小程序,在这里解释了我的问题:
import javax.swing.*;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.*;
import java.sql.SQLException;
@SuppressWarnings("serial")
public class TestFrame extends JFrame {
public final Dimension SCROLL_PANE_DIMENSION = new Dimension(200, 100);
private JComboBox<String> comboNames;
private JPanel panel = new JPanel();
private JList<String> availableList;
private JScrollPane theScrollPane;
private boolean string1Used = true;
String[] strings = { "Aaardvark", "Adam", "Alms" };
String[] strings2 = { "Bad", "Bugs", "Bunny" };
public static void main(String[] args){
try {
TestFrame frame = new TestFrame();
frame.setVisible(true);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public TestFrame() throws SQLException {
String[] comboStrings = { "Doesn't", "matter", "here" };
this.setSize(300,200);
availableList = new JList<String>(strings);
theScrollPane = new JScrollPane(availableList);
theScrollPane = new JScrollPane(availableList);
theScrollPane.setPreferredSize(SCROLL_PANE_DIMENSION);
theScrollPane.setSize(SCROLL_PANE_DIMENSION);
theScrollPane.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(), "Sub Conditions",
TitledBorder.CENTER, 0));
availableList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
availableList.setSelectedIndex(0);
availableList.setVisibleRowCount(5);
availableList.setSize(SCROLL_PANE_DIMENSION);
comboNames = new JComboBox<String>(comboStrings);
comboNames.addActionListener(new ConditionComboListener());
panel = new JPanel();
this.add(panel);
panel.add(comboNames);
panel.add(theScrollPane);
}
private class ConditionComboListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent arg0) {
refreshSubConditionList();
}
private void refreshSubConditionList() {
if (string1Used) {
System.out.println("Switching to Strings2");
availableList = new JList<String>(strings2);
string1Used = false;
} else{
System.out.println("Switching to Strings");
availableList = new JList<String>(strings);
string1Used = true;
}
theScrollPane = new JScrollPane(availableList);
theScrollPane.revalidate();
theScrollPane.repaint();
}
}
}
在此示例中,我希望 JScrollPane 内的列表在每次更改 JComboBox 中的内容时在数组 strings1 和 strings2 之间切换。我还希望此更改在我更改组合框中的内容后立即可见,而不是稍后。正如您从编译后的代码中看到的那样,它并不完全是这样。我究竟做错了什么?为什么当我想要它时它不改变列表?