2017-07-01 24 views
0

ボタンをクリックすると、ボタンがコンソールに印刷されます。ここに私のコードです。私はこのコードを使って基本的なアプリを作ろうと思っていましたが、ボタンをどのように動作させるのかと思っていました。初めて、初めてコンソールを使い始めましたが、後で画像を表示する可能性がありますか?ボタンにアクションを追加するにはどうすればよいですか?

/** 
* @param args 
*/ 


public static void main(String[] args) { 
    // TODO Auto-generated method stub 

    JFrame frame = new JFrame("GUI"); 
    frame.setSize(320, 300); 
    frame.setBackground(Color.WHITE); 
    frame.setVisible(true); 


    JPanel panel = new JPanel(); 
    panel.setSize(50,50); 

    JLabel label = new JLabel(); 
    frame.add(panel); 
    panel.add(label); 

    label.setText("Welcome to Team 1389!"); 

    Container contentPane = getContentPane(); 
    contentPane.setBackground(Color.blue); 

    contentPane.setLayout(new FlowLayout()); 

    JButton button = new JButton("MATCHES"); 
    button.setSize(100, 30); 
    button.setLocation(95, 45); 
    button.addActionListener(null); 
    button.setVisible(true); 

    frame.add(button); 

    JButton button2 = new JButton("PIT TEAM"); 
    button2.setSize(100, 30); 
    button2.setLocation(95, 100); 
    button2.setVisible(true); 
    frame.add(button2); 

    JButton button3 = new JButton("SCOUTING"); 
    button3.setSize(100, 30); 
    button3.setLocation(95, 150); 
    button3.setVisible(true); 
    frame.add(button3); 



} 

private static Container getContentPane() { 
    // TODO Auto-generated method stub 
    return null; 
} 

}

`

+2

:別途、あなたがそうすることを望むならば、それを追加する前に

button.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent event){ //do stuff.. } }); 

あなたはまた、リスナーを作成することができます:あなたはイベントが処理された未実装のメソッドを追加する必要がありますので、彼らインターフェイスですこの種のもののための公式のチュートリアルです。 http://docs.oracle.com/javase/tutorial/uiswing/components/button.html – Radiodef

答えて

1

は、OracleのWebサイト上でこのtutorialを見ることができ、それがうまく物事を説明します

ActionListenerを使用してください。そこ

ActionListener listener = new ActionListener(){ 

      @Override 
      public void actionPerformed(ActionEvent event){ 
       //do stuff.. 
      } 

}; 

button.addActionListener(listener); 
関連する問題