的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