的actionPerformed获得一个实例变量我已经创建与cardLayout和第一个可见的JPanel一个JFrame具有我已经添加的动作侦听器以执行一个动作一个JButton。该动作创建一个字符串变量'hhhhh',我想在另一个JPanel中使用它。这是我遇到的问题。你可以这样做调用从在另一个的JPanel
Class 1
import java.awt.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class NHome extends JFrame{
JPanel Bucket= new JPanel(), Start= new JPanel(), Cashier = new csView(), Manager = new JPanel();
JButton stbtn= new JButton("Start"), mnbtn= new JButton("Manager"), csbtn= new JButton("Cashier");
CardLayout cl= new CardLayout();
private final JTextField textField = new JTextField();
private JPasswordField passwordField;
public NHome() {
textField.setBounds(322, 141, 158, 31);
textField.setColumns(10);
Bucket.setLayout(cl);
Bucket.add(Start, "1");
Bucket.add(Cashier, "2");
Bucket.add(Manager, "3");
Start.setLayout(null);
stbtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
cl.show(Bucket, "2");
/*
* I want to use this value of this String in the another class (csView)
*/
String hhhhh=new String("Peter");
System.out.println(hhhhh);
}
});
stbtn.setBounds(353, 245, 76, 23);
Start.add(stbtn);
Start.add(textField);
passwordField = new JPasswordField();
passwordField.setBounds(322, 183, 158, 31);
Start.add(passwordField);
Cashier.setLayout(null);
csbtn.setBounds(197, 139, 116, 23);
Cashier.add(csbtn);
Manager.setBackground(Color.BLUE);
Manager.add(mnbtn);
cl.show(Bucket, "1");
setTitle("NOVA PHARM");
getContentPane().add(Bucket);
setBounds(300, 300, 566, 482);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(new CardLayout(5, 5));
setResizable(true);
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
NHome window = new NHome();
window.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
/*
*this is the second class where I want to use the variable
*/
2级
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.awt.Font;
public class csView extends JPanel {
/**
* Create the panel.
*/
public csView() {
setLayout(null);
/**
* I want to display the String hhhhh in the JLabel Uniqlbl below
*
*/
JLabel Uniqlbl = new JLabel("Cashier Name:");
Uniqlbl.setFont(new Font("Tahoma", Font.PLAIN, 16));
Uniqlbl.setBounds(227, 62, 253, 46);
add(Uniqlbl);
}
}
先看看[Model-View-Controller](http://en.wikipedia.org/wiki/)型号%E2%80%93view%E2%80%93controller)。这个想法是创建维持这就需要使用'null'布局视图之间共享 – MadProgrammer
避免形成模型,像素完美的布局是现代的UI设计中的错觉。影响组件的个体大小的因素太多,其中没有一个可以控制。摇摆设计为核心与布局管理工作,丢弃这些会导致没有问题,问题到底,你会花更多的时间,试图纠正 – MadProgrammer
你可能想通过[代码约定为Java TM有一个读编程语言(http://www.oracle.com/technetwork/java/codeconvtoc-136057.html),它将使人们更容易阅读你的代码,并为您如果这个问题得到解决读别人 – MadProgrammer