我遇到的问题是我想制作一个通用的代码块。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);