如何在JTextarea或JTable

时间:2016-03-23 19:52:42

标签: java jtable jtextarea

所以我创建了两个按钮,我想在单击按钮时执行特定任务。如果使用ActionListener单击按钮1(b1),我想创建Van的对象并在JTextarea或JTable中显示实例变量。例如,如果单击Van按钮,则操作将是创建Van的对象并获取实例变量值并将其打印在JTextArea / JTable中。以下是我目前的代码:

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTable;


public class TestButton extends JFrame{

JTable table;

public TestButton (){

    setLayout(new FlowLayout());
}
static class ActionTwo implements ActionListener{

    @Override
    public void actionPerformed (ActionEvent evt){

        Vehicle sport = new Sportcar (200, 1500, 220);

    }
  }

  static class Action implements ActionListener{

    @Override
    public void actionPerformed (ActionEvent evt){

        Vehicle aVan = new Van(100,0.9,3500,160.4);


    }

   }

  public static void main (String [] args){

  JFrame frame = new JFrame ("Type of Vehicle");
  frame.setVisible(true);
  frame.setSize(400,200);
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.setLocationRelativeTo(null);
  JPanel panel = new JPanel();
  panel.setBackground(Color.black);
  JButton b1 = new JButton("Van");
  JButton b2 = new JButton("Sports Car");
  panel.add(b1);
  panel.add(b2);
  frame.add(panel);
  b1.addActionListener(new Action());
  b2.addActionListener(new ActionTwo());

  }




  }

1 个答案:

答案 0 :(得分:0)

查看Java tutorial on Action Listeners

这将按照您的意愿行事,但您应该仔细阅读该教程,以便全面了解所发生的事情。

public static void main (String [] args){
    JTextField text = new JTextField();
    ActionListener textSetter = new ActionListener() {

      @Override
      public void actionPerformed(ActionEvent e) {
          JButton clicked = (JButton) e.getSource();
          text.setText(clicked.getText());
      }
    };

    JButton btnVan = new JButton("Van");
    btnVan.addActionListener(textSetter);
    JButton btnCar = new JButton("Sports Car");
    btnCar.addActionListener(textSetter);

    JPanel btnPanel = new JPanel();
    btnPanel.add(btnVan);
    btnPanel.add(btnCar);

    JPanel mainPanel = new JPanel(new BorderLayout());
    mainPanel.add(text, BorderLayout.NORTH);
    mainPanel.add(btnPanel, BorderLayout.SOUTH);

    JFrame frame = new JFrame ("Type of Vehicle");
    frame.add(mainPanel);
    frame.setSize(400,200);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
}