البرمجة

تغيير نص الزر باستخدام Java

It looks like there might be a couple of issues in your code. Let’s try to fix them:

  1. The ActionListener interface is misspelled in your class declaration. It should be ActionListener instead of ActionListene.
  2. You’re redeclaring student st1 inside the constructor, which hides the class-level st1 variable. Remove the student type from the declaration inside the constructor.
  3. Make sure that the WhatIsUp() method of the student class returns a String value that you want to set as the text of b2.

Here’s the corrected code:

java
import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class myJPanel6 extends JPanel implements ActionListener { myJButton b1, b2; student st1; String s1; public myJPanel6() { setLayout(new GridLayout(1, 1)); st1 = new student("Michael", "Robinson", 20); b1 = new myJButton(st1.getName()); b1.addActionListener(this); add(b1); b2 = new myJButton("Button 2"); b2.addActionListener(this); add(b2); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == b2) { s1 = st1.WhatIsUp(); b1.setText(s1); } } public static void main(String[] args) { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(new myJPanel6()); frame.pack(); frame.setVisible(true); } }

Make sure that the student class has a method WhatIsUp() that returns a String. If there are still issues, please provide more details or the student class definition for further assistance.

المزيد من المعلومات

بالتأكيد، يمكنني تزويدك بمزيد من المعلومات حول كيفية تغيير نص زر واحد عند النقر على زر آخر في Java.

لتغيير نص الزر، يجب عليك الوصول إلى كائن الزر الذي تريد تغيير نصه واستخدام الدالة setText لتغيير النص. في حالتك، تريد تغيير نص b1 عند النقر على زر b2. لذلك، يجب عليك التعديل على طريقة actionPerformed كما يلي:

java
@Override public void actionPerformed(ActionEvent e) { if (e.getSource() == b2) { s1 = st1.WhatIsUp(); b1.setText(s1); } }

هذا الشرط if (e.getSource() == b2) يتحقق مما إذا كان الحدث المنشأ (e.getSource()) هو زر b2. إذا كان الأمر كذلك، يتم استدعاء st1.WhatIsUp() للحصول على النص الجديد ومن ثم يتم تعيينه كنص لزر b1 باستخدام b1.setText(s1).

يُفترض أن تعمل هذه الطريقة بشكل صحيح، ولكن إذا كان لديك مشكلة محددة، يرجى تقديم مزيد من التفاصيل حتى أتمكن من مساعدتك بشكل أفضل.

زر الذهاب إلى الأعلى