首先我有一个GUI(gui1),当我按下一个按钮时,会创建一个不同的GUI(gui2)。我的问题是:如何使用gui1中的方法访问gui2中的元素?
示例:当我按下gui1中的按钮时,我希望QuesHandText.setText(myVector[0]);
QuesHandText
是来自gui1的JTextField
和myVector[0]
来自gui2的变量。结果错误消息:线程“AWT-EventQueue-0”中的异常java.lang.NullPointerException
当我从Gui2按Ok时,我想在Gui1上为JTextField设置setText http://img72.imageshack.us/img72/2822/36185233.png
//imports
public class Gui extends JFrame{
public JButton Simulate, Particular, Start, HandSelection;
public JTextField QuesHandText, FlopTurnRiverText, RezultatText;
public Gui g;
public Gui()
{
QuesHandText = new JTextField(4);
//instruct
ClassParticular handler1 = new ClassParticular();
Particular.addActionListener(handler1);
}
public Gui(String t)
{
//instruct
myVector[0]="some_string";
myVector[1]="some_string2";
}
public class ClassParticular implements ActionListener{
public void actionPerformed(ActionEvent event){
//instruc
HandSelection hs = new HandSelection();
HandSelection.addActionListener(hs);
StartClass hndlr = new StartClass();
Start.addActionListener(hndlr);
add(HandSelection);
add(Start);
}
}
public class HandSelection implements ActionListener{
public void actionPerformed(ActionEvent e){
g = new Gui("Hand selection");
g.setVisible(true);
g.setSize(1135,535);
g.setDefaultCloseOperation(HIDE_ON_CLOSE);
g.setResizable(false);
}
}
public class StartClass implements ActionListener{
public void actionPerformed(ActionEvent event){
QuesHandText.setText(myVector[0]); // THE PROBLEM IS HERE, I KNOW IT !!
}
}
}
答案 0 :(得分:4)
1.你的问题是
public class Gui extends Jframe{
应该是
public class Gui extends JFrame{
2.其他问题
public JButton Simulate, Particular, Start, HandSelection;
public JTextField QuesHandText, FlopTurnRiverText, RezultatText;
public Gui g;
删除JButton
和JTextField
,因为它们是JComponents and API
名称
或正确声明JButton
和JTextField
public JButton myButton, ...
public JTextField myTextField, ...
3.don't extends JFrame
将其创建为本地变量
4.不要从ActionPerformed
使用CardLayout
答案 1 :(得分:3)
您有两个Gui
的构造函数。
public Gui()
并且
public Gui(String t)
您已在第一个中初始化QuesHandText
,但在第二个中未初始化。
如果您使用第二个来初始化Gui
,那么您应该获得NullPointerException
。
我认为你应该在构造函数中执行此操作:
[按照Kleopetra的建议编辑]
public Gui(){
this("");
}
public Gui(String t){
//instruct (I am not sure what it means)
quesHandText = new JTextField(4);
classParticular handler1 = new ClassParticular();
particular.addActionListener(handler1);
myVector = new String[2]; // or some other size you need.
myVector[0]="some_string";
myVector[1]="some_string2";
}