2017-09-23 139 views
0

我不知道如何解决这种情况: 我有一个带有JPanel的JFrame。我向这个JPanel添加了两个JButton。刷新JFrame? Java Swing

级的大型机

import java.awt.Color; 
import javax.swing.JFrame; 

public class MainFrame extends JFrame{ 
    public MainFrame(){ 
     this.setSize(100,100); 
     MainPanel panel = new MainPanel(); 
     this.add(panel); 
     this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     this.setVisible(true); 
    } 
} 

和mainPanel中有两个按钮

import java.awt.BorderLayout; 
import java.awt.Color; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import javax.swing.JButton; 
import javax.swing.JPanel; 

public class MainPanel extends JPanel implements ActionListener{ 
    JButton button, example; 

    public MainPanel(){ 
     this.setLayout(new BorderLayout()); 
     JButton button = new JButton("New"); 
     button.addActionListener(this); 
     JButton example = new JButton("example"); 
     this.add(button, BorderLayout.NORTH); 
     this.add(example, BorderLayout.CENTER); 
    } 
    @Override 
    public void actionPerformed(ActionEvent event) { 
     if (event.getSource().equals(button)){ 
      example.setEnabled(false); 
      example.setBackground(Color.yellow); 
     } 
    } 
} 

,并开始类主要

public class Main { 
    public static void main (String[] args){ 
     MainFrame frame = new MainFrame(); 
    } 
} 

我应该怎么做来改变背景颜色第二个按钮?

回答

1

你有你的按钮变量定义两次,一次作为一个实例变量,一次作为局部变量。

摆脱局部变量:

//JButton example = new JButton("example"); 
example = new JButton("example"); 

现在你的ActionListener代码引用实例变量。

-1

在您的例子:

JButton button, example; // <-- Here, you create your two (protected) variables 

public MainPanel(){ 
    this.setLayout(new BorderLayout()); 
    JButton button = new JButton("New"); // <-- And here, you create a local variable 
    button.addActionListener(this); 
    JButton example = new JButton("example"); // <-- Here, another local variable 
    this.add(button, BorderLayout.NORTH); 
    this.add(example, BorderLayout.CENTER); 
} 

@Override 
public void actionPerformed(ActionEvent event) { 
    if (event.getSource().equals(button)){ 
     example.setEnabled(false); 
     example.setBackground(Color.yellow); 
    } 
} 
+1

(1)这指出了问题可能是什么,但没有提供关于如何解决它的答案。在任何情况下,问题/解决方案早已提供。没有必要混乱与试图重复的答案论坛。 – camickr

+0

我有回答这个问题也许2分钟后,其他答案,所以我不知道比另一个答案 – 0ddlyoko