我正在嘗試創建一個鎖屏界面。我有4個字符串變量,分別稱爲L11,L21,L31和L41。在我的LockButton類中,我嘗試使用ActionListener設置它們的值。我將第一個L11設置爲按鈕上的文字。通過檢查L11!= null是否設置了L21等等。相反,輸出顯示每次按下按鈕時都會設置L11,這不是我所想要的。一個接一個設置變量
的LockScreen類
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class LockScreen
{
static int lockID;
static String L1, L2, L3, L4;
static JFrame frame;
static JPanel panel;
static JButton digits;
static GridLayout grid = new GridLayout(3,4);
public static void main(String [] args)
{
frame = new JFrame("LockScreen");
panel = new JPanel();
for(int lockID = 1; lockID < 10; lockID++)
{
lockButton btn = new lockButton(lockID, L1, L2, L3, L4);
panel.add(btn);
}
panel.setLayout(grid);
frame.add(panel);
frame.setSize(300,600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
LockButton類
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
public class lockButton extends JButton
{
int lockID1;
String L11, L21, L31, L41;
public lockButton(int lockID, String L1, String L2, String L3, String L4)
{
lockID1 = lockID;
L1 = L11;
L2 = L21;
L3 = L31;
L4 = L41;
setText("" + lockID1);
addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if(L11 == null)
{
L11 = getText();
}
else
{
L21 = getText();
}
System.out.println("Btn Txt: " + getText());
System.out.println("L1: " + L11 + " L2: " + L21 + " L3: " + L31 + " L4: " + L41);
}
});
}
public void setL1()
{
L11 = getText();
}
}
「輸出顯示,L11是在每次按下按鈕時」是的,因爲這正是你已經編程做它。如果這不是你想要的,你想要什麼? – Boann
我希望它繼續設置下一個。這是爲什麼即時檢查L11是否爲空?因此,如果L11爲空,則將其設置爲getText(),如果它不爲空並設置L21。 –