JAVA入門のボタンサンプル
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ButtonDemo extends JFrame {
// Create a panel for displaying message
protected MessagePanel messagePanel = new MessagePanel(“Welcome to C++");
// Declare two buttons to move the message left and right
private JButton jbtLeft = new JButton(“<=");
private JButton jbtRight = new JButton(“=>");
public ButtonDemo() {
// Set the background color of mesaagePanel
messagePanel.setBackground(Color.WHITE);
// Create panel buttonPanel to hold two buttons “<=" and “=>"
JPanel buttonPanel = new JPanel();
buttonPanel.add(jbtLeft);
buttonPanel.add(jbtRight);
// Place panels in the frame
add(messagePanel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
// Set keyboard Mnemonics
jbtLeft.setMnemonic('L’); // ホットキーを設定 Altキーとホットキーを押しながらホットキーを設定
jbtRight.setMnemonic('R’);
// Register listeners with the buttons
jbtLeft.addActionListener(new ButtonActionListener());
jbtRight.addActionListener(new ButtonActionListener());
//Set icons and remove text
// jbtLeft.setIcon(new ImageIcon(“image/left.gif"));
// jbtRight.setIcon(new ImageIcon(“image/right.gif"));
// jbtLeft.setText(null);
// jbtRight.setText(null);
// Set tool tip text on the button
jbtLeft.setToolTipText(“Move message to left");
jbtRight.setToolTipText(“Move message to right");
}
class ButtonActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if(e.getSource() == jbtLeft)
messagePanel.moveLeft();
else if(e.getSource() == jbtRight)
messagePanel.moveRight();
messagePanel.repaint();
}
}
public static void main(String[] args) {
ButtonDemo frame = new ButtonDemo();
frame.setTitle(“ButtonDemo");
frame.setSize(300, 200);
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}