繁体   English   中英

刷新JFrame? Java秋千

[英]Refresh JFrame? Java Swing

我不知道如何解决这种情况:我有一个带有JPanel的JFrame。 我在此JPanel中添加了两个JButton。

类MainFrame

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();
    }
}

我该怎么做才能改变背景颜色的第二个按钮?

您有两次定义按钮变量,一次定义为实例变量,一次定义为局部变量。

摆脱局部变量:

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

现在,您的ActionListener代码可以引用实例变量。

在您的示例中:

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);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM