无法确定JButton的大小

时间:2011-07-05 18:33:37

标签: java swing jframe jbutton layout-manager

我正在尝试向我的JFrame添加一个按钮。 我无法将JButton指定为特定大小。

我试过了

mJButtonOne.setPreferredSize
mjButtonOne.setMinimum/maximum
mjBUttonOne.setSize

无论我尝试什么,按钮总是加载全屏。

这是我的代码我正在使用一些方法,一个make,一个构建和一个dostuff。

private void make() {
    this.mJLabelTime = new JLabel("");
    this.mJButtonOne = new JButton("");
//I have tried setting size in do stuff as well.

      }

private void build(){
    this.add(this.mJLabelTime);
    this.add(this.mJButtonOne);

     }

private void doStuff(){

    this.mJLabelTime.setText(Customtime.time("HH:mm:ss"));
    this.mJButtonOne.setText("BUTTON!");
    this.mJButtonOne.setPreferredSize(new Dimension(1, 10));

My Main看起来像这样。

public static void main(String[] args) {
    View view = new View();
       view.setMaximumSize(new Dimension(200, 200));
       view.setMinimumSize(new Dimension(200, 200));
    view.setVisible(true);
System.out.println("Running app..."); 
//System.out.println("Goodbye World");    
}

2 个答案:

答案 0 :(得分:3)

如果您没有使用任何LayoutManager,请为setLayout(null)课程致电View

但是建议您选择并使用布局管理器,让layoutmanager负责调整组件大小。

答案 1 :(得分:2)

通常,布局管理器会尊重您传递给setPreferredSize(...)的尺寸。

示例

public class View {

    public static void main(String[] args){
        SwingUtilities.invokeLater(new Runnable(){
            @Override
            public void run() {
                createAndShowGUI();
            }
        });
    }

    private static void createAndShowGUI(){
        final JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        final JPanel panel = new JPanel(){
            @Override
            public Dimension getPreferredSize(){
                return new Dimension(200, 200);
            }
        };
        final JButton button = new JButton("Button"){
            @Override
            public Dimension getPreferredSize(){
                return new Dimension(100, 20);
            }
        };
        panel.add(button);
        frame.add(panel);

        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

<强>输出

enter image description here

修改

不是将组件直接添加到JFrame,而是将其添加到JPanel,然后将JPanel添加到JFrame。请注意,JPanel默认为流程布局