开发者

Unable to size JButton

I am attempting to add a button to my JFrame. I am unable to assign the JButton to a certain size.

I have tried

mJButtonOne.setPreferredSize
mjButtonOne.setMinimum/maximum
mjBUttonOne.setSize

No matter what I try the button always loads full screen.

Here is my code I am using a few methods, a make, a build, and a 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 looks like this.

public static void main(String[] 开发者_StackOverflowargs) {
    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");    
}


If you are not using any LayoutManager, call setLayout(null) for your View class.

But it's recommended that you pick and use a layout manager and let the layoutmanager take care of sizing components.


Usually the layout manager respects the dimensions you pass to setPreferredSize(...).

EXAMPLE

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);
    }
}

OUTPUT

Unable to size JButton

EDIT

Instead of adding the components directly to the JFrame, add them to a JPanel, and then add the JPanel to the JFrame. Note that JPanel defaults to a flow layout.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜