java - 我不知道如何使用 JButton Action
问题描述
你好,我是Java新手。我不知道如何使用 JButton Action。嗨,我是 JAVA 新手,我需要一些帮助。我的训练任务的目标是创建一个带有按钮的表格,该按钮还可以创建带有数据的表格,然后组合选定的数据。但我面临的可能是一个非常简单的问题,我不知道如何在按钮上设置动作,或者更确切地说如何让按钮只绘制一个类。我的代码如下。
这是我的主要方法:
public class Test {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
JFJB JaFr = new JFJB();
JaFr.JFJB();
}
}
JFrame+JButton:
import java.awt.Color;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class JFJB extends JFrame {
// JPanel/Frame
JPanel pnlFrameforButton = new JPanel();
// JButton
JButton btnMakeTable = new JButton("MakeTable");
public void JFJB() {
// FlightInfo setbounds
btnMakeTable.setBounds(60, 400, 220, 30);
// JPanel bounds
//pnlButton.setLayout(new FlowLayout(FlowLayout.LEADING, 5, 5));
pnlFrameforButton.setBounds(0, 0, 50, 50);
// Adding to JFrame
pnlFrameforButton.add(btnMakeTable);
add(pnlFrameforButton);
// JFrame properties
setSize(350, 200);
setBackground(Color.BLACK);
setTitle("Just Frame with Button");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
}
我要画的课:
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class PlayerTable extends JFrame {
public static void createPlayerTable() {
JFrame frame = new JFrame("Test frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
String[] columnNames = {
"Name",
"Score"
};
String[][] data = {
{"addins", "02.11.2006 19:15", "Folder", ""},
{"AppPatch", "03.10.2006 14:10", "Folder", ""},
{"assembly", "02.11.2006 14:20", "Folder", ""},
{"Boot", "13.10.2007 10:46", "Folder", ""},
{"Branding", "13.10.2007 12:10", "Folder", ""},
{"Cursors", "23.09.2006 16:34", "Folder", ""},
{"Debug", "07.12.2006 17:45", "Folder", ""},
{"Fonts", "03.10.2006 14:08", "Folder", ""},
{"Help", "08.11.2006 18:23", "Folder", ""},
{"explorer.exe", "18.10.2006 14:13", "File", "2,93MB"},
{"helppane.exe", "22.08.2006 11:39", "File", "4,58MB"},
{"twunk.exe", "19.08.2007 10:37", "File", "1,08MB"},
{"nsreg.exe", "07.08.2007 11:14", "File", "2,10MB"},
{"avisp.exe", "17.12.2007 16:58", "File", "12,67MB"},
};
JTable table = new JTable(data, columnNames);
JScrollPane scrollPane = new JScrollPane(table);
frame.getContentPane().add(scrollPane);
frame.setPreferredSize(new Dimension(450, 200));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
解决方案
btnMakeTable.addActionListener(e -> {
PlayerTable.createPlayerTable();
});
同样在您的主要方法中,您不需要第二行,因为已经调用了构造函数并且它不是静态的
您还可以实现接口 actionlistener 并使用 addActionListener(this);
推荐阅读
- android - 按下按钮时如何发送单个数据而不是在内部循环并在释放按钮时停止动作
- django - 如何使用 django rest 框架创建功能性 api?
- java - Jenkins maven 有其他 java 版本。如何解决?
- google-cloud-platform - gsutil 复制所有文件并创建子目录
- php - 试图获取非对象的属性
- python-3.x - 保持字典值大于五的长度
- reactjs - 反应 setState 得到错误的状态
- android - 无法在 Android Studio 3.6 上启用 Gradle 的离线模式
- ruby - 我想在 mac 上安装 SASS 但它给出了以下错误
- typescript - 类型:类型变量与类型:字符串