2017-05-10 2 views
0

모든 가져 오기가 필요하며 오류는 없지만 작동하지는 않습니다.눌렀을 때 JButton의 색상을 변경할 수 없습니다.

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

답변

0

"추상 클래스의 구현"과 관련 될 수 있다고 생각합니다. 이 시도 :

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

} 
0

당신은 ButtonModel에를 확장하거나 그것을 자신의 버튼을 만들 수 있습니다, here을 제안한다.

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

}

관련 문제