我需要Java上的什么布局?
我有一个JPanel,例如,如果我单击按钮插入,我可以添加一个JButton和一个JLabel。我的问题是我需要在JButton下插入JLabel。JLabel文本必须与JButton文本一致。在那之后,我想要一个大约10像素的空间来再次使用我的插入按钮,并在JButton和JLabel上水平添加一个方向相同的新对 谢谢我需要Java上的什么布局?,java,swing,layout,Java,Swing,Layout,我有一个JPanel,例如,如果我单击按钮插入,我可以添加一个JButton和一个JLabel。我的问题是我需要在JButton下插入JLabel。JLabel文本必须与JButton文本一致。在那之后,我想要一个大约10像素的空间来再次使用我的插入按钮,并在JButton和JLabel上水平添加一个方向相同的新对 谢谢 PD:请用一次尝试来补充你的问题。我想你有类似的问题 rootPane +-----panelButton | +------JButto
PD:请用一次尝试来补充你的问题。我想你有类似的问题
rootPane
+-----panelButton
| +------JButton
|
+-----panelPanels
+-----panel
+---JButton
+---JLabel
SpringLayout可以帮助您
SpringUtilities.makeGrid(panel,
2, 1, //rows, cols
0, 0, //initialX, initialY
5, 5);//xPad, yPad
下面是一个显示动态的快速示例,我假设您希望设置允许插入未定义数量的面板:
public class AwesomeAnswer {
public static void main(String[] args) {
// please not that this is only an example and not a
// Swing thread safe way of starting a JFrame
JFrame frame = new JFrame();
JPanel content = (JPanel)frame.getContentPane();
// create our top panel that will hold all of the inserted panels
JPanel page = new JPanel();
page.setLayout( new BoxLayout( page, BoxLayout.Y_AXIS ) );
// add our page to the frame content pane
content.add( page );
// add two button/label panels
page.add( insert( "This is an awesome answer", "Accept" ) );
page.add( insert( "Say thank you", "Thank" ) );
frame.pack();
frame.setVisible( true );
}
public static final JPanel insert( String labelText, String buttonText ) {
// create the label and the button
JLabel lbl = new JLabel( labelText );
JButton btn = new JButton( buttonText );
// create the panel that will hold the label and the button
JPanel wrapPanel = new JPanel( new GridBagLayout() );
wrapPanel.setBorder( BorderFactory.createEmptyBorder( 10, 10, 10, 10 ) );
// tell the grid bag how to behave
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = 0;
gbc.gridheight = 2;
// make the button centered
JPanel buttonPanel = new JPanel( new FlowLayout( 0, 0, FlowLayout.CENTER ) );
buttonPanel.add( btn );
// make the label centered
JPanel labelPanel = new JPanel( new FlowLayout( 0, 0, FlowLayout.CENTER ) );
labelPanel.add( lbl );
// add our button and label to the grid bag with our constraints
wrapPanel.add( buttonPanel, gbc );
wrapPanel.add( labelPanel, gbc );
return wrapPanel;
}
}
我认为在启动GUI之前,我应该有一个类似屏幕的设计。我将尝试这个替代方案。谢谢你的回答!