2015-02-08 65 views
-2
origPrice * discCombo = salesPrice; 

我明白這將是問題。正如我試圖將JComboBox轉換爲JTextField並且不起作用。我無法在網上找到如何做到這一點。有人可以請幫忙嗎?從JComboBox轉換到JTextField

origPrice是一個jtextfield,discombo是組合框,而salesPrice也是一個jtextfield。我希望能夠將用戶放入的原始價格乘以多少,然後將其乘以從下拉組合框中選擇的項目,然後將結果導入salesPrice jtextfield

+0

,目前還不清楚你問什麼在這裏,請嘗試開發通過添加背景和你嘗試過什麼已經和它是如何沒有工作 – 2015-02-08 20:56:54

+1

JComboBox中不能轉換到JTextField.However你可以設置他們的內容。還提到哪一個是JTextField.if'salesPrice'是JTextField,那麼你必須這樣做。 salesPrice.setText((Integer)discCombo.getSelectedItem())* origPrice +「」; – 2015-02-08 21:02:49

回答

1

沒有必要將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(); 
     } 
     }); 
    } 
}