我想要“世界你好!”当我的按钮被点击时显示。
因此,转到下一个“框架”,但在同一个窗口中!
我尝试过卡片布局,但是谁能告诉我如何使用这段代码来做到这一点?
我在这段代码中做错了什么?
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JOptionPane;
public class myTest{
public static void main(String[] args){
JPanel panel = new JPanel();
JButton button1 = new JButton();
frame.add(panel);
panel.add(button1);
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(null, "Hello World");
}
});
}
}
尝试使用代码:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JOptionPane;
public class myTest {
public static void main(String[] args) {
final JFrame frame = new JFrame();
JPanel panel = new JPanel();
JButton button1 = new JButton();
frame.add(panel);
panel.add(button1);
frame.setVisible(true);
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(frame.getComponent(0), "Hello World");
}
});
}
}
它正在按预期工作。
或者,如果您希望消息位于同一框架上,请尝试使用此代码。
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class myTest {
public static void main(String[] args) {
final JFrame frame = new JFrame();
JPanel panel = new JPanel();
JButton button1 = new JButton();
final JLabel label = new JLabel("Hello World");
label.setVisible(false);
frame.add(panel);
panel.add(button1);
panel.add(label);
frame.setVisible(true);
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//JOptionPane.showMessageDialog(frame.getComponent(0), "Hello World");
label.setVisible(true);
}
});
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)