2014-09-28 35 views
0

根據我的要求:垂直JPanel手動定位:哪種佈局?

  • JPanels的單個垂直列。
  • 設置JPanel的垂直位置*而不使用兄弟的屬性。
  • 當框架被調整大小時,組件的位置和大小是固定的。
  • 保持其他佈局方面的自動(如優選的尺寸計算),儘可能

(*)位置:我的意思是定位在Component.setLocation(x, y)

是否有解決方案,這是明顯的,如果這是GridBagLayout,如何做到這一點?

詳情:

我想唯一指定其垂直位置,把組件垂直一列容器(如垂直框)。在不失去佈局佈局的其他好處的情況下做到這一點的最佳方式是什麼?

在垂直框,設置組件的垂直位置,必須使用一個filler來完成,或者通過調整正上方的部件的尺寸,也沒有像這樣的可能性:

panel.setLocation(getLocation().x, y) 

在另一方面使用無佈局容器穿上我的任務管理:

  • 組件
  • 容器調整大小事件的初始大小。

這裏推薦的null layout的解決方案,在這裏,這是一個custom之一,在這裏,這是GridBagLaout。此外MIGLayout似乎是普遍的(但我不希望添加另一個庫到我的項目)。

+0

爲什麼不使用'JList'? – 2014-09-28 09:43:45

+0

*「我專注於佈局」*當佈局是關鍵時,人們經常忽略佈局。有時候,當一種完全不同的方法可能更好時(例如列表,樹,工具欄,選項卡窗格),人們會將注意力集中在佈局上。例如。這個接受的[answer](http://stackoverflow.com/a/26080729/418556)似乎在Rob Camick的'WrapLayout'中,但在答案中的3種方法中,我可能會使用'JList'。不止一種方法去皮膚那隻貓。 ;) – 2014-09-28 10:05:02

+0

嘗試我的解決方案http://stackoverflow.com/a/26084135/1966247 – Muhammad 2014-09-28 10:51:49

回答

2

我已經寫了下面的程序給那些也在尋找相同要求的人。

注意:確保將第一個元素添加到0的位置,因爲不會有更多的組件,並且除0,2到0或1,3到0或1或2之外沒有可用的位置,等等

public class VerticalList extends JFrame { 

    JPanel pnl = null; 
    TextField tf = new TextField(10); 
    Box center = Box.createVerticalBox(); 
    JScrollPane jsp = new JScrollPane(center); 
    JPanel ctrl = new JPanel(new FlowLayout()); 
    JButton send = new JButton("Send"); 


    public VerticalList() { 
     jsp.setAutoscrolls(true); 
     ctrl.add(send); 
     ctrl.add(new JLabel("Position:")); 
     ctrl.add(tf); 
     Container cnt = getContentPane(); 

     cnt.add(jsp, BorderLayout.CENTER); 
     cnt.add(ctrl, BorderLayout.SOUTH); 
     send.addActionListener(new ActionListener() { 

      @Override 
      public void actionPerformed(ActionEvent e) { 
       pnl = new JPanel(new FlowLayout()); 

       pnl.setBorder(BorderFactory.createLineBorder(Color.red)); 
       pnl.add(new JLabel("Added to Position: "+tf.getText())); 

       pnl.setMaximumSize(new Dimension(Integer.MAX_VALUE, (int)pnl.getPreferredSize().getHeight())); 
       try{ 
       int index = Integer.parseInt(tf.getText()); 
       center.add(pnl, index); 
       }catch(Exception ex){ 
        JOptionPane.showMessageDialog(null, "Please Provide a Valid position", "Position Error", JOptionPane.ERROR_MESSAGE); 
       } 
       validate(); 
      } 
     }); 
     setPreferredSize(new Dimension(300, 300)); 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     setVisible(true); 
     pack(); 

    } 

    public static void main(String[] args) { 
     new VerticalList(); 
    } 
} 
+0

謝謝。我不確定自己的理解是否正常,似乎是將面板添加到容器中,在變量兄弟索引中添加面板,然後讓佈局將它們按正確的順序排列。我正在尋找的是設置以像素表示的垂直位置。 – mins 2014-09-28 11:06:02

+1

'setPreferredSize(new Dimension(300,300));'請參閱[我應該避免使用Java Swing中的set(Preferred | Maximum | Minimum)Size方法嗎?](http://stackoverflow.com/q/7229226/ 418556)(是) – 2014-09-28 11:12:20

+0

@AndrewThompson setPreferredSize(Dim)不是這裏的問題,但佈局:) – Muhammad 2014-09-28 11:40:03