簡體   English   中英

我如何在JTextarea或JTable中顯示

[英]How do i display in JTextarea or JTable

因此,我創建了兩個按鈕,並且在單擊按鈕時想執行特定的任務。 如果使用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());

  }




  }

看看有關動作偵聽器Java教程

這將完成您想做的事情,但是您應該通讀該教程以全面了解正在發生的事情。

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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM