Java Swing制作具有自定义尺寸的盒子

时间:2014-06-13 20:01:40

标签: java swing jpanel grid-layout boxlayout

我需要帮助在Java Swing中制作布局。我的盒子非常小,无法弄清楚如何让它们更大。

以下是它的样子:http://i.imgur.com/QtWqSjB.png

enter image description here

这就是我想要的:http://i.imgur.com/LP0DUVm.png

enter image description here

代码:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class MPC
{
    public static void main(String [] args)
    {
            createWindow();
    }

    public static void createWindow()
    {
            JPanel main, left, right;
            JFrame frame = new JFrame("MPC");
            Box [] box = new Box[16];
            JSlider tempo = new JSlider(JSlider.VERTICAL, 0, 30, 15);

            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            main = new JPanel();
            main.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));

            //Left side holds boxes
            left = new JPanel();
            left.setLayout(new GridLayout(4, 4));

            for(int i = 0; i < 16; i++)
            {
                    box[i] = new Box(BoxLayout.X_AXIS);
                    box[i].setBorder(BorderFactory.createLineBorder(Color.black));
                    box[i].add(new JLabel("      " + (i+1) + "      "));
                    left.add(box[i]);
            }

            //Right side for tempo
            right = new JPanel();
            right.setLayout(new GridLayout(1, 1));
            tempo.setMajorTickSpacing(10);
            tempo.setMinorTickSpacing(1);
            tempo.setPaintTicks(true);
            right.add(tempo);

            //Add everything to window
            main.add(left, BorderLayout.WEST);
            main.add(right, BorderLayout.EAST);

            frame.add(main);
            frame.getContentPane();

            //Window Stuff
            frame.setBounds(50,50,500,500);
            frame.setResizable(false);
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
    }
}

我该怎么做才能让它看起来像第二张照片?任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:2)

尝试将main的布局更改为BorderLayout

main = new JPanel(new BorderLayout());

然后,将left面板添加到BorderLayout

的中心
main.add(left, BorderLayout.CENTER);

这样,框网格将尽可能多地占用main的可用空间。有关详细信息,请参阅How to Use BorderLayout

这些变化的结果:

enter image description here