【发布时间】:2012-04-19 16:13:42
【问题描述】:
我正在阅读一本名为 Swing: A Beginner's guide 的好书。 书中有这段代码创建了一个按钮和一个标签,用于提醒按钮的状态变化事件:
//Demonstrate a change listener and the button model
package swingexample2_6;
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
public class ChangeDemo {
JButton jbtn;
JLabel jlab;
public ChangeDemo() {
//Create a new JFrame container
JFrame jfrm = new JFrame("Button Change Events");
//Specify FlowLayout for the layout manager
jfrm.getContentPane().setLayout(new FlowLayout());
//Give the frame an initial size
jfrm.setSize(250, 160);
//Terminate the program when the user closes the application
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create an empty label
jlab = new JLabel();
//Make a button
jbtn = new JButton("Press for Change Event Test");
//--Add change listener
jbtn.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent ce) {
ButtonModel mod = jbtn.getModel();
String what = "";
if (mod.isEnabled()) {
what += "Enabled<br>";
}
if (mod.isRollover()) {
what += "Rollover<br>";
}
if (mod.isArmed()) {
what += "Armed<br>";
}
if (mod.isPressed()) {
what += "Pressed<br>";
}
//Notice that this label's text is HTML
jlab.setText("<html>Current stats:<br>" + what);
}
});
//Add the components to the content pane
jfrm.getContentPane().add(jbtn);
jfrm.getContentPane().add(jlab);
//Display the frame
jfrm.setVisible(true);
}
public static void main(String[] args) {
//Create the frame on the event dispatching thread
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new ChangeDemo();
}
});
}
}
除翻转事件外,一切正常。 底层操作系统是 Mac OS Lion。 我应该把这个挥杆问题归咎于狮子还是我做错了什么? 谢谢。
【问题讨论】:
-
对我来说很好用...Windows 7 操作系统
-
@mre 此处相同(也使用 Win. 7 和后期 1.6 JRE)。使用的 JRE 版本是什么? (对 mre 和原始海报的问题。)
-
@AndrewThompson,jdk 1.6.0_29
-
@skiabox 我希望在倾向于该结论/策略之前,至少再看到一位 OS X 用户的回复。
-
为sscce+1。
标签: java swing jbutton changelistener