Button的ActionListener在不同的Class中?

时间:2015-03-20 13:10:05

标签: java swing actionlistener

我遇到了问题,我有5个课程。其中一个是MainGUI,另一个是带按钮的JPanel(但按钮不是来自JPanels类,而是来自第3,第4和第5类)和3个按钮类。 我不知道结构是否有点愚蠢(如果我错了,请纠正我,这只是为了体验) 所以这里最大的问题是我不能为每个Button使用ActionListeners。我想从另一个名为JPanelTime的类中更改(J)Textfield的文本 守则如下:

MainGUI.java

package view;
//Removed the javax.swing.*, etc imports because it's taking too much space

import listener.StartButton;

public class MainGUI{

private JFrame frame = new JFrame("Stoppuhr");


public static void main(String[] args) throws IOException{
    MainGUI gui = new MainGUI();
    gui.run();
}

public void run() throws IOException{
    frame.setSize(400, 500);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(new BorderLayout());

    JPanelTime timePanel = new JPanelTime();
    frame.add(timePanel.getGUI(), BorderLayout.NORTH);

    JPanelButtons buttonPanel = new JPanelButtons();
    frame.add(buttonPanel.getGUI(), BorderLayout.SOUTH);


    JPanelPicture picturePanel = new JPanelPicture();
    frame.add(picturePanel.getGUI(), BorderLayout.CENTER);
    frame.setVisible(true);

    }
}

JPanelButtons.java

package view;
//Same as above

import listener.MeantimeButton;
import listener.StartButton;
import listener.StopButton;

public class JPanelButtons extends JPanel{

private JPanel buttonPanel = new JPanel();

public JPanelButtons(){
    StartButton startButton = new StartButton();
    StopButton stopButton = new StopButton();
    MeantimeButton meantimeButton = new MeantimeButton();

    buttonPanel.setBorder(BorderFactory.createTitledBorder("Buttons"));
    buttonPanel.setLayout(new GridLayout(1,3));

    startButton.setText("Start");
    meantimeButton.setText("Zwischenzeit");
    stopButton.setText("Stopp");
    buttonPanel.add(startButton);
    buttonPanel.add(meantimeButton);
    buttonPanel.add(stopButton);
}


public JComponent getGUI(){
    return buttonPanel;
}
}

StartButton.java

package listener;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.JButton;

import view.MainGUI;

public class StartButton extends JButton implements ActionListener{


public StartButton() {
    JButton startButton = new JButton();
    startButton.addActionListener(this);
    startButton.setVisible(true);
}

@Override
public void actionPerformed(ActionEvent e) {
    Date now = new Date();
    SimpleDateFormat thisDate = new SimpleDateFormat("HH:mm:ss.SSS");
    String getDate = thisDate.format(now);

    }

}

任何帮助表示赞赏!在此先感谢:)

0 个答案:

没有答案