编辑:我发现了我的问题,但仍然不知道为什么会发生这种情况,我还没有完成 Mehran Sahami 教授(斯坦福大学)的在线讲座,如果我继续播放讲座视频,也许我会找到答案.
问题是我在我的按钮方法之前删除了我的其他组件方法以有效地发布空间,所以我应该把我的
JToggleButton
方法放在我的主要JFrame
方法之后让它工作,但是如果我的 其他组件也继承其他类怎么办?我应该首先使用哪种方法来使所有组件正常工作?我会通过更多地练习java来发现。感谢@Dan 和@SebVb 的回答和建议,如果这只是初学者的错误,请见谅:)
我现在正在学习 java 一个月,并且已经有了简单的学习项目,但是现在我遇到了JToggleButton
,ItemEvent
和actionPerformed
If 语句中的问题。
我已经搜索了一个星期来寻找在另一个类中使用actionPerformed
if 语句的示例,ItemEvent
但我找不到相同的问题来产生工作结果。
我正在尝试制作一个仅在选择切换按钮时才会扫描的窗口扫描仪,然后JPanel
使用缓冲图像进行绘制(每 100 毫秒重绘一次)并在取消选择切换按钮时将其处理,但我认为我的做法是错误的。我有一个主类和两个子类,如下所示:
主类:
public class WindowScanner {
public static void main(String[] args) {
new Window().setVisible(true);
}
}
窗口类:
class Window extends JFrame {
static JToggleButton captureButton = new JToggleButton("CAPTURE");
@SuppressWarnings("Convert2Lambda")
public Window() {
// JFrame looks codes
/** EDIT: these components method should be written after button method
* JPanel looks codes
* JLabel looks codes
* END EDIT
*/
add(captureButton);
// capture button default looks code
ItemListener captureListener = new ItemListener(){
@Override
public void itemStateChanged(ItemEvent captureButtonEvent) {
int captureState = captureButtonEvent.getStateChange();
if(captureState == ItemEvent.SELECTED){
// capture button SELECTED looks code
System.out.println("capture button is selected");
} else if(captureState == ItemEvent.DESELECTED){
// capture button DESELECTED looks code
System.out.println("capture button is deselected");
}
}
}; captureButton.addItemListener(captureListener);
}
}
扫描仪类:
public class Scanner extends Window {
private static BufferedImage boardCaptured;
static int delay = 100;
protected BufferedImage boardScanned(){
return boardCaptured;
}
@SuppressWarnings("Convert2Lambda")
public static void Scan() {
if (captureButton.isSelected()) {
ActionListener taskPerformer = new ActionListener() {
@Override
public void actionPerformed(ActionEvent captureEvent) {
try {
// capturing method
} catch (AWTException error) {
// AWTException error method
}
// is this the right place to put JPanel code?
JPanel panel = new JPanel();
boardCaptured = new BufferedImage(500, 500, BufferedImage.TYPE_INT_ARGB);
Graphics2D graphic = boardCaptured.createGraphics();
panel.setSize(500,500);
panel.paint(graphic);
panel.revalidate();
panel.repaint();
}
}; new Timer(delay, taskPerformer).start();
} else {
// this suppose to end capturing if capture button isSelected() == false
}
}
}
所以这是我的问题:
- 我真的必须将 Main 类与 Window 类分开吗?什么原因?
- 如何让我在 Scan 方法中的 if 语句
JToggleButton
从 Window 类中识别我的状态?这是不可能的,我有一个错误的方法来做到这一点? - 在 Scanner 类中,我无法为我的
actionPerformed
(Netbeans 总是将其检查为错误)进行获取/设置,但为什么我可以为我的BufferdImage
? - 如果我无法解决第 3 个问题,我该如何使用 If 语句停止捕获
Timer.stop()
?还是我又走错路了? - 是否会生成我
JPanel
的扫描仪课程并为我的缓冲图像制作查看器?
PS我很抱歉它的问题很拥挤,我尽量不发多个帖子,所以我发了一个有多个问题的帖子。如果之前有答案,请注意我,老实说我找不到它或者用错误的标签搜索它。