[英]How do I visibly change the contents of my JScrollPane each time I call the ActionListener?
每次调用Action Listener时,我都希望这个JScrollPane将其列表更改为完全不同的列表。 我不完全确定如何做到这一点。 我已经尝试更改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();
}
}
}
在这个例子中,每当我更改JComboBox中的内容时,我希望JScrollPane内的列表在数组strings1和strings2之间切换。 我也希望这个改变是可见的,因为我改变了组合框中的内容,而不是以后。 正如您从编译的代码中看到的那样,它并没有那么好用。 我究竟做错了什么? 为什么我不希望它改变列表?
创建新的滚动窗格不会将滚动窗格添加到面板。
无论如何,没有必要继续创建一个新的滚动窗格。 只需更改滚动窗格中显示的组件:
//theScrollPane = new JScrollPane(availableList);
//theScrollPane.revalidate();
//theScrollPane.repaint();
theScrollPane.setViewportView(availableList);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.