gpt4 book ai didi

java - 检查和交换按钮? GUI [有相应的操作命令吗?]

转载 作者:行者123 更新时间:2023-12-01 10:23:54 24 4
gpt4 key购买 nike

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class test extends JFrame implements ActionListener {


public test() {

super("Checker and Swapper");

getContentPane().setLayout(new FlowLayout());

JTextField textField1 = new JTextField(15);
JButton check = new JButton("CHECK");
check.setActionCommand("check");



JTextField textField2 = new JTextField(15);
JButton swap = new JButton ("SWAP");
swap.setActionCommand("swap");


check.addActionListener(this);
swap.addActionListener(this);


getContentPane().add(textField1);
getContentPane().add(check);
getContentPane().add(textField2);
getContentPane().add(swap);


setSize(300, 170);
setVisible(true);
}

public void actionPerformed( ActionEvent e)
{
// i don't know what to put here
}


public static void main(String args[]) {
new test();
}
}

所以我试图制作一个图形用户界面,如果我单击“检查”按钮,它将检查两个文本字段上的字符串是否相同,然后在下部显示的标签是相同的,然后如果我单击交换它将交换两个字符串。

我是 gui 的初学者。谁能帮我吗?

谢谢(:

This is what I already have expect for action for the button.

最佳答案

根据您的代码,现在它使用 JOPtionPane 创建一个弹出窗口,如果您需要标签,只需使用 JLabel lblname = new JLabel() 并将其添加到框架中,并通过调用 lblname.setText("text"); 设置标签文本;

public class test extends JFrame {

public test() {

this.setTitle("Checker and Swapper");
getContentPane().setLayout(new FlowLayout());

JTextField textField1 = new JTextField(15);
JButton check = new JButton("CHECK");
check.setActionCommand("check");

JTextField textField2 = new JTextField(15);
JButton swap = new JButton ("SWAP");
swap.setActionCommand("swap");

check.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
if(textField1.getText().equals(textField2.getText()))
{
JOptionPane.showMessageDialog(null, "Both Texts are equal");
}
}
});

swap.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
String temporary = textField1.getText();
textField1.setText(textField2.getText());
textField2.setText(temporary);
}
});


getContentPane().add(textField1);
getContentPane().add(check);
getContentPane().add(textField2);
getContentPane().add(swap);


setSize(300, 170);
setVisible(true);
}

关于java - 检查和交换按钮? GUI [有相应的操作命令吗?],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35436536/

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