答案取決於這個組件是什麼,你正在添加項目。如果您使用的是JList
,則可以使用類似DefaultListModel#add(int, Object)
的東西將項目添加到特定位置。
如果您正在使用基於JComponent
(如JPanel
)的東西,你可以用JComponent#add(Component, int)
指定組件時,應添加的地點,這種假設存在的位置(即你不能添加組件如果容器僅包含單個組件,則將其置於位置100)。
以下示例將生成一個隨機數,確定該數字應該插入的位置,以便維護有序列表並在該點插入組件。它也會嘗試滾動JScrollPane
使項目可見
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JViewport;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test10 {
public static void main(String[] args) {
new Test10();
}
public Test10() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JPanel numbers;
private List<Integer> values;
public TestPane() {
values = new ArrayList<>(25);
setLayout(new BorderLayout());
numbers = new JPanel(new GridLayout(0, 1));
add(new JScrollPane(numbers));
Timer timer = new Timer(500, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int next = (int) (Math.random() * Integer.MAX_VALUE);
int insertion = Collections.binarySearch(values, next);
if (insertion < 0) {
insertion = (Math.abs(insertion)) - 1;
}
values.add(insertion, next);
JLabel label = new JLabel(Integer.toString(next));
numbers.add(label, insertion);
numbers.revalidate();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
Point p = label.getLocation();
JViewport vp = (JViewport) numbers.getParent();
JScrollPane sp = (JScrollPane) vp.getParent();
vp.setViewPosition(p);
}
});
}
});
timer.start();
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
}
1-您不應該調用'JScrollPane#add'; 2-答案取決於這個「組件」是什麼 – MadProgrammer