用Java编写应用程序如下:布局采用BorderLayout组件与组件间隔都为10其中按钮1的背景色为红色字体颜色为白色setForeground。第二个按钮的颜色为:new Color100100255
,字体颜色为黑色(setForeground)。当按钮1被点击时,在控制台输出“按钮1被点击了”,当按钮2被点击时,在控制台输出“按钮2被点击了”。
代码如下:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MyFrame extends JFrame implements ActionListener {
private JButton button1, button2;
public MyFrame() {
super("My Frame");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 200);
setLocationRelativeTo(null);
button1 = new JButton("Button 1");
button1.setBackground(Color.RED);
button1.setForeground(Color.WHITE);
button1.addActionListener(this);
button2 = new JButton("Button 2");
button2.setBackground(new Color(100, 100, 255));
button2.setForeground(Color.BLACK);
button2.addActionListener(this);
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout(10, 10));
panel.add(button1, BorderLayout.WEST);
panel.add(button2, BorderLayout.EAST);
getContentPane().add(panel);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button1) {
System.out.println("Button 1 was clicked.");
} else if (e.getSource() == button2) {
System.out.println("Button 2 was clicked.");
}
}
public static void main(String[] args) {
new MyFrame();
}
}
``
原文地址: https://www.cveoy.top/t/topic/hsQt 著作权归作者所有。请勿转载和采集!