以下是我正在使用的完整相关代码:
JPanel songDetails = new JPanel(new GridBagLayout() );
GridBagConstraints constraints = new GridBagConstraints();
constraints.fill = GridBagConstraints.BOTH;
constraints.weightx = 1.0;
constraints.gridx = 0;
constraints.gridy = 0;
for(int i = 0; i < songOptions.length; i++, constraints.gridx++){
songDetails.add(this.buttons[i],constraints);
}
constraints.gridy = 1;
for(int i = 0; i < songInfo.length; i++, constraints.gridy++){
constraints.gridwidth = 1;
constraints.gridx = 0;
songDetails.add(this.labels[i],constraints);
constraints.gridwidth = GridBagConstraints.REMAINDER;
constraints.gridx = 1;
songDetails.add(this.fields[i],constraints);
}
JList<Song> list = new JList<Song>(this.lib); //data has type Object[]
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setLayoutOrientation(JList.VERTICAL);
list.setVisibleRowCount(5);
JScrollPane listScroller = new JScrollPane();
listScroller.setViewportView(list);
constraints.fill = GridBagConstraints.BOTH;
constraints.weightx = 1.0;
constraints.gridheight = GridBagConstraints.RELATIVE;
constraints.gridwidth = GridBagConstraints.REMAINDER;
constraints.gridx = 0;
constraints.gridy = 0;
constraints.anchor = GridBagConstraints.NORTHWEST;
setLayout(new GridBagLayout());
add(listScroller,constraints);
constraints.gridy++;
add(songDetails, constraints);
在main中,我按如下方式初始化帧:
SongLib myLibrary = new SongLib("Song Library", pathName );
myLibrary.setVisible(true);
myLibrary.setSize(300, 250);// Sets the Frame Size
myLibrary.setMinimumSize(new Dimension(300,250));
myLibrary.setResizable(true);//Makes the size not fixed
myLibrary.setLocationRelativeTo(null); // Make the Frame appear centered
myLibrary.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//Tells program to exit when the 'x'(close) button is pressed
我的问题是,当我展开框架时,它会水平扩展(宽度),但不会垂直扩展。我认为改变填充值会对我有用,但事实并非如此。 此外,如果可能在发生此更改时更改字体大小。
如果它不会太复杂,我还想让用户能够改变每个帧的相对大小。我认为需要一些动作监听器。如果是的话我会稍后再看,但是如果有什么东西我会忽略它会非常感激!
答案 0 :(得分:3)
请注意您的代码:
GridBagConstraints constraints = new GridBagConstraints();
constraints.fill = GridBagConstraints.BOTH;
constraints.weightx = 1.0; // *********
constraints.gridx = 0;
constraints.gridy = 0;
你没有为GridBagConstraints设置重量,只是权重。设置它,它将垂直扩展。
如,
GridBagConstraints constraints = new GridBagConstraints();
constraints.fill = GridBagConstraints.BOTH;
constraints.weightx = 1.0;
constraints.weighty = 1.0; // ***** added *****
constraints.gridx = 0;
constraints.gridy = 0;
答案 1 :(得分:0)
随着扩展问题的解决,我仍然可以告诉你,更改字体需要一个像这样的监听器:
myLibrary.addComponentListener(new java.awt.event.ComponentAdapter()
{
public void componentResized(ComponentEvent e)
{
//Call method that changes the font of each object
}
});
我不太确定你改变每个帧的相对大小是什么意思(?)但如果你的意思是你的框架内的每个组件,我建议先做一些研究,然后再做(如有必要)发布一个新问题。