为什么JButton.getModel()。isPressed()总是返回false

时间:2017-11-01 09:14:11

标签: java swing jbutton

我有两个问题,第一个问题是JButton.getModel()。isPressed总是返回false。

public void setReadButtonStatus() {
        if(readButton.getModel().isPressed()==true) {
            readButton.getModel().setPressed(false);
        }
        else {
            readButton.getModel().setPressed(true);
        }
        System.out.println(readButton.getModel().isPressed());
    }

当我调用setReadButtonStatus函数时,isPressed总是为false。

另一个问题是如何让两个JButton同时按下状态

1 个答案:

答案 0 :(得分:0)

您的第一个回答:isPressed()确定是否用鼠标按下按钮。你可以在下面的程序中看到isPressed()的结果:

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;

class EventExample implements ActionListener {
  JFrame frame;
  JTextArea area;
  JScrollPane pane;
  JButton button1;
  JButton button2;
  JPanel contentPane;
  JPanel buttonPanel;
  boolean flag = true;

  public EventExample() {
    frame = new JFrame();

    area = new JTextArea(10,10);
    area.setEditable(true);
    area.setBorder(BorderFactory.createTitledBorder("EVENT"));

    button1 = new JButton("Button1");
    button1.addActionListener(this);


    button2 = new JButton("Button2");
    button2.addActionListener(this);

    contentPane = new JPanel(new BorderLayout());

    buttonPanel = new JPanel();
    buttonPanel.add(button1);
    buttonPanel.add(button2);

    contentPane.add(area);
    contentPane.add(buttonPanel,BorderLayout.AFTER_LAST_LINE);
    MouseAdapter adapter = new MouseAdapter() {
      @Override
      public void mousePressed(MouseEvent e) {
        area.setText(area.getText()+"\nMouse Pressed Event Occur Button isPressed  = "+button1.getModel().isPressed());
      }
      public void mouseEntered(MouseEvent e) {
        area.setText(area.getText()+"\nMouse Moved Event Occur Button isPressed  = "+button1.getModel().isPressed());
      }
    };

    button1.addMouseListener(adapter);
    frame.setContentPane(contentPane);
    frame.pack();
    frame.setVisible(true);
  }

  @Override
  public void actionPerformed(ActionEvent e) {
    if(e.getSource() == button2) {
      if(flag == true) {
        flag = false;
        button1.getModel().setPressed(false);
        area.setText(area.getText()+"\nMouse Pressed Event Occur in Button2 Button 1 isPressed  value = "+button1.getModel().isPressed());

      } else {
        flag = true;
        button1.getModel().setPressed(true);
        area.setText(area.getText()+"\nMouse Pressed Event Occur in Button2 Button 1 isPressed  value = "+button1.getModel().isPressed());

      }
    }
  }
  public static void main(String args[]) {
    new EventExample();
  }
}

如果您运行此程序,则了解isPressed()返回true时。运行程序后,您可以看到isPressed()方法在按下操作时返回true,如果移动动作按钮返回false