首先,我正在使用IBM Java2 SDK Standard Edition v 1.2
至少我有两个Clasess,
我的主要目标是将Panel类动态添加到JTabbed Panel中,并从加载的类中执行方法。
开始吧:
当前菜单,其中将包含会触发添加类的按钮。
主班。
public class WMenu extends javax.swing.JFrame {
JTabbedPane1 = new javax.swing.JTabbedPane();
JBtnexec = new javax.swing.JButton();
JBtnundo = new javax.swing.JButton();
...
public static void main(java.lang.String[] args) {
...
}
/*When the user Press the btn should execute this method.*/
public void exec(java.awt.event.MouseEvent e) {
JPanel content = new JPanel();
/*Name of my class is unknown at this ponit will be controled by Variable for this
case i addit manually, */
Class qc = Class.forName("Wcontrol");
content = (JPanel) qc.newInstance();
JTabbedPane1.addTab("Control", content );
}
/ *当按Undo btn时* /
public void undo(java.util.EventObject newEvent) {
Class wMenu = Class.forName("Wcontrol");
Method m = wMenu.getDeclaredMethod("undo", new Class[] {String.class});
Object c = wMenu.newInstance();
m.invoke(c,new Object[] {new String(this.getClass().getName().toString())});
}
}
2级
/ *我的面板是Control屏幕,有一些标签字段* /
public class Wcontrol extends JPanel {
txt_cve = new javax.swing.JTextField();
public void undo(String in) {
/*txt_cve.setText("TTT"); Comment first test...*/
System.out.println("Data " + txt_cveind.getText());
JOptionPane.showMessageDialog(this, "Data: " +txt_cveind.getText(), "Info", 1);
}
}
现在,当我运行Frame时,它表现得非常完美,当我执行以加载新的类Panel时,也完美无缺,并显示在JTabed面板中,没有任何问题。
问题是,当我输入txt格式的表单类Wcontrol example =“ TTT”并按undo btn(主类)时,将在wControl中执行该方法,以防它与Show Message一起出现,但Text Data不是那里...是空的??
如果我添加注释setText,然后再次运行它,则会显示Data:TTT
Enyone知道我在做什么错吗?或任何建议
最佳答案
我认为该程序可以为您编写代码。它是空的,因为您正在undo()中创建Wcontrol的新实例,该实例进而使用空文本初始化变量txt_cve。在下面查看我的评论:
public void undo(java.util.EventObject newEvent) {
Class wMenu = Class.forName("Wcontrol");
Method m = wMenu.getDeclaredMethod("undo", new Class[] {String.class});
// NOTE #1: This one create a new instance of the class
Object c = wMenu.newInstance();
m.invoke(c,new Object[] {new String(this.getClass().getName().toString())});
}
public class Wcontrol extends JPanel {
// Note #2: Reinitialize the txt_cve
txt_cve = new javax.swing.JTextField();
public void undo(String in) {
// Note #3: This is the interesting part, you change txt_cve and the
// txt_cveind got affected, so you must have assigned txt_cfe as a reference
// to txt_cveind somewhere in your code.
/*txt_cve.setText("TTT"); Comment first test...*/
System.out.println("Data " + txt_cveind.getText());
JOptionPane.showMessageDialog(this, "Data: " +txt_cveind.getText(), "Info", 1);
}
}