求代码!!!!!java

2025-01-02 22:38:30
推荐回答(2个)
回答1:

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

public class Practise{

public static void main(String[] args) {
new MyFrame();
}
}

class MyFrame extends JFrame
{
public MyFrame()
{
super("改变面板颜色");
final JPanel pan=new JPanel();
pan.setBackground(Color.RED);
JButton btnChangePanColor=new JButton("改变面板颜色");
btnChangePanColor.addActionListener(new ActionListener(){

@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
pan.setBackground(Color.GREEN);//改变面板颜色
}

});
pan.setLayout(new FlowLayout());
pan.add(btnChangePanColor);
this.getContentPane().add(pan);
this.setSize(300,300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//用户单击“关闭”按钮时关闭窗口
this.setResizable(false);
this.setVisible(true);
}
}

回答2:

class EventListener2 extends JFrame {
private JButton btBlue, btDialog;

public EventListener2() {
setTitle("Java GUI 事件监听处理");
setBounds(100, 100, 500, 350);
setLayout(new FlowLayout());

btBlue = new JButton("蓝色");
btDialog = new JButton("弹窗");

// 添加事件监听器(此处即为匿名类)
btBlue.addActionListener(new ActionListener() {
// 事件处理
@Override
public void actionPerformed(ActionEvent e) {
Container c = getContentPane();
c.setBackground(Color.BLUE);
}
});

// 并添加事件监听器
btDialog.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JDialog dialog = new JDialog();
dialog.setBounds(300, 200, 400, 300);
dialog.setVisible(true);
}
});

add(btBlue);
add(btDialog);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

}

//外部类DialogEventListener,实现ActionListener接口
class DialogEventListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
JDialog dialog = new JDialog();
dialog.setBounds(300, 200, 400, 300);
dialog.setVisible(true);
}
}

public class Demo{
public static void main(String args[]){
new EventListener2();
}
}
给你例子,应该可以实现了,希望能帮到你!