[英]How can I make JFrame resize automatically to display all buttons
我有一個簡單的swing應用程序,其中包括一個JLabel和三個按鈕。 這三個按鈕位於它們自己的JPanel中,該JPanel與JLabel一起位於JFrame中。 JPanel使用flowlayout管理器水平排列按鈕,JFrame使用BorderLayout管理器垂直排列JLabel和JPanel。
我的問題是,當我啟動該應用程序時,在使用過程中,按鈕之一上的文本會更改,這會增加其寬度。 但是,該窗口不會調整大小以適應此操作,並且其中一個按鈕消失了。 我曾想過再次調用pack(),但JFrame是構造函數中的局部變量,而且,我不必告訴我的程序來調整大小,對嗎? 我在Google或這里找不到任何幫助的方法,但是必須有一個簡單的解決方案,我想念的是什么? 代碼如下。
playButton = new JButton("Play");
pauseButton = new JButton("Pause");
stopButton = new JButton("Stop");
curTrackLabel = new JLabel("No Track Selected");
JFrame myFrame = new JFrame("MediaPlayer");
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setTitle("MediaPlayer");
myFrame.setLocation(400,300);
JPanel topPanel = new JPanel();
topPanel.setLayout(new BorderLayout());
myFrame.add(topPanel);
JPanel buttonPanel = new JPanel(new FlowLayout());
buttonPanel.add(playButton);
buttonPanel.add(pauseButton);
buttonPanel.add(stopButton);
topPanel.add(buttonPanel, BorderLayout.CENTER);
topPanel.add(curTrackLabel, BorderLayout.NORTH);
playButton.addActionListener(new playButtonHandler());
pauseButton.addActionListener(new pauseButtonHandler());
stopButton.addActionListener(new stopButtonHandler());
myFrame.pack();
myFrame.setVisible(true);
也許嘗試
((JFrame中)myButton.getTopLevelAncestor())包();
其中myButton是在執行期間修改其文本的按鈕。
與學習任何GUI軟件一樣,最好進行實驗。 嘗試將嵌套的JPanels與BorderLayouts混淆。
最終,您將JPanel與BorderLayout一起使用(Flow Layout可以,但實際上在調整窗口大小時,它通常會失敗)。 請參閱http://download.oracle.com/javase/tutorial/uiswing/layout/border.html,以了解有關BorderLayouts的更多信息。
現在,對於您的布局方案,應該遵循以下原則:
位於http://download.oracle.com/javase/tutorial/uiswing/layout/border.html的教程應對此提供幫助。 但通常使用以下命令:
如果您需要更多的靈活性,請查看JGoodies: http ://www.jgoodies.com/。 這更像是創建表單。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.