2016-05-24 9 views
0

私はこのプログラムを自分のパネルに追加しましたが、私はボタンを動作させるためにactionListenerを使用することができません。それらはパネルに貼り付けられた写真でなければならず、ボタンがクリックされると、画像は別の画像に変わるはずです。ありがとう!ここに私のコードです。シンプルなGUIプログラム

あなたがそうのように、ボタンにActionListenerを追加する必要が
import javax.swing.*; 
import java.awt.*; 
import java.awt.event.*; 

public class DrawPanelThree extends JPanel 
{ 
    private JButton button; 

    public DrawPanelThree() 
    { 
     button = new JButton(); 
     setLayout(new BorderLayout()); 
     add(button, BorderLayout.SOUTH); 
     button.setText("Start"); 
    } 

    protected void paintComponent(Graphics g) 
    { 
     super.paintComponent(g); 
     g.drawRect(90, 40, 100, 50); 
     g.setColor(Color.RED); 
     g.fillRect(10, 10, 10, 10); 
     g.fillRect(260, 10, 10, 10); 
     g.fillRect(10, 120, 10, 10); 
     g.fillRect(260, 120, 10, 10); 
     g.setColor(new Color(255, 215, 0)); 
     g.fillOval(120, 45, 40, 40); 
    } 

    public static void main(String[] args) 
    { 
     JFrame frame = new JFrame(); 
     frame.setTitle("Rectangle"); 
     frame.setSize(new Dimension(300, 200)); 
     frame.setLocationRelativeTo(null); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

     DrawPanelThree panel = new DrawPanelThree(); 
     frame.add(panel); 
     panel.setBackground(Color.CYAN); 

     frame.setVisible(true); 
    } 

    private class ButtonListener implements ActionListener 
    { 
     public void actionPerformed(ActionEvent event) 
     { 

     } 
    } 
} 

答えて

2

button.addActionListener(new MyCoolActionListener()); 

あなたはそれを宣言するときには、また、ActionListenerを定義することができ、それが一般的な考え方です。コンストラクタでJButtonを宣言した直後にActionListenerを追加したいとします。

希望すると便利です。

関連する問題