如果在另一个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());
}
}
答案 0 :(得分:0)
答案并不难。假设您的JButton
被称为button
而JLabel
被称为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
}