【问题标题】:How do I change the background color of a JPanel with a JButton?如何使用 JButton 更改 JPanel 的背景颜色?
【发布时间】:2014-05-28 21:08:30
【问题描述】:

我的程序中需要三个按钮(最后一个是退出按钮,它已经可以使用)另外两个需要在蓝色和红色之间更改JPanel 背景的颜色。

我需要知道AtionListeners 中的内容,以便在按下按钮时更改背景颜色。

这是目前为止的课程:

package myPackageNameGoesHere;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JPanel;

public class EventPanel extends JPanel {
private static final long serialVersionUID = 123796234;

private JButton blueButton;
private JButton redButton;
private JButton exitButton;

public EventPanel() {
    this.setPreferredSize(new Dimension(200, 300));

    this.blueButton = new JButton("Blue");
    this.add(this.blueButton);

    this.redButton = new JButton("Red");
    this.add(this.redButton);

    this.exitButton = new JButton("Exit");
    this.exitButton.addActionListener(new ExitListener());
    this.add(this.exitButton);
}

private class BlueListener implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent blue) {
        // What goes here?????

    }
}

private class RedListener implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent red) {
        // What goes here????

    }
}
private class ExitListener implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent exit) {
        System.exit(0);
    }
}
}

【问题讨论】:

标签: java swing jpanel jbutton actionlistener


【解决方案1】:

您不必为每个按钮声明一个侦听器类,您可以使用相同的侦听器类并添加 if 语句来确定操作来自哪个按钮。

if (e.getSource() == blueButton) {// e is the ActionEvent
    blueButton.getParent().setBackground(Color.BLUE);
} else if(e.getSource() == redButton) {
    redButton.getParent().setBackground(Color.RED);
}

【讨论】:

    【解决方案2】:

    您可以设置按钮父组件的背景颜色

    Component component = (Component) event.getSource();
    component.getParent().setBackground(Color.BLUE);
    

    【讨论】:

      猜你喜欢
      • 2014-05-11
      • 1970-01-01
      • 2011-01-28
      • 2016-05-08
      • 1970-01-01
      • 2012-01-05
      • 1970-01-01
      • 2020-12-06
      • 2015-05-07
      相关资源
      最近更新 更多