簡體   English   中英

按下時我無法更改JButton的顏色

[英]I can't change the color of a JButton when pressed

我擁有所有需要的導入,沒有錯誤,但無法正常工作。

    final JButton button_32 = new JButton("2");
    button_32.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            button_32.setBackground(Color.red);
        }
    });
    button_32.setBounds(0, 57, 33, 29);
    contentPane.add(button_32);

我認為這可能與“抽象類的實現”有關。 嘗試這個:

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.JFrame;


public class ExamButton extends JFrame {

    JButton button_32 = new JButton("ssf");
    JFrame frame = new JFrame();

    public ExamButton() {

        final JButton button_32 = new JButton("2");
        button_32.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                button_32.setBackground(Color.red);
            }
        });
        button_32.setBounds(0, 57, 33, 29);

        add(button_32, BorderLayout.CENTER);
        setSize(300, 300);
        setVisible(true);

    }

    public static void main(String[] args) {
        new ExamButton();
    }

}

您可以創建自己的Button,該按鈕可以擴展ButtonModel或按照此處的建議進行操作。

public class Main {

  static JFrame frame;

  public static void main(String[] args)
  {
    // schedule this for the event dispatch thread (edt)
    SwingUtilities.invokeLater(new Runnable()
    {
      public void run()
      {
        displayJFrame();
      }
    });
  }
  static void displayJFrame()
  {
    frame = new JFrame("Our JButton listener example");

    // create our jbutton
    final JButton showDialogButton = new JButton("Click Me");

    // add the listener to the jbutton to handle the "pressed" event
    showDialogButton.addActionListener(new ActionListener()
    {
      public void actionPerformed(ActionEvent e)
      {
        // when the button is pressed

          showDialogButton.setBackground(Color.RED);
      }
    });

    // put the button on the frame
    frame.getContentPane().setLayout(new FlowLayout());
    frame.add(showDialogButton);

    // set up the jframe, then display it
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.setPreferredSize(new Dimension(300, 200));
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  }

}

暫無
暫無

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

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