gpt4 book ai didi

Java Action 监听器不工作

转载 作者:行者123 更新时间:2023-12-01 06:46:56 26 4
gpt4 key购买 nike

我有两个问题:

1.为什么当我执行代码时,当我单击按钮 P 时,它不显示 println。2.我尝试用JLabel制作背景,它工作正常,但它没有覆盖所有JFrame。我用 try 和 catch 尝试了 JFrame,但它不显示它。

JPanel L1 = new JPanel();
JButton P = new JButton("Open");

JButton P1 = new JButton("Cancel");

Dimension D = new Dimension(80 , 30);

Container C = getContentPane();

JLabel Label2 = new JLabel(new




super.setTitle("Ismail Application");
//Buttons

//Button 1
P.setToolTipText("Click To Open");
P.setPreferredSize(D);

//Button 2
P1.addActionListener(this);

P1.setToolTipText("Click to exit program");

P1.setPreferredSize(D);

//Adding Components

L1.add(P, BorderLayout.WEST);

L1.add(P1, BorderLayout.EAST);

add(L1, BorderLayout.SOUTH);

P1.addActionListener(this);

P.addActionListener(this);


//Labels

Label2.setLayout(null);

Label2.setSize(400,300);

Label2.setToolTipText("This is the Background");

add(Label2, BorderLayout.NORTH);


}
public void actionPerformed (ActionEvent e)
{
if(e.getSource() == P)
{
System.out.println("not working");
}
if(e.getSource() == P1){

}

}

希望大家帮忙

谢谢

最佳答案

由于您发布的代码无法编译并且无法被我们运行,所以很难说到底发生了什么。请参阅下面的最基本的 JButton 示例,其中附加了 ActionListener,每次按下按钮时都会打印一些内容。将其与您的代码进行比较以找出差异,或将您的代码调整为 sscce .

import javax.swing.JButton;
import javax.swing.JFrame;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class FrameWithButtonExample {

public static void main( String[] args ) {
EventQueue.invokeLater( new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame( "TestFrame" );

final JButton testButton = new JButton( "TestButton" );
testButton.addActionListener( new ActionListener() {
@Override
public void actionPerformed( ActionEvent aActionEvent ) {
//if check to match the code from the question, but not really needed
if ( aActionEvent.getSource() == testButton ){
System.out.println("TestButton pressed");
}
}
} );
frame.add( testButton );
frame.pack();
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setVisible( true );
}
} );
}
}

关于Java Action 监听器不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9052783/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com