我有这个GUI:
我想在“热浴盆长度”文本框中输入一个数字后,该号码将被自动输入到热水浴缸的宽度文本框中,但仅当选择了圆形浴缸单选按钮时才会这样。
public void createHotTubs()
{
hotTubs = new JPanel();
hotTubs.setLayout(null);
labelTubStatus = new JTextArea(6, 30);
hotTubs.add(labelTubStatus);
JLabel lengthLabel = new JLabel(
"Length of hot tub(ft):");
lengthLabel.setBounds(10, 15, 260, 20);
hotTubs.add(lengthLabel);
hotTubLengthText = new JTextField();
hotTubLengthText.setBounds(180, 15, 150, 20);
hotTubs.add(hotTubLengthText);
JLabel widthLabel = new JLabel(
"Width of hot tub(ft):");
widthLabel.setBounds(10, 40, 260, 20);
hotTubs.add(widthLabel);
hotTubWidthText = new JTextField();
hotTubWidthText.setBounds(180, 40, 150, 20);
hotTubs.add(hotTubWidthText);
JLabel depthLabel = new JLabel(
"Average depth the hot tub(ft):");
depthLabel.setBounds(10, 65, 260, 20);
hotTubs.add(depthLabel);
hotTubDepthText = new JTextField();
hotTubDepthText.setBounds(180, 65, 150, 20);
hotTubs.add(hotTubDepthText);
JLabel volumeLabel = new JLabel("The hot tub volume is:(ft ^3");
volumeLabel.setBounds(10, 110, 260, 20);
hotTubs.add(volumeLabel);
hotTubVolumeText = new JTextField();
hotTubVolumeText.setBounds(180, 110, 150, 20);
hotTubVolumeText.setEditable(false);
hotTubs.add(hotTubVolumeText);
final JRadioButton rdbtnRoundTub = new JRadioButton("Round Tub");
rdbtnRoundTub.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
hotTubWidthText.setEditable(false);
}
});
rdbtnRoundTub.setSelected(true);
rdbtnRoundTub.setBounds(79, 150, 109, 23);
hotTubs.add(rdbtnRoundTub);
JRadioButton rdbtnOvalTub = new JRadioButton("Oval Tub");
rdbtnOvalTub.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
hotTubWidthText.setEditable(true);
}
});
rdbtnOvalTub.setBounds(201, 150, 109, 23);
hotTubs.add(rdbtnOvalTub);
ButtonGroup radioBtnGroup = new ButtonGroup();
radioBtnGroup.add(rdbtnRoundTub);
radioBtnGroup.add(rdbtnOvalTub);
JButton btnCalculateVlmn = new JButton("Calculate Volume");
btnCalculateVlmn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
double width = 0, length = 0, depth = 0, volume = 0;
String lengthString, widthString, depthString;
lengthString = hotTubLengthText.getText();
widthString = hotTubWidthText.getText();
depthString = hotTubDepthText.getText();
depth = Double.valueOf(depthString);
length = Double.valueOf(lengthString);
width = Double.valueOf(widthString);
try
{
if (rdbtnRoundTub.isSelected())
{
volume = length * width * depth;
}
else
{
volume = Math.PI * length * width / 4 * depth;
}
DecimalFormat formatter = new DecimalFormat("#,###,###.###");
hotTubVolumeText.setText("" + formatter.format(volume));
}
catch (NumberFormatException e)
{
labelTubStatus
.setText("Enter all three numbers!!");
}
}
});
答案 0 :(得分:1)
当焦点监听失去焦点并选择圆形窗格时,将焦点监听器添加到长度文本字段中,计算并设置宽度。