gpt4 book ai didi

java - 从另一个 JButton 获取 JButton

转载 作者:行者123 更新时间:2023-11-30 06:29:05 26 4
gpt4 key购买 nike

我想在单击另一个 jbutton 时获得一个 jbutton。

Here the link for sample code(Log in as jbutton,asdf as a password)

//File Name= test1.java
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class test1 extends JFrame {
public static void main(String[] args) {
new test1();
}

public test1() {
super("Using JButton");
Container content = getContentPane();
content.setBackground(Color.white);
content.setLayout(new FlowLayout());
JButton button = new JButton("First");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("You clicked first button");
}
});
content.add(button);
JButton button2 = new JButton("Second");
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("You clicked second button");
}
});
content.add(button2);
pack();
setVisible(true);
}
}

如果我点击“第一”按钮,我想隐藏“第二”按钮。我的期望是,”

button.setName("something");
button.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){
System.out.println("You clicked first button");
btn2=getButtonByName("something");
btn2.setVisible(!btn2.isVisible());
}
});"

最佳答案

您可以使用 setVisible(boolean)要更改可见性,这里是一个基于已发布代码的示例:

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

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

public test() {
super("Using JButton");
Container content = getContentPane();
content.setBackground(Color.white);
content.setLayout(new FlowLayout());
final JButton button = new JButton("First");
final JButton button2 = new JButton("Second");
button.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {
System.out.println("You clicked first button");
button2.setVisible(!button2.isVisible());
}
});
content.add(button);

button2.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {
System.out.println("You clicked second button");
button.setVisible(!button.isVisible());
}
});
content.add(button2);
pack();
setVisible(true);
}
}

关于java - 从另一个 JButton 获取 JButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11916675/

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