-4

我有一个 JPanel,例如,如果我单击“INSERT”按钮,我可以添加一个 JButton 和一个 JLabel。我的问题是我需要在 JButton 下插入 JLabel。JLabel 文本必须居中,尊重 JButton 文本。之后,我想要一个大约 10 像素的空间来再次使用我的“INSERT”按钮,并在 JButton 和 JLabel 上水平添加一个具有相同方向的新对。

谢谢!

PD:请尝试补充您的问题。

4

2 回答 2

1

这是一个快速示例,它显示了一个动态(我假设您想要的)设置,以允许插入未定义数量的面板:

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;
  }
}
于 2012-04-27T21:08:49.303 回答
1

我认为你有类似的东西

rootPane
    +-----panelButton
    |            +------JButton
    |
    +-----panelPanels
              +-----panel
                     +---JButton
                     +---JLabel

可以SpringLayout帮助你

SpringUtilities.makeGrid(panel,
                     2, 1, //rows, cols
                     0, 0, //initialX, initialY
                     5, 5);//xPad, yPad
于 2012-04-27T20:56:52.003 回答