我正在使用GUI,並且我的所有內容都正確顯示,但我在按按鈕時無法更改變量的值。該變量稱爲passover,它是一個私有的int,它在0參數構造函數中初始化爲1997的值,並且我有3個按鈕需要在按下時更改passover的值。對於逾越節在使用ActionListener更改變量時遇到問題
代碼:
panel.setBorder(
BorderFactory.createEmptyBorder(0, 0, 0, 0));
panel.setLayout(new BorderLayout(0, 0));
JPanel topPanel = getPanel();
topPanel.setLayout(new GridBagLayout());
topPanel.setBackground(new Color(173, 216, 230));
JLabel moveLabel = getLabel("Move Data");
moveLabel.setFont(new Font("Serif", Font.PLAIN, 20));
addComp(topPanel, moveLabel, 0, 0, 1, 1, 0.5, 0.2,
GridBagConstraints.HORIZONTAL, GridBagConstraints.NORTHEAST);
JLabel passoverLabel = getLabel(" Passover : " + passover);
passoverLabel.setFont(new Font("Serif", Font.PLAIN, 20));
addComp(topPanel, passoverLabel, 1, 0, 1, 1, 0.5, 0.2,
GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER);
代碼的按鈕:
JPanel bottomRightPanel = getPanel();
bottomRightPanel.setBorder(
BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
bottomRightPanel.setLayout(new GridBagLayout());
bottomRightPanel.setBackground(new Color(255, 105, 180));
JPanel passoverButtonPanel = getPanel();
passoverButtonPanel.setBackground(new Color(255, 105, 180));
passoverButtonPanel.setLayout(new BoxLayout(passoverButtonPanel, BoxLayout.Y_AXIS));
nextPassoverButton = new JButton("Next Passover");
goToPassoverButton = new JButton("Go To Passover: ");
previousPassoverButton = new JButton("Previous Passover");
JLabel filler = getLabel(" ");
goToField = new JTextField(6);
goToField.setPreferredSize(new Dimension(5, 30));
theHandler handler = new theHandler();
nextPassoverButton.addActionListener(handler);
goToPassoverButton.addActionListener(handler);
previousPassoverButton.addActionListener(handler);
goToField.addActionListener(handler);
我想逾越的值被按壓nextPassoverButton當被升高一個,降低了一個被按下previousPassoverButton時,和當goToPassoverButton被按下時,改變爲用戶輸入到goToField的值。
我的ActionListener類的樣子:
public class theHandler extends MyDataPalV2 implements ActionListener{
public void actionPerformed(ActionEvent event)
{
if (event.getSource() == goToField)
{
this.passover = Integer.parseInt(String.format("%s", event.getActionCommand()));
}
if (event.getSource() == nextPassoverButton)
{
this.passover++;
}
if (event.getSource() == previousPassoverButton)
{
this.passover--;
}
}
}
的錯誤是一個私人訪問錯誤,所以我想我會需要使用一個getter和setter,但我不知道我該怎麼做。也許有完全不同的方式來做到這一點?
這是我第一次在這裏發帖很抱歉,如果我在我的文章中發生任何錯誤。
爲了更快地獲得更好的幫助,請發佈[MCVE]或[簡短,獨立,正確的示例](http://www.sscce.org/)。 –