如果在另一个JPanel中执行某些操作,如何更新JPanel的组件?

时间:2014-08-25 16:52:48

标签: java swing

如果在另一个JPanel中执行某项操作,我想更新JPanel

示例:
JPanel BorderLayout包含以下内容:

1。)类LabelPanel扩展JPanel并包含显示值的JLabel  2.)类ButtonPanel,其扩展JPanel并包含JButton

如果用户点击JButton,则JLabel的值应增加50。

JLabel应以某种方式被ActionListener调用JButton来调用。你怎么能这样做?

mainPanel中:

public class MainPanel extends JPanel {
   public MainPanel() {
      this.setLayout(new BorderLayout());

      this.add(new LabelPanel());
      this.add(new ButtonPanel());

   }
}

LabelPanel:

public class LabelPanel extends JPanel {
   public LabelPanel() {
      this.add(new JLabel("Value: " + 0));
   }
}

ButtonPanel:

public class ButtonPanel extends JPanel {
   public ButtonPanel() {
      this.add(new JButton());
   }
}

2 个答案:

答案 0 :(得分:0)

答案并不难。假设您的JButton被称为buttonJLabel被称为label,您可以这样做:

button.addActionListener((ActionEvent e) -> // register ActionListener
{
    int value = Integer.parseInt(label.getText()); // get current value of the label
    value += 50; // increase value by 50
    label.setText(Integer.toString(value)); // update text of the label
});

答案 1 :(得分:0)

您需要以下内容,

  

私人TextField tfCount; //声明组件TextField
  私人按钮btnCount; //声明组件按钮
  private int count = 0; //计数器的值

btnCount = new Button("Count");     // allocate Button instance
add(btnCount);                     // "this" Frame adds btnCount
btnCount.addActionListener(this);

 // ActionEvent handler - Called back when the button has been clicked.
   @Override
   public void actionPerformed(ActionEvent evt) {
      count = Integer.parseInt(tfInput.getText());
      count += 50;                     // incrase the counter value
      tfCount.setText(count + ""); // display on the TextField
                                   // setText() takes a String
   }