ism*_*idi 0 java swing jlabel jframe actionlistener
我有两个问题:
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){
}
}
Run Code Online (Sandbox Code Playgroud)
我希望你们能帮忙
谢谢
由于您发布的代码无法编译且无法由我们运行,因此很难说明发生了什么.请参阅下面的最基本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 );
}
} );
}
}
Run Code Online (Sandbox Code Playgroud)