问题描述:

I want to get one jbutton when I click another 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);

}

}

If I click "First" button, I want to hide "second" button. My Expectation is like,"

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());

}

});"

网友答案:

You can use setVisible(boolean) to change visibility, here is an example based on posted code:

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);
    }
}
相关阅读:
Top