【发布时间】:2013-11-08 19:18:52
【问题描述】:
我的问题是我想制作一个通用的代码块。 getHalfDotTime 方法和 getHalfTime 方法是许多类似方法中的两种。
我不想为每个方法都创建一个新的 ActionListener,而是想在 commonFormatting 方法中创建 ActionListener。
当我这样做时遇到的问题是,Declarations.halfDotTime 双变量不能包含为例如本地双变量。
我想要 double currentTitle = Declarations.halfDotTime 然后在 ActionListener setText 到 currentTitle。产生的这个问题是,当程序运行时,它将当前标题设置为 INIT 值 0,然后在按下按钮时保持为 0。
private static void gethalfDotTime(JButton tapButton, JPanel contentPane) {
final JLabel currentLabel = new JLabel("0ms");
currentLabel.setBounds(119, 185, 120, 16);
tapButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
currentLabel.setText(Declarations.threeDecimals.format(Declarations.halfDotTime) + "ms");
}
});
commonFormatting(tapButton, contentPane, currentLabel);
}
private static void gethalfTime(JButton tapButton, JPanel contentPane) {
final JLabel currentLabel = new JLabel("0ms");
currentLabel.setBounds(119, 185, 120, 16);
tapButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
currentLabel.setText(Declarations.threeDecimals.format(Declarations.halfTime) + "ms");
}
});
commonFormatting(contentPane, currentLabel);
}
//MANY MORE SIMILAR METHODS ALL CALLING COMMON FORMATTING.
private static void commonFormatting(JPanel contentPane, final JLabel currentLabel) {
currentLabel.setHorizontalAlignment(SwingConstants.RIGHT);
currentLabel.setForeground(new Color(255, 255, 255));
currentLabel.setFont(new Font("Letter Gothic Std", Font.BOLD, 14));
contentPane.add(currentLabel);
【问题讨论】:
-
这个问题似乎是题外话,因为它是关于审查代码,因此应该在Code Review
-
这不是评论,而是问题。我现在已经解决了它,如果它被解锁,我会发布解决方案。我也改写了这个问题,因为它一团糟!我向所有人道歉!
-
当然,经过您的编辑,它看起来会更好。在你看起来真的想改进你的代码风格之前。
标签: java oop polymorphism double encapsulation