我有下面的代码;我希望它还希望将鼠标悬停在“执行的操作”中的代码发生。不用再把代码复制粘贴,次数翻倍,有没有办法轻松设置?
代码:
private void btnGreenActionPerformed(java.awt.event.ActionEvent evt) {
Color btnGrn = new Color(159, 191, 143); //Sets the colour to a class
Color txtGrn = new Color(201, 255, 191); //Sets the colour to a class
Color txtGry = new Color(89, 89, 89); //Sets the colour to a class
this.getContentPane().setBackground(new java.awt.Color(127,191,95)); //Sets background color to green
btnConvert.setBackground(btnGrn); //Changes the colors to green
btnReset.setBackground(btnGrn); //Changes the colors to green
btnClose.setBackground(btnGrn); //Changes the colors to green
btnInfo.setBackground(btnGrn); //Changes the colors to green
txtIncome.setBackground(txtGrn); //Changes the colors to green
txtPayable.setBackground(txtGrn); //Changes the colors to green
txtStatus.setBackground(txtGrn); //Changes the colors to green
txtIncome.setForeground(txtGry); //Changes the colors to grey
txtPayable.setForeground(txtGry); //Changes the colors to grey
txtStatus.setForeground(txtGry); //Changes the colors to grey
}
注意:我有 7 个按钮,除了颜色值之外,其他按钮都相同。
最佳答案
我会向您的面板类添加一个内部类,以管理颜色,然后根据您的配色方案创建尽可能多的实例,包括您喜欢的任何颜色。像这样的东西。
顺便说一句,这一切都在您的面板类中。我并没有将其设想为它自己的 .java
文件中的独立类;因为它完全与面板的特性有关。一个更可重用的版本看起来会有点不同。
private class ButtonColorScheme {
final Color paneBackground;
final Color buttonBackground;
final Color textBackground;
final Color textForeground;
ButtonColorScheme(Color paneBackground, Color buttonBackground, Color textBackground, Color textForeground) {
this.paneBackground = paneBackground;
this.buttonBackground = buttonBackground;
this.textBackground = textBackground;
this.textForeground = textForeground;
}
void apply() {
getContentPane().setBackground(paneBackground);
btnConvert.setBackground(buttonBackground);
btnReset.setBackground(buttonBackground);
btnClose.setBackground(buttonBackground);
btnInfo.setBackground(buttonBackground);
txtIncome.setBackground(textBackground);
txtPayable.setBackground(textBackground);
txtStatus.setBackground(textBackground);
txtIncome.setForeground(textForeground);
txtPayable.setForeground(textForeground);
txtStatus.setForeground(textForeground);
}
}
private final ButtonColorScheme greenAndGrey = new ButtonColorScheme(
new Color(127,191,95), new Color(159, 191, 143), new Color(201, 255, 191), new Color(89, 89, 89));
private final ButtonColorScheme redAndBlack = new ButtonColorScheme(
new Color(191,120,95), new Color(202, 160, 143), new Color(255, 180, 191), Color.BLACK);
public void btnGreenActionPerformed(ActionEvent evt){
greenAndGrey.apply();
}
public void btnRedActionPerformed(ActionEvent evt){
redAndBlack.apply();
}
关于java - 如何简单地复制我的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22054966/