2

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

这里是示例代码的链接(以 jbutton 身份登录,asdf 作为密码登录)

//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());
   }
});"
4

1 回答 1

5

您可以使用 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);
    }
}
于 2012-08-11T19:05:05.883 回答