现在是这样,我想点A的时候p1显红色,p2不显;点B的时候p1不显,p2显白色。现在不知道怎么加那个actionPerformed方法,求各位帮帮忙!
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class test extends JFrame
{
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
Choice combo = new Choice();
public test()
{
combo.add("A");
combo.add("B");
setLocation(300,100);
setSize(500,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
p1.setBackground(Color.red);
p2.setBackground(Color.white);
setLayout(null);
combo.setBounds(30,30,60,25);
add(combo);
p1.setBounds(0,200,500,400);
p2.setBounds(0,200,500,400);
add(p1);
add(p2);
p1.setVisible(false);
p2.setVisible(false);
setVisible(true);
}
public static void main(String args[])
{
new test();
}
}
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class test extends JFrame
{
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
Choice combo = new Choice();
public test()
{
combo.add("A");
combo.add("B");
setLocation(300,100);
setSize(500,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
p1.setBackground(Color.red);
p2.setBackground(Color.white);
setLayout(null);
combo.setBounds(30,30,60,25);
add(combo);
p1.setBounds(0,200,500,400);
p2.setBounds(0,200,500,400);
add(p1);
add(p2);
p1.setVisible(false);
p2.setVisible(false);
setVisible(true);
}
public static void main(String args[])
{
new test();
}
}
combo.addItemListener();
把期待的動作寫到監聽里
import java.awt.Color;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;import javax.swing.JFrame;
import javax.swing.JPanel;public class test extends JFrame {
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
Choice combo = new Choice(); public test() {
combo.add("A");
combo.add("B");
setLocation(300, 100);
setSize(500, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
p1.setBackground(Color.red);
p2.setBackground(Color.white);
setLayout(null);
combo.setBounds(30, 30, 60, 25);
add(combo);
p1.setBounds(0, 200, 500, 400);
p2.setBounds(0, 200, 500, 400);
add(p1);
add(p2);
p1.setVisible(false);
p2.setVisible(false);
setVisible(true);
combo.addItemListener(new ItemListener(){ public void itemStateChanged(ItemEvent e) {
if (combo.getSelectedItem().toString().equals("A")){
p1.setVisible(true);
p2.setVisible(false);
}
if (combo.getSelectedItem().toString().equals("B")){
p1.setVisible(false);
p2.setVisible(true);
}
}
});
} public static void main(String args[]) {
new test();
}
}改好了 你看看是不是你要的效果