我用java编写了一个小周薪小程序。但是当谈到获得一个体面的布局时,我是无能为力的。我开始将面板和网格布局添加到代码中。但我不知道如何实施它们。
这是代码。
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import java.text.DecimalFormat;
import javax.swing.*;
public class WeeklyPayCalculatorApplet extends Applet implements ActionListener {
//define variables, Button, label, TextField
//Create a Button class
Label title1 = new Label("Western Distribution");
Label title2 = new Label("Weekly Payroll Calculation");
Label lblEnterMins = new Label("Enter Total Minutes Worked: ");
Label lblEnterHours = new Label("Enter Hourly Pay Rate: ");
Label lblHoursWorked = new Label("Hours Worked:");
Label lblLeftOver = new Label("Leftover Miutes:");
Label lblWeekPay = new Label("Weekly Pay:");
Label hoursWorked = new Label(" ");
Label leftoverMins = new Label(" ");
Label weeklyPay = new Label(" ");
TextField txtMinutes = new TextField(10);
TextField txtRate = new TextField(10);
Button btnPay = new Button("Weekly Pay");
Button btnClear = new Button("Clear");
Button btnExit=new Button("Exit");
//Panels
Panel pnlCenter = new Panel();
Panel pnlSouth = new Panel();
Panel pnlNorth = new Panel();
//Grids
GridLayout gridLay1 = new GridLayout(1,3);
public void init() {
// add the displayable objects;
add("Center", pnlCenter);
pnlCenter.setLayout(gridLay1);
pnlCenter.add(title1);
pnlCenter.add(title2);
add(lblEnterMins);
add(txtMinutes);
add(lblEnterHours);
add(txtRate);
add(btnPay);
add(btnClear);
add(btnExit);
add(lblHoursWorked);
add(hoursWorked);
add(lblLeftOver);
add(leftoverMins);
add(lblWeekPay);
add(weeklyPay);
//Attach event to Button
btnPay.addActionListener(this);
btnClear.addActionListener(this);
btnExit.addActionListener(this);
}
public void paint(Graphics g) {
//Draw any pictures
//Make sure the picture is in the same directory as the .class files
}
public void actionPerformed(ActionEvent e) {
//This method will fire when button is pressed
//define temporary variables
Integer hour = 60;
Double dblWeeklyPay;
Integer intLeftOvers;
Integer inthoursWorked;
Integer intMinutes = Integer.parseInt(txtMinutes.getText());
Double dblRate = Double.parseDouble(txtRate.getText());
inthoursWorked = intMinutes / hour;
intLeftOvers = 600 - intMinutes;
dblWeeklyPay = (intMinutes / hour) * dblRate;
hoursWorked.setText(inthoursWorked);
leftoverMins.setText(intLeftOvers);
weeklyPay.setText(dblWeeklyPay);
}
}
答案 0 :(得分:2)
当谈到布局时,阅读Using Layout Managers将是一个良好的开端。我个人喜欢使用GridBagLayout因为它给你很多控制权,但根据你的需要可能会有些过分。
但如果你发现它太令人生畏,你总是可以使用Netbeans或Eclipse(eclipse是更开源和我最喜欢的)来可视化地设计你的GUI。