关于如何从已在另一个类上声明的已声明实例获取方法的想法是什么?
成长课程
public class Grow {
public static void main( String [] args ) {
JFrame frame = new JFrame();
final GrowPanel growPanel = new GrowPanel();
ButtonPanel btnPanel = new ButtonPanel();
frame.add( growPanel );
frame.add( btnPanel, BorderLayout.SOUTH);
frame.setSize( 400, 300 );
frame.setVisible( true );
}
}
ButtonPanel Class
public class ButtonPanel extends JPanel implements ActionListener{
JButton btn;
public ButtonPanel() {
btn = new JButton("Pause");
add(btn);
btn.addActionListener(this);
}
public void actionPerformed(ActionEvent e){
if( e.getActionCommand().equals("Pause")){
System.out.println("RESUME");
//growPanel.pause();
btn.setText("Resume");
} else {
System.out.println("PAUSE");
// growPanel.start();
btn.setText("Pause");
}
}
}
GrowPanel Class
class GrowPanel extends JComponent {
private int x;
private int y;
private Timer timer;
ButtonPanel b;
public GrowPanel() {
x = 10;
y = 10;
startPaiting();
}
public void startPaiting() {
timer = new Timer();
timer.schedule( new TimerTask(){
public void run(){
changeState();
repaint();
}
},0, 100 );
}
public void pause(){
timer.cancel();
startPaiting();
}
public void start(){
timer.cancel();
x = 10;
y = 10;
startPaiting();
}
public void paintComponent( Graphics g ){
g.fillOval( x, y, 10, 10 );
}
private void changeState(){
x+=10;
if( x >= 400 ) {
y+=10;
x = 0;
}
if( y >= 300 ){
y = 10;
}
}
}
我已经在Grow中宣布了一个新的GrowPanel实例。我只是不知道如何从ButtonPanel获取GrowPanel的方法而不在ButtonPanel中声明一个新的GrowPanel实例。这个想法甚至可能吗?到目前为止,我已经获得了一些可能有用的主题:Setters / getters,Singleton Pattern ......但到目前为止,这个想法一直难以捉摸。
答案 0 :(得分:1)
您不希望在按钮面板中使用GrowPanel的新实例。您希望使用与主框架使用的实例相同的实例。所以,只需将其传递给按钮面板:
ButtonPanel btnPanel = new ButtonPanel(growPanel);
...
public class ButtonPanel extends JPanel implements ActionListener{
private JButton btn;
private GrowPanel growPanel;
public ButtonPanel(GrowPanel growPanel) {
this.growPanel = growPanel;
}
...
}