我的程序有一个计算器布局,有9个按钮,有清晰,负面和转换。和2个单选按钮,当您选择一个按钮时,它会转换您输入的数字。 我设计了它,但我不知道如何做动作监听部分。 我想我只需要帮助启动代码。
// import packages
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
// class
public class Lab31Panel extends JPanel implements ActionListener
{
// data declarations
private JRadioButton k2pButton;
private JRadioButton p2kButton;
private ButtonGroup weight;
private JPanel selectConversion;
private JButton jb0,jb1,jb2,jb3,jb4,jb5,jb6,jb7,jb8,jb9,jbminus,jbclear,jbconvert;
private JTextArea display;
//constructor to initiate data and set up GUI
public Lab31Panel()
{
setLayout( new BorderLayout() );
// organizing radio buttons and their behaviours
k2pButton = new JRadioButton( "Kilograms to Pounds" );
p2kButton = new JRadioButton( "Pounds to Kilograms" );
weight = new ButtonGroup();
weight.add( k2pButton );
weight.add( p2kButton );
// adding components to panel to be south of the GUI
selectConversion = new JPanel();
selectConversion.add( k2pButton );
selectConversion.add( p2kButton );
add( selectConversion, BorderLayout.SOUTH );
//setting up west area of GUI
JPanel westPanel = new JPanel();
JPanel convert = new JPanel();
// setting up components for the west of the GUI
westPanel.setLayout(new GridLayout(5,3));
westPanel.add(jb0 = new JButton("0"));
westPanel.add(jb1 = new JButton("1"));
westPanel.add(jb2 = new JButton("2"));
westPanel.add(jb3 = new JButton("3"));
westPanel.add(jb4 = new JButton("4"));
westPanel.add(jb5 = new JButton("5"));
westPanel.add(jb6 = new JButton("6"));
westPanel.add(jb7 = new JButton("7"));
westPanel.add(jb8 = new JButton("8"));
westPanel.add(jb9 = new JButton("9"));
westPanel.add(jbminus = new JButton("-"));
westPanel.add(jbclear = new JButton("clear"));
westPanel.add(jbconvert = new JButton("convert"));
add(westPanel, BorderLayout.WEST);
//setting up east components
JPanel eastPanel = new JPanel();
eastPanel.setLayout(new BorderLayout());
display = new JTextArea();
eastPanel.add(display,BorderLayout.CENTER);
add(eastPanel);
// add listeners to radio buttons
p2kButton.addActionListener(this);
k2pButton.addActionListener(this);
//add listeners to all textfields
} //end constructor
public void actionPerformed(ActionEvent e)
{
}
} // end class
答案 0 :(得分:3)
建议:
类似的东西:
// add listeners to radio buttons // **** no, don't do this
// p2kButton.addActionListener(this);
// k2pButton.addActionListener(this);
jbclear.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO code to clear the JTextField
// usually this will involve setText("")
}
});
jbconvert.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO code to convert
// first get JRadioButton selection -- which one is set
// then get data from text component
// convert it to number (but catching for NumberFormatException)
// do conversion based on the selected JRadioButton
// and display usually with a call to setText(...)
}
});