有几次我因为建议使用以下方法而受到批评:
在Swing组件上.当我想在显示的组件之间定义比例时,我没有看到任何替代它们的用法.我被告知这个:
对于布局,答案总是相同的:使用合适的LayoutManager
我在网上搜索了一下,但我没有找到任何关于这个主题的综合分析.所以我有以下问题:
我总是在这个覆盖的站点中看到建议,getPreferredSize() 而不是setPreferredSize() 像以前的这些线程中所示那样使用.
看这个例子:
public class MyPanel extends JPanel{
private final Dimension dim = new Dimension(500,500);
@Override
public Dimension getPreferredSize(){
return new Dimension(dim);
}
public static void main(String args[]){
JComponent component = new MyPanel();
component.setPreferredSize(new Dimension(400,400));
System.out.println(component.getPreferredSize());
}
}
Run Code Online (Sandbox Code Playgroud)
setPreferredSize()
- 设置此组件的首选大小.
getPreferredSize()
- 如果preferredSize已设置为非null值,则返回它.如果UI委托的getPreferredSize方法返回非null值,则返回该值; 否则遵从组件的布局管理器.
所以这样做显然打破了Liskov替代原则.
prefferedSize是一个绑定属性,所以当你设置它时firePropertyChange执行.所以我的问题是,当你覆盖时,getPrefferedSize()你不需要覆盖setPreferredSize(..)吗?
例:
public class MyPanel extends JPanel{
private Dimension dim = null;
@Override
public Dimension …Run Code Online (Sandbox Code Playgroud) 我有一个扩展JComponent的自定义组件,它覆盖了方法paintComponent(Graphics g)但是当我尝试将它添加到我的JPanel时它只是不起作用,没有绘制任何东西.这是我的代码:
public class SimpleComponent extends JComponent{
int x, y, width, height;
public SimpleComponent(int x, int y, int width, int height){
this.x = x;
this.y = y;
}
@Override
public void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.BLACK);
g2.fillRect(x, y, width, height);
}
}
public class TestFrame{
public static void main(String[] args){
JFrame frame = new JFrame();
JPanel panel = new JPanel();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel.setPreferredSize(new Dimension(400, 400));
frame.add(panel);
frame.pack();
frame.setResizable(false);
SimpleComponent comp = new SimpleComponent(10, 10, 100, 100);
panel.add(comp);
frame.setVisible(true); …Run Code Online (Sandbox Code Playgroud) 这是我的代码
public class HomeTopPanel extends JPanel {
//BUTTONS
private final JButton myAccountButton = new JButton("My Account");
private final JButton updatePhoto = new JButton("Update Photo");
//PANELS
private final JPanel rightPanel_1 = new JPanel(new GridBagLayout());
private final JPanel rightPanel_2 = new JPanel(new GridBagLayout());
private final JPanel logHistoryPanel = new JPanel(new GridBagLayout());
//BORDERS
private final Border homeTopPanel_LineBorder = BorderFactory.createLineBorder(Color.BLACK, 1);
private final Border rightPanel1_LineBorder = BorderFactory.createLineBorder(Color.BLACK, 1);
private final Border rightPanel2_LineBorder = BorderFactory.createLineBorder(Color.BLACK, 1);
private final TitledBorder logHistoryPanel_TitledBorder = BorderFactory.createTitledBorder("Log History");
//LABELS
private …Run Code Online (Sandbox Code Playgroud)