Java Swing GUI 入门-Checkbox和Slider
java Swing GUI 入门-Checkbox和Slider
觉得有用的话,欢迎一起讨论相互学习~
设计布局
- 大部分和上一节: https://xuzhiwei.blog.csdn.net/article/details/111476522 的内容一致,新加入的内容有
- Radio Button
- Checkbox
- JSlider
添加事件操作
- 对于checkbox主要关注的是其状态的变化,因此使用的是ChangeListener
professionalCheckBox.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
if (professionalCheckBox.isSelected()) {
feeField.setText("$120");
} else {
feeField.setText("$100");
}
}
});
* 对于radiobutton 一般情况下可以多选,为了避免多选的情况使用ButtonGroup,即新建一个ButtonGroup,并且将其他button绑定到这个ButtonGroup上.
- 对于slider,主要使用的是其范围的变化,其中范围可以根据maximum和minimum属性进行修改,并且value可以设置初始的值.
- slider主要关注的是其状态的变化,因此使用的是ChangeListener
slider1.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
int handicap = slider1.getValue();
handiLabel.setText("Your Handicap: " + handicap);
}
});
}//end constructor
程序演示
完整代码
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class GolfTourneyManager {
private JPanel mainPanel;
private JPanel panel1;
private JPanel panel2;
private JPanel panel3;
private JPanel panel4;
private JPanel panel5;
private JTextField textField1;
private JCheckBox professionalCheckBox;
private JRadioButton sandpiperRadioButton;
private JRadioButton mayfairRadioButton;
private JRadioButton blackHawkRadioButton;
private JRadioButton theRanchRadioButton;
private JTextField feeField;
private JButton REGISTERButton;
private JSlider slider1;
private JLabel handiLabel;
private JLabel logoLabel;
private JButton registerNowButton;
private JPanel TitleBarPanel;
public GolfTourneyManager() {
professionalCheckBox.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
if (professionalCheckBox.isSelected()) {
feeField.setText("$120");
} else {
feeField.setText("$100");
}
}
});
slider1.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
int handicap = slider1.getValue();
handiLabel.setText("Your Handicap: " + handicap);
}
});
}//end constructor
public static void main(String[] args) {
JFrame frame = new JFrame("Golf Tourney Manager");
frame.setContentPane(new GolfTourneyManager().mainPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
private void createUIComponents() {
}
}//end class