【问题标题】:Make JButton insert text from JTextField into variables?让 JButton 将 JTextField 中的文本插入到变量中?
【发布时间】:2012-10-12 16:43:50
【问题描述】:

我正在尝试编写一个程序,该程序将在 JTextField 中获取文本并将其放入我在按下 JButton 时声明的变量中。我需要计算一个学校项目的每周工资,但这只需要控制台,我做 GUI 是为了我自己的乐趣。我正在尝试得到它,所以当我点击“计算”时,它会从 id、rh、oh、hp 等中获取输入并计算每周工资 (wp),然后将其打印在右侧的列旁边计算按钮。

//the calculations aren't complete yet until I finish the GUI

public class Weekly_Pay 
{

public static void calculations(String[] args) 
{

Scanner imput = new Scanner(System.in);

System.out.println("ID number: ");
int employeeId = imput.nextInt();

System.out.println("Hourly Wage: ");
Double hourlyWage = imput.nextDouble();

System.out.println("Regular Hours: ");
double regularHours = imput.nextDouble();

System.out.println("Overtime Hours: ");
double overtimeHours = imput.nextDouble();

double overtimePay = round(overtimeHours * (1.5 * hourlyWage));
double regularPay  = round(hourlyWage * regularHours);

double weeklyPay = regularPay + overtimePay;

System.out.println("Employee ID Number:" + employeeId);
System.out.printf("Weekly Pay: " + "$%.2f\n", weeklyPay);

}

public static double round(double num) 
{

// rounding to two decimal places
num *= 100;
int rounded = (int) Math.round(num);
return rounded/100.0;

}


public static void main(String[] args) 
{

JFrame window = new JFrame();
window.setTitle("Weekly Pay");
window.setSize(350, 200);
window.setResizable(false);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Color lGray = new Color(209, 209, 209);

JPanel panel = new JPanel();
GroupLayout layout = new GroupLayout(panel);
panel.setBackground(lGray);
panel.setLayout(layout);
layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);

JTextField idEntry = new JTextField(); //where the user imputs their ID
JTextField hwEntry = new JTextField(); //where the user imputs their hourly wage
JTextField rhEntry = new JTextField(); //where the user imputs their regular hours
JTextField ohEntry = new JTextField(); //where the user imputs their overtime hours

JLabel id = new JLabel("ID Number");
JLabel hw = new JLabel("Hourly Wage");
JLabel rh = new JLabel("Regular Hours");
JLabel oh = new JLabel("Overtime Hours");
JButton calc = new JButton("Calculate");
JLabel wp = new JLabel(" Weekly Pay: $" + "$%.2f\n", weeklyPay);

GroupLayout.SequentialGroup hGroup = layout.createSequentialGroup();    
hGroup.addGroup(layout.createParallelGroup().
           addComponent(id).addComponent(hw).addComponent(rh).addComponent(oh).addComponent(calc));
hGroup.addGroup(layout.createParallelGroup().
  addComponent(idEntry).addComponent(hwEntry).addComponent(rhEntry).addComponent(ohEntry).addComponent(wp));
layout.setHorizontalGroup(hGroup);

GroupLayout.SequentialGroup vGroup = layout.createSequentialGroup();    
vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE).
    addComponent(id).addComponent(idEntry));
vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE).
    addComponent(hw).addComponent(hwEntry));
vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE).
    addComponent(rh).addComponent(rhEntry));
vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE).
    addComponent(oh).addComponent(ohEntry));
vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE).
    addComponent(calc).addComponent(wp));
layout.setVerticalGroup(vGroup);

window.add(panel);
window.setVisible(true);

}  
}

【问题讨论】:

    标签: java swing variables jbutton jtextfield


    【解决方案1】:

    例如:

    String input = new String();         
    JButton mbutt = new JButton;
    JTextField jtxt = new JTextField();
    
    mbutt.addActionListener(new ActionListener(){
    
           public void actionPerformed(ActionEvent event){    
                 input = jtxt.getText().toString();
           }
     });
    

    ///////////////////////////////////////////////////// ///////////////////

    在我跳入代码之前,现在有几件事。

    -我只是想展示ActionListener的工作原理,以及如何从字段中提取数据并将其放入变量中。

    -直接将组件放在JFramethats exactly what i have done here 上是一种不好的做法(我太糟糕了。 .!!!),因此您应该始终在JFrame 上使用JPanel 之类的东西,然后然后将组件放在它上面。为了保持它简单,我故意直接使用 JFrame 来保存组件。

    - 是的,拥有UI work on the UI thread, and Non-UI work on Non-UI thread 始终是非常好的做法

    -Swingsmain()方法是不长生,在Event Dispatcher Thread中调度GUI构建后它退出了...所以现在 EDT 负责处理 GUI,所以你应该保留 EDT 仅用于处理 GUI,就像我在 main() 中所做的那样方法[EventQueue.invokeLater()]。

    完整代码:

    import java.awt.BorderLayout;
    import java.awt.EventQueue;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JTextField;
    
    public class Tes extends JFrame {
    
        String input;
        JTextField jtxt; 
        JButton mbutt; 
    
    
        public Tes(){
    
     //--ALWAYS USE A JPANEL OVER JFRAME, I DID THIS TO KEEP IT SIMPLE FOR U--//
    
            this.setSize(400,400);
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
            this.setComponent();
            this.setHandler();
        }
    
        public void setComponent(){
    
            jtxt =  new JTextField("Hello");
    
            mbutt = new JButton("Button"); 
    
            this.add(BorderLayout.SOUTH,mbutt);
    
            this.add(BorderLayout.NORTH,jtxt);
    
        }
    
        public void setHandler(){
    
            mbutt.addActionListener(new ActionListener() {
    
                @Override
                public void actionPerformed(ActionEvent arg0) {
    
                    input = jtxt.getText().toString();
    
                    System.out.println("Input Value: "+input);
    
              **//--See your Console Output everytime u press the button--//**
    
                }
            });
    
        }
        public static void main(String[] args){
    
    
             EventQueue.invokeLater(new Runnable(){
    
                @Override
                public void run() {
    
                    Tes t = new Tes();
                    t.setVisible(true);
    
                }
    
    
    
             });
        }
    
    }
    

    【讨论】:

    • 我才学了四个星期的java,你能帮我解释一下如何在我的代码中实现它吗?
    • @xSpartanCx,我在办公室,现在在回家的路上,我一到就给你密码。
    • @xSpartanCx 我已经为你提供了代码和解释...Please read the points before the Code...它们很重要....
    猜你喜欢
    • 1970-01-01
    • 2021-04-26
    • 1970-01-01
    • 1970-01-01
    • 2010-11-26
    • 1970-01-01
    • 2021-02-16
    • 2021-09-05
    • 1970-01-01
    相关资源
    最近更新 更多