我是Java新手,我有一个问题。
我有一个扩展JPanel
的课程。它包含JButton
。如果我按下这个按钮,我想让另一个班级注意到这一点。通过这样做,我读过我必须使用Observer/Observable
。
唯一的问题是,我只能延长一次..有什么建议吗?
这两个类:
public class ControlsPanel extends JPanel{
private JButton start;
private JButton stop;
private int animationSpeed = 5;
private boolean startIsPressed;
private CashRegistersPanel cr_panel;
public ControlsPanel(final ParametersPanel panel) {
start = new JButton("Start");
stop = new JButton("Stop");
start.setFont(new Font("Arial", Font.BOLD, 14));
stop.setFont(new Font("Arial", Font.BOLD, 14));
this.setLayout(null);
this.setBackground(new Color(199,202,255));
this.add(start);
this.add(stop);
start.setBounds(10, 10, 280, 30);
stop.setBounds(10, 50, 280, 30);
stop.setEnabled(false);
start.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
if (start.getText().equals("Start")) {
start.setText("Pause");
stop.setEnabled(true);
startIsPressed = true;
}
}
});
//For the STOP BUTTON
stop.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (stop.isEnabled()) {
stop.setEnabled(false);
start.setText("Start");
startIsPressed = false;
}
}
});
}
public boolean StartisPressed() {
return startIsPressed;
}
}
和
public class CashRegistersPanel extends JPanel{
private Image img;
private int amount;
private ParametersPanel parametersPanel;
private ControlsPanel controlsPanel;
private boolean startIsPressed;
private CashRegister register;
private ArrayList<CashRegister> myRegister = new ArrayList<CashRegister>();
public CashRegistersPanel(ParametersPanel parametersPanel, ControlsPanel controlPanel) {
startIsPressed = controlsPanel.StartisPressed();
}
public void paintComponent(Graphics g) {
if (startIsPressed) {
Need to do the painting here
}
}
}
}
答案 0 :(得分:0)
您可以在类中实现ActionListener,假设MyPanel正在扩展JPanel。然后,您可以在按钮的ActionListener中传递MyPanel的对象。
class MyPanel extends JPanel implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
// Your Drawing Code
}
//your other jpanel code
}
创建自定义JPanel的对象
MyPanel myPanel1;
现在您可以将myPanel1对象作为按钮的ActionListener传递。
button.addActionListener(myPanel1);
答案 1 :(得分:0)
您应该向要监控的ActionListener
添加Jbutton
。
答案 2 :(得分:0)
不要扩展JPanel,你应该没有一个理由。现在,如果您希望其他类注意到您应该使用控制器作为MVC模式的排序版本。