java gui怎么来回切换按钮背景颜色
1个回答
展开全部
package demo.com.test;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JLabel;
public class SwingTest {
private JFrame frame;
private JLabel lblNewLabel;
private boolean flag = false;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SwingTest window = new SwingTest();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public SwingTest() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 288, 234);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnNewButton = new JButton("OK");
btnNewButton.setBounds(59, 51, 146, 77);
btnNewButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (!flag) {
btnNewButton.setBackground(Color.red);
flag =true;
} else {
btnNewButton.setBackground(Color.black);
flag = false;
}
}
});
frame.getContentPane().add(btnNewButton);
lblNewLabel = new JLabel("");
lblNewLabel.setBounds(35, 107, 214, 36);
frame.getContentPane().add(lblNewLabel);
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询