java - 组件之间的 Java swing 通信
问题描述
我在 Swing 中以交互或施加动作流的方式连接组件时遇到问题。我的计划是在按下按钮时禁用/启用 JTextPane,然后输入数字以便程序可以开始计算。到目前为止,这是我被困在的地方:
private JPanel contentPane;
protected JTextPane txtpnA;
protected JTextPane txtpnB;
protected JTextPane txtpnC;
/* Button 'a' **/
JButton btnA = new JButton("a");
btnA.setBackground(Color.YELLOW);
btnA.setBounds(47, 54, 89, 23);
btnA.setActionCommand("a");
btnA.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
} {
}
});
contentPane.add(btnA);
/* TextPane 'a' **/
txtpnA = new JTextPane();
txtpnA.setBounds(47, 88, 89, 20);
contentPane.add(txtpnA);
txtpnA.setBorder(BorderFactory.createLineBorder(Color.black));
这是方法:
public void actionPerformed(ActionEvent event) {
String command = event.getActionCommand();
if(command.equals("a"))
{
txtpnA.setEnabled(false);
} else if(command.equals("b"))
{
txtpnB.setEnabled(false);
} else if(command.equals("c"))
{
txtpnC.setEnabled(false);
}
}
}
我很难找到有关 JComponents 之间通信的文章。如果您还可以建议一个详细的来源,将不胜感激。
解决方案
我建议您创建一个新类来处理您对特定组件的请求,并且不要使用匿名事件处理程序:
public class ButtonHandler extends AbstractAction {
private JComponent componentToDisable;
public ButtonHandler(JComponent comp, String text) {
super(text);
componentToDisable = comp;
}
public void actionPerformed(ActionEvent event) {
componentToDisable.setEnabled(false);
}
}
如何使用它:
/* TextPane 'a' **/
txtpnA = new JTextPane();
txtpnA.setBounds(47, 88, 89, 20);
contentPane.add(txtpnA);
txtpnA.setBorder(BorderFactory.createLineBorder(Color.black));
JButton btnA = new JButton(new ButtonHandler(textpnA, "a"));
btnA.setBackground(Color.YELLOW);
btnA.setBounds(47, 54, 89, 23);
contentPane.add(btnA);
其他按钮的步骤相同。
JButton btnB = new JButton(new ButtonHandler(textpnB, "b"));
JButton btnC = new JButton(new ButtonHandler(textpnC, "c"));
最后但并非最不重要。正如 Andrew Thompson 已经提到的:
Java GUI 必须在不同的语言环境中使用不同的 PLAF 在不同的操作系统、屏幕尺寸、屏幕分辨率等上工作。因此,它们不利于像素完美布局。而是使用布局管理器,或者它们的组合以及布局填充和空白边框。
推荐阅读
- java - 如何在 Discord JDA 嵌入式消息中使用本地文件作为缩略图?
- flutter - 如何实现下拉刷新和上拉加载(iOS风格)?
- javascript - 在 TypeScript 中导入纯 JavaScript(不是模块)函数
- ruby - 无法使用 parallel_rspec gem 在 Windows 10 上执行 selenium 测试
- python - 如何覆盖 Python Dataclass 'asdict' 方法
- c - 为什么我的功能在我调用它时不能正常工作?
- riscv - RISC-V 调用约定
- php - PHP,循环遍历多个数组 - 一些数组只有 1 个结果
- liquibase - 在 liquibase 默认值字段中添加和号
- django - 无法符号化堆栈跟踪:网络请求失败 - React Native