如何在Java中通过单击第二个JButton来更改一个JButton的文本
当我单击第二个如何在Java中通过单击第二个JButton来更改一个JButton的文本,java,swing,jbutton,Java,Swing,Jbutton,当我单击第二个JButton时,我想更改其中一个JButton的文本,但它什么也不做。我不知道是什么问题。 如果有人能尽快帮助我,我会非常感激并感谢他们的努力 public class myJPanel6 extends JPanel implements ActionListener { myJButton b1, b2; student st1; String s1; public myJPanel6() { setLayout(new GridLayout(1,1));
JButton
时,我想更改其中一个JButton
的文本,但它什么也不做。我不知道是什么问题。
如果有人能尽快帮助我,我会非常感激并感谢他们的努力
public class myJPanel6 extends JPanel implements ActionListener
{
myJButton b1, b2;
student st1;
String s1;
public myJPanel6()
{
setLayout(new GridLayout(1,1));
student st1 = new student("Michael", "Robinson", 20);
b1 = new myJButton(st1.getName());
b1.addActionListener(this);
add(b1);
b2 = new myJButton(st1.WhatIsUp());
b2.addActionListener(this);
add(b2);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == b1)
{
s1=st1.WhatIsUp();
b2.setText(s1);
}
}
实际上你有两个问题:
student
声明为局部变量,而其已定义为实例变量(阴影);您应该在案例中使用实例变量b2
已经具有WhatIsUp
值,因此不会有任何更改;您应该将其设置为name,以便能够更改按钮1的值。请查看我下面的示例以了解您的完整示例whatisUp()是一种方法,它有一个文本显示在按钮上,位于学生类中。若要更快获得更好的帮助,请发布一个或多个。再看一看。实际上,我希望当我点击第一个按钮时,第二个按钮上的文本在每次点击第一个按钮时都会发生变化。但是我的代码没有任何作用。我已经更新了您的代码,以便能够工作,请检查我答案中的代码。请接受此答案,如果您有其他疑问,请发布另一个问题。@Navedali:您可以通过单击左侧的来接受此答案。@Navedali:您不能继续问(扩展您的案例)这不好,不同的问题应该有不同的调查。
package a.b.c;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class myJPanel6 extends JPanel implements ActionListener {
JButton b1, b2;
student st1;
String s1;
public myJPanel6() {
setLayout(new GridLayout(1, 1));
st1 = new student("Michael", "Robinson", 20);
b1 = new JButton(st1.getName());
b1.addActionListener(this);
add(b1);
b2 = new JButton(st1.WhatIsUp());
b2.addActionListener(this);
add(b2);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == b1) {
s1 = st1.getName();
b2.setText(s1);
}
}
public static void main(String[] args) {
JFrame frm=new JFrame();
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myJPanel6 pnl=new myJPanel6();
frm.add(pnl);
frm.pack();
frm.setLocationRelativeTo(null);
frm.setVisible(true);
}
}