【发布时间】:2013-05-07 14:16:26
【问题描述】:
我正在尝试装饰 JLabel,但我设置的礼仪不起作用。
装饰器类:
public class Decorator extends JComponent{
public Decorator(JComponent c){
setLayout(new BorderLayout());
add("Center",c);}
}
PlayLabel 类:
public class PlayLabel extends Decorator{
JComponent thisComp;
public PlayLabel(JComponent c){
super(c);
thisComp=this;
LineBorder line = new LineBorder(new Color(36,77,240), 2, true);
thisComp.setAlignmentX(Component.CENTER_ALIGNMENT);
thisComp.setBackground(new Color(36,77,240));
thisComp.setMaximumSize(new Dimension(150,75));
thisComp.setForeground(Color.WHITE);
thisComp.setOpaque(true);
thisComp.setFont(new Font("Times New Roman",Font.BOLD,35));
//thisComp.setHorizontalAlignment(SwingConstants.CENTER);
thisComp.setBorder(line);
c.addMouseListener(new MouseListener() {
@Override
public void mouseEntered(java.awt.event.MouseEvent evt) {
thisComp.setBackground(new Color(96,125,244));
}
@Override
public void mouseExited(java.awt.event.MouseEvent evt) {
thisComp.setBackground(new Color(36,77,240));
}
});
}
}
我在jFrame 中有一个JPanel,我在其中添加PlayLabel,如下所示:
panel.add(new PlayLabel(new JLabel("PLAY")));
这些属性不适用于我创建的 PlayLabel:
thisComp.setAlignmentX(Component.CENTER_ALIGNMENT);
thisComp.setBackground(new Color(36,77,240));
thisComp.setMaximumSize(new Dimension(150,75));
thisComp.setForeground(Color.WHITE);
thisComp.setFont(new Font("Times New Roman",Font.BOLD,35));
我做错了什么?
【问题讨论】:
-
旁注:您不希望
PlayLabel在其构造函数中使用JLabel吗?我看不出灵活并接受JComponent会带来什么。 -
您是否测试过这些属性在不使用装饰的情况下“按预期”工作? IE。手动将它们应用到普通的
JLabel? -
我在没有装饰器的情况下测试了属性,它们在普通的 jLabel 上工作
-
如需尽快获得更好的帮助,请发帖SSCCE。
-
add("Center",c);- 这不是在将组件添加到面板时指定约束的方法。阅读 Container API 以找到合适的方法。另外,不要对值进行硬编码。每个布局管理器都为允许的约束提供静态变量。
标签: java swing decorator jlabel