Overriding setPreferredSize() and getPreferredSize()

情到浓时终转凉″ 提交于 2020-01-17 07:05:10

问题


Due to the answers I have received I am now doing this a different way.

Is there any way to override setPreferredSize() and getPreferredSize() so it will actually set the size of the component to a number higher than was actually input, and get a number that is a number lower than it actually is?

Here I am overriding both methods to set the size of a panel to 100 pixels more than what I actually put in setPreferredSize() and if I were to get the preferred size, I would like it to return what I put in setPreferredSize()

I am suspecting that Swing uses getPreferredSize() to set the size, so is there another method I can override to achieve this or am I stuck having to make another method to return the values I want?

import java.awt.*;
import java.beans.Transient;
import javax.swing.*;

public class PreferredSize extends JPanel{

public static void main(String[] args) {
    JPanel background = new JPanel();

    PreferredSize ps = new PreferredSize();
    ps.setPreferredSize(new Dimension(200, 200));
    ps.setBackground(Color.CYAN);

    JPanel panel = new JPanel();
    panel.setBackground(Color.BLUE);
    panel.setPreferredSize(new Dimension(200, 200));


    background.add(ps);
    background.add(panel);

    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setContentPane(background);
    f.pack();
    f.setLocationRelativeTo(null);
    f.setVisible(true);
}


@Override
public void setPreferredSize(Dimension preferredSize) {
    super.setPreferredSize(new Dimension(preferredSize.width+100, preferredSize.height+100));
}

@Override
@Transient
public Dimension getPreferredSize() {
    return new Dimension(super.getPreferredSize().width-100, super.getPreferredSize().height-100);
}
}

Thanks.


回答1:


The problem you're facing is the fact that preferred size is only a guide that CAN be used by the layout managers to make decisions about how a component should be laid out. It's perfectly reasonable for a layout manager to ignore these hints.

In the case of ip your example;

  1. The default size of a JPanel is 0x0, so by the time you've added in and subtracted the 100 pixels, its now 0x0 again.
  2. The default layout manager for a JFrame is BorderLayout, which will ignore the preferred size if its available size is larger or smaller then that specified by preferred size

The real question is, what are your actually trying to achieve?



来源:https://stackoverflow.com/questions/15308487/overriding-setpreferredsize-and-getpreferredsize

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!