沒有必要將JComboBox變成任何事情,因爲你可以更好地離開它,只需提取它所需的數據。這可以通過getSelectedItem()
完成,檢查它不是空的,然後使用它。
例如:
import java.awt.event.ActionEvent;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import javax.swing.*;
public class ComboDemo extends JPanel {
private Integer[] items = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
private DefaultComboBoxModel<Integer> comboModel = new DefaultComboBoxModel<>(items);
private JComboBox<Integer> combo = new JComboBox<>(comboModel);
private JFormattedTextField orgPriceField = new JFormattedTextField(new DecimalFormat("0.00"));
private JFormattedTextField finalPriceField = new JFormattedTextField(NumberFormat.getCurrencyInstance());
public ComboDemo() {
finalPriceField.setFocusable(false);
orgPriceField.setColumns(10);
finalPriceField.setColumns(10);
orgPriceField.setText("0.00");
add(orgPriceField);
add(new JLabel("x"));
add(combo);
add(new JLabel("="));
add(finalPriceField);
add(new JButton(new CalculateAction()));
}
private class CalculateAction extends AbstractAction {
public CalculateAction() {
super("Calculate");
}
@Override
public void actionPerformed(ActionEvent e) {
Number orgPrice = (Number) orgPriceField.getValue();
Integer multiplier = ((Integer) comboModel.getSelectedItem()).intValue();
double result = orgPrice.doubleValue() * multiplier;
finalPriceField.setValue(result);
}
}
private static void createAndShowGui() {
ComboDemo mainPanel = new ComboDemo();
JFrame frame = new JFrame("ComboDemo");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
,目前還不清楚你問什麼在這裏,請嘗試開發通過添加背景和你嘗試過什麼已經和它是如何沒有工作 – 2015-02-08 20:56:54
JComboBox中不能轉換到JTextField.However你可以設置他們的內容。還提到哪一個是JTextField.if'salesPrice'是JTextField,那麼你必須這樣做。 salesPrice.setText((Integer)discCombo.getSelectedItem())* origPrice +「」; – 2015-02-08 21:02:49