我正在測試ButtonModel
的行爲,我遇到了一個奇怪的情況。 isRollover()
方法不會返回預期的(根據我)值。Java Swing - JButton模型中的isRollover()值
這是我剛剛創建的示例代碼:
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
/**
*
* @author rmu
*/
public class NewClass extends JFrame {
private static final Logger logger = Logger.getLogger(NewClass.class.getName());
static {
logger.setLevel(Level.INFO);
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("Test MVC");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JButton btn = new JButton("Test button");
final JLabel lbl = new JLabel("");
btn.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
logger.log(Level.INFO, "\nButton armed: " + btn.getModel().isArmed()
+ "\nButton pressed: " + btn.getModel().isPressed()
+ "\nButton selected: " + btn.getModel().isSelected()
+ "\nButton rollover: " + btn.getModel().isRollover()
);
lbl.setText(btn.getModel().isRollover() ? "Mouse is over the button" : "Mouse is NOT over the button");
}
});
frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.PAGE_AXIS));
frame.getContentPane().add(btn);
frame.getContentPane().add(lbl);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
createAndShowGUI();
}
});
}
}
回購步驟:
- 將鼠標移動到按鈕 - >一切正常
- 按下鼠標按鈕 - >一切正常
- (不釋放鼠標按鈕)移動鼠標,使其不再位於按鈕上 - > Ever ything的OK
- (不釋放...)再次將鼠標移動到按鈕 - >
isRollback()
方法返回false
(見日誌和JLabel
)
它是正確的行爲或錯誤?我想寫一些使用這個屬性的代碼,我不確定我是否可以依賴它。
[也許這是一個錯誤](http://stackoverflow.com/q/30581812/714968),使用SwingUtilities.isLeftMouseButton – mKorbel