[英]Setting divider location on a JSplitPane
我想擁有3個可水平調整的JPanels。 它工作正常,但我無法設置第一個JSlitPane的位置: sp.setDividerLocation(.3);
不起作用。
public class JSplitPanelProva extends JFrame {
public JSplitPanelProva() {
this.setLayout(new BorderLayout());
JPanel leftPanel = new JPanel();
leftPanel.setBackground(Color.BLUE);
JPanel centerPanel = new JPanel();
centerPanel.setBackground(Color.CYAN);
JPanel rightPanel = new JPanel();
rightPanel.setBackground(Color.GREEN);
JSplitPane sp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, centerPanel);
JSplitPane sp2 = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, sp, rightPanel);
sp.setOneTouchExpandable(true);
sp2.setOneTouchExpandable(true);
this.add(sp2, BorderLayout.CENTER);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(1000, 600);
this.setVisible(true);
sp.setDividerLocation(.3);
sp2.setDividerLocation(.6);
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new JSplitPanelProva();
}
}
更改:
sp.setDividerLocation(.3);
sp2.setDividerLocation(.6);
至:
sp2.setDividerLocation(.6);
ActionListener splitListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
sp.setDividerLocation(.3);
}
};
Timer t = new Timer(200, splitListener);
t.setRepeats(false);
t.start();
它將按預期工作。 延遲使GUI有時間重新計算大小。
看來需要發生三件事:
Event Dispatch Thread (EDT)
的末尾 以下代碼將完成所有3步:
this.setVisible(true);
sp2.setDividerLocation(.6);
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
sp.setDividerLocation(.3);
}
});
注意:所有Swing組件都應在EDT上創建。 因此,您還應該使用以下內容來創建框架:
EventQueue.invokeLater(new Runnable()
{
public void run()
{
new JSplitPaneProva();
}
});
setDividerLocation(double proportionalLocation)
方法的文檔說:
如果未正確實現拆分窗格並在屏幕上顯示,則此方法無效(新的分隔符位置將變為(當前大小*比例位置)為0)。
相反,您可以使用setDividerLocation(int location)
方法,如下所示:
sp.setDividerLocation(300);
sp2.setDividerLocation(600);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.