簡體   English   中英

如何使用JButton更改JPanel的背景顏色?

[英]How do I change the background color of a JPanel with a JButton?

我的程序中需要有三個按鈕(最后一個是退出按鈕,它已經起作用了),另外兩個需要在藍色和紅色之間更改JPanel背景的顏色。

我需要知道AtionListeners中的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);
    }
}
}

您不必為每個按鈕聲明一個偵聽器類,只需使用相同的監聽器類,然后添加if語句即可確定操作來自哪個按鈕。

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

您可以設置按鈕的父組件的背景色

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM