Panel クラスをメイン クラスに配置できません。ボタンをインスタンス化して actionPerformed メソッドに登録できないようです。このプロジェクトは、9 つの入力ボタン (Enter、Space、および Clear 用の 3 つの他のボタン) を備えたグリッド レイアウトを使用することを想定しており、JTextArea に入力を表示します。Panel クラスは正しく設定されていると思いますが、JButton 配列をまとめて actionPerformed メソッドに登録するのに問題があります。任意のポインタをいただければ幸いです。(副次的な質問ですが、コードをすべてコード ブロックにまとめてコピー アンド ペーストするにはどうすればよいですか?)
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class TextButtons extends JFrame implements ActionListener {
private JButton[] buttons;
private JTextArea textArea;
private final int ENTER; //Index of Enter button in buttons
private final int SPACE; //Index of Space button in buttons
private final int CLEAR; //Index of Clear button in buttons
public TextButtons(String title) {
super(title);
JFrame frame = new JFrame("Text Button");
//TODO: instantiate all JButtons, add them to the buttons array,
// and register "this" as the ActionListener for each button.
for (int i = 0; i < buttons.length; i++) {
buttons[i] = new JButton();
//this.buttons.addActionListener(e);
}
ENTER = 9;
SPACE = 10;
CLEAR = 11;
buttons[ENTER] = new JButton("\n");
buttons[SPACE] = new JButton(" ");
buttons[CLEAR] = new JButton("clear");
JTextArea textArea = new JTextArea();
textArea.setEditable(false);
TextButtonsPanel mainPanel = new TextButtonsPanel(buttons, textArea);
this.getContentPane().add(mainPanel);
this.pack();
this.setVisible(true);
}
/* (non-Javadoc)
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
@Override
public void actionPerformed(ActionEvent e) {
// ??
}
public static void main(String[] args) {
final TextButtons f = new TextButtons("Text Buttons");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
PanelClass
public class TextButtonsPanel extends JPanel {
public TextButtonsPanel(JButton[] buttons, JTextArea textArea) {
int ENTER = 11;
JPanel mainPanel = new JPanel(new GridLayout(4, 3));
JButton b1 = new JButton("A");
JButton b2 = new JButton("B");
JButton b3 = new JButton("C");
JButton b4 = new JButton("1");
JButton b5 = new JButton("2");
JButton b6 = new JButton("3");
JButton b7 = new JButton("X");
JButton b8 = new JButton("Y");
JButton b9 = new JButton("Z");
add(b1);
mainPanel.add(b2);
mainPanel.add(b3);
mainPanel.add(b4);
mainPanel.add(b5);
mainPanel.add(b6);
mainPanel.add(b7);
mainPanel.add(b8);
mainPanel.add(b9);
JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setPreferredSize(new Dimension(80, 120));
mainPanel.add(scrollPane);
}
}
}