2 つのオブジェクトを持つサンプル コードを次に示します。パネルとリスナーを簡単に作成するためのパネル オブジェクトと、コードを実行するためのフレーム オブジェクト。意図は、回答テキストフィールドで押されたボタンを表示するコードを取得することです。ただし、回答テキストを作成する場所はどこでも、必要な他のものの範囲外であるため、コンパイルする方法がわかりません。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class myPanel extends JPanel implements ActionListener {
public myPanel(int start, int numOfButtons){
setLayout(new FlowLayout(FlowLayout.LEFT, 10, 20));
JButton buttons[] = new JButton[numOfButtons];
for (int k = start; k < start + numOfButtons; k++){
buttons[ k ] = new JButton("Button " + k);
this.add( buttons[k] );
buttons[ k ].addActionListener(this);
}
}
public void actionPerformed(ActionEvent e)
{
myFrame.setText(e.getActionCommand());
}
}
public class myFrame extends JFrame{
public myFrame()
{
super("myFrame");
myPanel buttonPanel1 = new myPanel(1, 3);
myPanel buttonPanel2 = new myPanel(4, 3);
JPanel answerPanel = new JPanel();
JTextField answertext;
answertext = new JTextField(10);
answertext.setEditable(false);
answerPanel.add(answertext);
setSize(300,200);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout( new GridLayout(3,1) );
setTitle("ShowPressedButton");
add(buttonPanel1);
add(answerPanel);
add(buttonPanel2);
pack();
setVisible(true);
}
public void setText(string input)
{
answertext = input;
}
public static void main(String[] args) {
myFrame showButton = new myFrame();
showButton.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
}
mypanel が回答テキストを設定できるように、パブリック メソッドを設定して回答テキストを設定しましたが、コンパイラは、コンパイルしようとするとそのメソッドが見つからないと言います