2016-11-27 7 views
1

제 동생이 자신이 플레이하는 게임에서 세금을 계산하는 간단한 GUI 응용 프로그램을 만들 것을 요청했습니다. 그래서 나는이 코드를 빨리 조립했다. 난 그냥 빨리 일을 원하는대로 말 그대로, 5 분 사용 :Mac에서는 JTextField가 표시되지만 Windows에서는 표시되지 않습니다.

public class MainGUI extends JFrame implements ActionListener { 

    private static final double EA_TAX = 0.05; 

    private JButton btnProfit; 
    private JTextField buyPrice; 
    private JTextField sellPrice; 
    private JTextField resultField; 
    private JLabel buyLabel; 
    private JLabel sellLabel; 
    private static final NumberFormat NUMBER_FORMAT = NumberFormat.getInstance(); 
    JPanel container; 

    public MainGUI(){ 
     this.setSize(400,400); 
     container = new JPanel(); 
     btnProfit = new JButton("Calculate"); 
     buyPrice = new JFormattedTextField(getIntFormatter(NUMBER_FORMAT)); 
     sellPrice = new JFormattedTextField(getIntFormatter(NUMBER_FORMAT)); 
     resultField = new JTextField(); 
     buyLabel = new JLabel("The price you intend to pay"); 
     sellLabel = new JLabel("Price you intend to sell the player for"); 
     resultField.setEditable(false); 
     btnProfit.addActionListener(this); 
     GridLayout gridLayout = new GridLayout(3,2); 
     container.setLayout(gridLayout); 
     container.add(buyLabel); 
     container.add(sellLabel); 
     container.add(buyPrice); 
     container.add(sellPrice); 
     container.add(btnProfit); 
     container.add(resultField); 

     container.setVisible(true); 
     this.add(container); 

     this.pack(); 
     this.setVisible(true); 
     this.setDefaultCloseOperation(EXIT_ON_CLOSE); 

    } 

    private NumberFormatter getIntFormatter(NumberFormat NUMBER_FORMAT) { 
     NumberFormatter formatter = new NumberFormatter(NUMBER_FORMAT); 
     formatter.setValueClass(Integer.class); 
     formatter.setMinimum(0); 
     formatter.setMaximum(Integer.MAX_VALUE); 
     //formatter.setAllowsInvalid(false); 
     formatter.setCommitsOnValidEdit(true); 


     return formatter; 
     } 


    @Override 
    public void actionPerformed(ActionEvent e) { 
     if(e.getSource() == this.btnProfit){ 
      this.resultField.setText("" +determineProfitAfterTax(Integer.parseInt(buyPrice.getText().replace(",", "")), Integer.parseInt(sellPrice.getText().replace(",", "")))); 
     } 
    } 

    private int determineProfitAfterTax(int buyPrice, int sellPrice){ 
     return (int) (sellPrice * (1.00 - EA_TAX)) - buyPrice; 
    } 
} 

을 Java 클래스 MainApplication.java에 내가 인스턴스화 JFrame : 텍스트 필드의 모든이를 제외하고 표시

public class MainApplication { 

    public static void main(String args[]){ 
     new MainGUI(); 
    } 
} 

resultFieldJTextField이며 결과를 보유하고 있습니다. Mac에서나 Windows에서 작동하지 않는 특별한 이유가 있습니까? 모든 입력을 부탁드립니다.

+0

[이벤트 발송 스레드] (http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html)에서 _only_ 스윙 GUI 객체를 생성하고 조작하십시오. – trashgod

+0

@trashgod 링크를 보았지만 이해가되지 않았습니다. 예를 들어 주시겠습니까? – tomSurge

+1

'main()'은 [example] (http://stackoverflow.com/search?tab=votes&q=user%3a230513%20EventQueue.invokeLater)에 대해'EventQueue.invokeLater()'를 호출해야합니다. – trashgod

답변

0

문제는 강하게 사용자 @trashgod에 의해 제안 이벤트 처리 쓰레드 (의 GUI 스윙 GUI 옵션을 구성하여 해결되었다에서 작업 명확히하기 위해 대신이 일을 :.

public class MainApplication { 

    public static void main(String args[]){ 
     new MainGUI(); 
    } 
} 

이 작업을 수행 :

public class MainApplication { 

    public static void main(String args[]){ 
     SwingUtilities.invokeLater(new Runnable() { 
      public void run() { 
       new MainGUI(); 
      } 
     }); 
    } 
} 

하시기 바랍니다 항상 첫 번째 방법을 사용하면 프로그램이 작동하는 것처럼 보일 수 있습니다 비록 첫 번째 방법을 사용하여, 시도하고 두 번째 방법을 사용합니다. 매우 이상한 부작용을 일으킨다.

1

몇 가지 실수가 수정되었습니다. 지금은 Windows.`

import javax.swing.*; 

    import javax.swing.text.NumberFormatter; 
    import java.awt.*; 
    import java.awt.event.ActionEvent; 
    import java.awt.event.ActionListener; 
    import java.text.NumberFormat; 

    public class MainGUI extends JFrame implements ActionListener { 

private static final double EA_TAX = 0.05; 

private JButton btnProfit; 
private JTextField buyPrice; 
private JTextField sellPrice; 
private JTextField resultField; 
private JLabel buyLabel; 
private JLabel sellLabel; 
private static final NumberFormat NUMBER_FORMAT =  NumberFormat.getInstance(); 
JPanel container; 

public MainGUI(){ 
    this.setSize(400,400); 
    container = new JPanel(); 
    btnProfit = new JButton("Calculate"); 
    buyPrice = new JFormattedTextField(getIntFormatter(NUMBER_FORMAT)); 
    sellPrice = new JFormattedTextField(getIntFormatter(NUMBER_FORMAT)); 
    resultField = new JTextField(); 
    buyLabel = new JLabel("The price you intend to pay"); 
    sellLabel = new JLabel("Price you intend to sell the player for"); 
    resultField.setEditable(false); 
    btnProfit.addActionListener(this); 
    GridLayout gridLayout = new GridLayout(3,2); 
    container.setLayout(gridLayout); 
    container.add(buyLabel); 
    container.add(sellLabel); 
    container.add(buyPrice); 
    container.add(sellPrice); 
    container.add(btnProfit); 
    container.add(resultField); 

    container.setVisible(true); 
    this.add(container); 

    this.pack(); 
    this.setVisible(true); 
    this.setDefaultCloseOperation(EXIT_ON_CLOSE); 

} 

private NumberFormatter getIntFormatter(NumberFormat NUMBER_FORMAT) { 
    NumberFormatter formatter = new NumberFormatter(NUMBER_FORMAT); 
    formatter.setValueClass(Integer.class); 
    formatter.setMinimum(0); 
    formatter.setMaximum(Integer.MAX_VALUE); 
    //formatter.setAllowsInvalid(false); 
    formatter.setCommitsOnValidEdit(true); 


    return formatter; 
} 



public void actionPerformed(ActionEvent e) { 
    if(e.getSource() == this.btnProfit){ 
     this.resultField.setText("" +determineProfitAfterTax(Integer.parseInt(buyPrice.getText().replace(",", "")), Integer.parseInt(sellPrice.getText().replace(",", "")))); 
    } 
} 

private int determineProfitAfterTax(int buyPrice, int sellPrice){ 
    return (int) (sellPrice * (1.00 - EA_TAX)) - buyPrice; 
} 
}` 
+0

변경 사항이 없습니다. 너 무슨 소리 야? 가져 오기 변경 사항 만 추가했습니다. 또한, 당신이 뭔가를 "고정"했다고 말할 때, 당신이 고쳐 놓은 것을 지정하십시오. 내 IDE를 복사하여 붙여 넣고 라이브러리를 가져 와서 여기에 다시 붙여 넣기 만하면됩니다. 포스트는 혼란스럽고 처음부터 만들어져서는 안됩니다. – tomSurge

+0

@tomSurge : 이것은 잘못 동기화 된 프로그램, 즉'EventQueue.invokeLater()'가없는 예가 한 플랫폼에서 올바르게 실행되고 다른 플랫폼에서 실패 할 수있는 예입니다. – trashgod