我有一个简单的swing应用程序,它由一个JLabel和三个按钮组成。这三个按钮与JLabel一起位于JFrame中的JPanel中。 JPanel使用flowlayout管理器水平排列按钮,JFrame使用BorderLayout管理器垂直排列JLabel和JPanel。如何让JFrame自动调整大小以显示所有按钮
我的问题是当我启动应用程序时,在使用过程中,其中一个按钮的文本更改增加其宽度。但是,该窗口不会调整大小以适应此并且其中一个按钮消失。我想过再次调用pack(),但JFrame是我的构造函数中的局部变量,而且,我不应该告诉我的程序调整大小,对吧?我一直没有找到任何东西在谷歌或在这里帮助我,但必须有一个简单的解决方案,我错过了什么?代码如下。
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);
+1,cool!我今天学习一种新方法。在过去,我建议SwingUtilities.windowForComponent(...)。 – camickr 2010-11-24 20:12:11