JButton如何控制它的大小? [英] How does JButton control it's size?

查看:138
本文介绍了JButton如何控制它的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在框架上添加了一个按钮,并使用计时器控制其文本和/或最小尺寸.

I have added a button to a frame and controlling it's text and/or minimum size with timer.

我注意到,该按钮有时会增大,有时却不会增大.

I noticed, that button does grow sometimes, and sometimes does not.

如果采用null布局,则它将忽略文本和最小宽度更改.

If in null layout, then it ignores both text and minimum width changing.

如果采用FlowLayout布局,则在更改文本时会增大,但会忽略最小宽度的变化.

If in FlowLayout layout, then it grows if text changing, but ignores minimum width changing.

在后一种情况下如何使其生长?如果最小宽度发生变化,那么布局管理器为什么不调整按钮形状?如何迫使它重塑?

How make it grow in latter case? If minimum width changes, then why doesn't layout manager reshapes button? How to force it to reshape?

注意:下面的代码是SSCCE,即用于调查目的.

Note: code below is SSCCE, i.e. it is for investigation purposes.

public class Try_ButtonAutoresize_01 {

    private static final Logger log = LoggerFactory.getLogger(Try_ButtonAutoresize_01.class);

    private static final String text = "Very Long Text For Appear On Button ";
    private static int position = 7;

    public static void main(String[] args) {

        final JButton button = new JButton(text.substring(0, position));
        button.setBounds(10, 10, 100, 50);

        JFrame frame = new JFrame();
        //frame.setLayout(null);
        frame.setLayout(new FlowLayout(FlowLayout.LEFT));
        frame.add(button);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocation(100,100);
        frame.setSize(640, 480);
        frame.setVisible(true);

        new Timer(1000, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {


                /*
                button.setText(button.getText() + text.charAt(position));

                position++;
                if( position >= text.length() ) {
                    position=0;
                }
                */


                button.setMinimumSize(new Dimension((int)button.getMinimumSize().getWidth()+10, (int)button.getMinimumSize().getHeight()));

                log.info("Minimum width is now = {}", button.getMinimumSize().getWidth());
            }
        }).start();

    }

}

更新

它也不适合首选尺寸.无效也无济于事.

It does not work with preferred size too. Invalidation also does not help.

public class Try_ButtonAutoresize_01 {

    private static final Logger log = LoggerFactory.getLogger(Try_ButtonAutoresize_01.class);

    private static final String text = "Very Long Text For Appear On Button ";
    private static int position = 7;

    public static void main(String[] args) {

        final JButton button = new JButton(text.substring(0, position));
        button.setBounds(10, 10, 100, 50);

        final JFrame frame = new JFrame();
        //frame.setLayout(null);
        frame.setLayout(new FlowLayout(FlowLayout.LEFT));
        frame.add(button);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocation(100,100);
        frame.setSize(640, 480);
        frame.setVisible(true);

        new Timer(1000, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {


                /*
                button.setText(button.getText() + text.charAt(position));

                position++;
                if( position >= text.length() ) {
                    position=0;
                }
                */


                //button.setMinimumSize(new Dimension((int)button.getMinimumSize().getWidth()+10, (int)button.getMinimumSize().getHeight()));
                button.setPreferredSize(new Dimension((int)button.getPreferredSize().getWidth()+10, (int)button.getPreferredSize().getHeight()));

                //frame.invalidate();
                //button.invalidate();

                log.info("Minimum width is now = {}", button.getMinimumSize().getWidth());
                log.info("Preferred width is now = {}", button.getPreferredSize().getWidth());
            }
        }).start();

    }

}

更新2

答案需要两个条件:

1)使用setPreferredSize()作为@Sage建议,并且

1) use setPreferredSize() as @Sage suggested, and

2)调用revalidate()(我在setText()源代码中看到的内容).

2) call revalidate() (what I saw in setText() source code).

最终的工作代码如下:

public class Try_ButtonAutoresize_02 {

    private static final Logger log = LoggerFactory.getLogger(Try_ButtonAutoresize_02.class);

    public static void main(String[] args) {

        final JButton button = new JButton("short");

        final JFrame frame = new JFrame();
        frame.setLayout(new FlowLayout(FlowLayout.LEFT));
        frame.add(button);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocation(100,100);
        frame.setSize(640, 480);
        frame.setVisible(true);

        new Timer(1000, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {


                //button.setMinimumSize(new Dimension((int)button.getMinimumSize().getWidth()+10, (int)button.getMinimumSize().getHeight()));
                button.setPreferredSize(new Dimension((int)button.getPreferredSize().getWidth()+10, (int)button.getPreferredSize().getHeight()));

                button.revalidate();

                log.info("Preferred width is now = {}", button.getPreferredSize().getWidth());


            }
        }).start();

    }

}

推荐答案

  1. 不要采用第一种方法:null layout(AbsoluteLayout)即使有人威胁到您死刑.
  2. 使用FlowLayout的第二种方法:您可能已经知道这是一个LayoutManager.但是,此布局管理器尊重组件的首选大小.因此,通过设置bounds:setBounds(x, y, width, height)给出大小提示将无效.使用button.setPreferredSize(Dimension)可获得快速结果.但是,您实际上应该再次扩展该类,并覆盖getPreferredSize(Dimension)和其他getXXXSize(Dimension)方法以根据内容大小进行调整.

  1. Don't go with first approach: null layout(AbsoluteLayout) even if someone threaten you to life death.
  2. Second approach with FlowLayout: It is a LayoutManager as you might already know. However, this layout manager respects preferred size of a component. So giving size hints by setting bounds:setBounds(x, y, width, height) won't have effect. Use button.setPreferredSize(Dimension) to have a quick result. But again you should actually extend the class and override the getPreferredSize(Dimension) and other getXXXSize(Dimension) method to adjust with the content size.

 JButton button = new JButton("Press Me"){
    @Override
    public Dimension getPreferredSize() {
        Dimension size = new Dimension();
        size.width = ???; // give some thinking about it
        size.height = ???; // give some thinking about it
        return size;
    }

 };

  • 正如@mKobel在下面指出的那样,我忘记了要解决的问题:不要将大小设置为JFrame.它减少了布局管理员正确布局的机会.在JFrame.setVisible(true)之前先呼叫JFrame.pack().

  • As @mKobel has pointed out below, which i have forgotten to address: do not set size to JFrame. It reduce the chance for layout managers to layout properly. Call JFrame.pack() before JFrame.setVisible(true) instead.

    在本教程页面中查看详细信息:

    1. 如何使用FlowLayout
    2. 解决常见的布局问题
    1. How to use FlowLayout
    2. Solving Common Layout Problems

    这篇关于JButton如何控制它的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆