我有一个JTabbedPane,里面有两个面板:panel1和panel2。我想在panel1中执行操作时更新位于panel2中的JComboBox。
在panel1中我有这段代码:
JPanel panel1 = new JPanel();
tabbedPane.addTab("panel1", null, panel1, null);
panel1.setLayout(null);
//some code
JButton btnSubmit = new JButton("Submit");
btnSubmit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// ?
}
});
btnSubmit.setBounds(12, 155, 150, 25);
panel1.add(btnSubmit);
在panel2中是我的JComboBox:
JPanel panel2 = new JPanel();
tabbedPane.addTab("panel2", null, panel2, null);
panel2.setLayout(null);
//some code
final JComboBox comboBox_2 = new JComboBox();
comboBox_2.setBounds(12, 240, 200, 24);
panel2.add(comboBox_2);
我该怎么做?
答案 0 :(得分:0)
这是一个快速而肮脏的实现。
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
public class Window extends JFrame {
JTabbedPane jtp = new JTabbedPane();
JPanel panel1 = new JPanel();
JPanel panel2= new JPanel();
JComboBox<String> comboBox_2 = new JComboBox<String>();
ActionListener buttonListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
comboBox_2.addItem("abc");
comboBox_2.addItem("def");
}
};
public Window() {
initP1();
initP2();
initJTP();
}
public void initJTP(){
jtp.add(panel1);
jtp.add(panel2);
this.add(jtp);
}
public void initP1(){
JButton btnSubmit = new JButton("Submit");
btnSubmit.setBounds(12, 155, 150, 25);
btnSubmit.addActionListener(buttonListener);
panel1.add(btnSubmit);
}
public void initP2(){
comboBox_2.setBounds(12, 240, 200, 24);
panel2.add(comboBox_2);
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
Window frame = new Window();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}