【JAVA编程】创建Frame类型窗口,在窗口中添加两个不同颜色的Panel面板,每个面板中添加两个按钮组件、、

【JAVA编程】创建Frame类型窗口,在窗口中添加两个不同颜色的Panel面板,每个面板中添加两个按钮组件、、,第1张

setBackground设置背景色!

布局随便选,下面程序使用了边框(BorderLayout)和流水(FlowLayout)2种布局方式!

顺便帮你加了一个按钮事件!有问题再追问吧!~

import java.awt.BorderLayout

import java.awt.Color

import java.awt.Container

import java.awt.FlowLayout

import java.awt.event.ActionEvent

import java.awt.event.ActionListener

import javax.swing.JButton

import javax.swing.JFrame

import javax.swing.JLabel

import javax.swing.JPanel

public class Test extends JFrame implements ActionListener {

private JPanel panel0 = null, panel2 = null

private JButton b1 = null, b2 = null, b3 = null, b4 = null

public Test() {

Container c = this.getContentPane()

//边框布局

c.setLayout(new BorderLayout())

//创建panel

panel0 = new JPanel()

panel2 = new JPanel()

//为2个panel设置底色

panel0.setBackground(Color.red)

panel2.setBackground(Color.BLUE)

//2个panel都是用流水布局

panel0.setLayout(new FlowLayout())

panel2.setLayout(new FlowLayout())

//创建按钮

b1 = new JButton("panel2黄色")

b2 = new JButton("panel2绿色")

b3 = new JButton("panel0橙色")

b4 = new JButton("panel0灰色")

/**

* 添加按钮事件

*/

b1.addActionListener(this)

b2.addActionListener(this)

b3.addActionListener(this)

b4.addActionListener(this)

/**

* 将按钮添加相应panel上

*/

panel0.add(b1)

panel0.add(new JLabel())

panel0.add(b2)

panel2.add(b3)

panel2.add(b4)

/**

* 将panel添加到容器

*/

c.add(panel0, BorderLayout.CENTER)

c.add(panel2, BorderLayout.EAST)

this.setSize(500, 500)

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)

this.setVisible(true)

}

public static void main(String[] args) {

new Test()

}

@Override

public void actionPerformed(ActionEvent e) {

// TODO Auto-generated method stub

if (e.getSource() == b1) {

panel2.setBackground(Color.yellow)

} else if (e.getSource() == b2) {

panel2.setBackground(Color.green)

} else if (e.getSource() == b3) {

panel0.setBackground(Color.ORANGE)

} else if (e.getSource() == b4) {

panel0.setBackground(Color.GRAY)

}

}

}

你是不是用的awt而不是Swing?

首先想要这么多按钮,要new这么多次是肯定的,不可能new一次然后反复添加就可以了。因为java组件容器中在添加时首先会检测该组件是否已经包含在一个容器中,如果已经包含,就会先将其移除,然后再重新添加。

然后关于慢的问题:我相信你是用的是AWT而不是Swing,这两个库的速度完全不一样,如果你使用Swing,添加10000个按钮并创建窗体应该在1秒左右就能完成了

下面这个代码你试一下就知道了:

import java.awt.*

import javax.swing.*

/**

*

* @author Jeky

*/

public class ButtonsDemo extends JFrame {

public ButtonsDemo() {

this.setLayout(new FlowLayout())

for (int i = 0i <10000i++) {

JButton button = new JButton()

button.setPreferredSize(new Dimension(5, 5))

this.add(button)

}

this.setSize(800, 800)

this.setDefaultCloseOperation(EXIT_ON_CLOSE)

}

public static void main(String[] args) {

new ButtonsDemo().setVisible(true)

}

}


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/bake/8012065.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-12
下一篇 2023-04-12

发表评论

登录后才能评论

评论列表(0条)

保存