你可以参考一下,希望采纳
import java.awt.*;
import javax.swing.*;
public class MyFrame extends JFrame {
public MyFrame() {
add(new MyPanel());
setDefaultCloseOperation(EXIT_ON_CLOSE);
setBounds(400, 300, 200, 130);
setVisible(true);
}
class MyPanel extends JPanel {
private JButton b1, b2;
private JLabel l1;
private JPanel p1;
public MyPanel() {
b1 = new JButton("Left");
b2 = new JButton("Right");
l1 = new JLabel("PUSH ME");
p1 = new JPanel();
p1.setBackground(Color.BLUE);
p1.setPreferredSize(new Dimension(200, 40));
p1.add(b1);
p1.add(b2);
add(l1);
add(p1);
setBackground(Color.CYAN);
b1.addActionListener((e) -> {
l1.setText("Left");
});
b2.addActionListener((e) -> {
l1.setText("Right");
});
}
}
public static void main(String[] args) {
new MyFrame();
}
}