我正在尝试获取它,以便当按下按钮时在 java 中显示一个组合框。这是我尝试过的。
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.TitledBorder;
public class main {
public static void main(String[] args) {
final JFrame testFrame = new JFrame();
testFrame.setSize(300,450);
testFrame.setLocation(150,250);
testFrame.setTitle("My frame");
testFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
testFrame.setResizable(true);
testFrame.setVisible(true);
testFrame.setLayout(new FlowLayout());
final JButton testButton = new JButton("show");
testFrame.add(testButton);
class MyListener implements ActionListener
{
public void actionPerformed(ActionEvent event) {
JButton clickedButton = (JButton) event.getSource();
if (clickedButton == testButton) {
String[] myArray = {"test","test2"};
JComboBox testingCom = new JComboBox(myArray);
testFrame.add(testingCom);
}
}
}
}
}
任何帮助将不胜感激。谢谢。
最佳答案
根据您的代码,您永远不会addActionListener
到您的按钮。
在您的 ActionListener
中,每次调用 actionPerformed
时,您都会创建一个组合框的新实例,如果这就是您想要的,您可能会感兴趣是否可见。
因此您可以像这样更改代码:
final JButton testButton = new JButton("show");
final JComboBox combo = new JComboBox(new String[]{"test1","test2"});
testButton.addActionListener(new ActionListener(){
// this is anonymous class
@Override
public void actionPerformed(ActionEvent evt){
//then you know that is attached to this button
combo.setVisible(!combo.isVisible());
}
});
combo.setVisible(Boolean.FALSE);
testFrame.add(testButton);
testFrame.add(combo);
关于java - 如何在java中单击按钮时显示组合框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22597362/