一道JAVA编程题

来源:百度知道 编辑:UC知道 时间:2024/05/10 10:41:49
我想把程序嵌套入按钮内要怎么做!
比如说就把一个加法程序
public class Main
{
public static void main(String[] args)
{
int num1=2,num2=3,sum;
sum = num1 + num2;
System.out.println("sum = " + sum);
}
}嵌入到按钮内
public class Sum extends javax.swing.JFrame {

/** Creates new form Sum */
public Sum()
{
initComponents();
}

/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc=" 生成的代码 ">//GEN-BEGIN:initComponents
private void initComponents() {
jButton1 = new javax.swing.JButton();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);<

你创建了一个JButton的对象jButton1,所以接下来就可以通过它的方法addActionListener创建一个监听器,另一方面,对于监听器而言,你可以对它内部的actionPerformed进行定义,而你需要加入的程序是嵌套在这个actionPerformed代码块里面哈
具体的方式可以给你写一个小示范代码:
sendButton = new JButton("Send");
sendButton.addActionListener(new
ActionListener()
{
public void actionPerformed(ActionEvent event)
{ ...
}
}
之后怎么把Button加入到面板就是你自己的事情了哈,呵呵 懂了吧