【发布时间】:2015-06-15 11:05:06
【问题描述】:
我想更改包含框架的背景颜色,但它似乎不起作用。我添加了调试消息并检查了控制台输出,开关正在工作并设置背景
MainFrame.setBackground() 方法。
import java.awt.*;
import java.awt.event.*;
public class StateWindow {
private Frame MainFrame;
private int bgcolor;
StateWindow() {
GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
int scrwidth = gd.getDisplayMode().getWidth();
int scrheight = gd.getDisplayMode().getHeight();
MainFrame = new Frame("StateWindow");
MainFrame.setSize(200, 200);
MainFrame.setLayout(new BorderLayout());
MainFrame.setLocation((scrwidth-250), (scrheight-450));
MainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent) {
System.exit(0);
}
});
bgcolor = 1;
Panel centerPanel = new Panel(new FlowLayout());
Label titlelabel = new Label("StateWindow", Label.CENTER);
Button changeBut = new Button("Change State");
changeBut.setSize(60, 30);
centerPanel.add(changeBut);
MainFrame.add(titlelabel, BorderLayout.NORTH);
MainFrame.add(centerPanel, BorderLayout.CENTER);
MainFrame.setBackground(Color.BLUE);
changeBut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
switch(bgcolor) {
case 1: MainFrame.setBackground(Color.GREEN); MainFrame.repaint(); bgcolor = 2; break;
case 2: MainFrame.setBackground(Color.ORANGE); MainFrame.repaint(); bgcolor = 3; break;
case 3: MainFrame.setBackground(Color.RED); MainFrame.repaint(); bgcolor = 1; break;
}
}
});
MainFrame.setVisible(true);
}
public static void main(String args[]) {
StateWindow StateWindow = new StateWindow();
}
}
【问题讨论】:
-
也许你必须重新粉刷框架?
-
重新粉刷吧,伙计
-
将
MainFrame.setLayout(new BorderLayout());更改为MainFrame.setLayout(new BorderLayout(20,20));以查看应用程序。工作(比您预期的要少)。 ;) 包含按钮的标签和面板都是不透明的,唯一的谜团是它们为什么会显示蓝色 BG.. 但是为什么要使用 AWT?它是一个许多 Java GUI 程序员从未使用过的 GUI 工具包,曾经编写过它的人忘记了 AWT 和 Swing 之间的许多差异。 .. -
.. 请参阅this answer 有很多充分的理由放弃使用支持 Swing 的组件的 AWT。
标签: java awt actionevent