【发布时间】:2015-10-20 13:47:06
【问题描述】:
下面是一个窗口的代码,当用户点击一个按钮时它会改变颜色,当他点击另一个按钮时会改变标签的文本。
它有两个按钮,一个用于按住按钮的面板、一个标签和一个用于图形的面板。
概念解释:
首先,我使用默认的BorderLayout 将label 添加到frame 的North 部分。然后我在一个单独的面板中添加了两个buttons,并将panel 添加到主要frame 的South 部分。然后我在主frame的Center中为图形添加了panel。
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
class GuiAnimation extends JFrame
{
JButton colorBut;
JButton labelBut;
JLabel label;
PaintCanvas firstCanvas;
JPanel buttonPanel;
GuiAnimation()
{
colorBut = new JButton("Color Change");
labelBut = new JButton("Text Change");
label = new JLabel("I will change");
firstCanvas = new PaintCanvas();
buttonPanel = new JPanel();
addListener(); //May be i should make different method for different component for the flexibility.But here program is small.
addEverything();
}
private void addListener()
{
colorBut.addActionListener(new ColorListener());
labelBut.addActionListener(new LabelListener());
}
private void setButtonInPanel()
{
int pad = 80;
buttonPanel.setLayout(new FlowLayout(FlowLayout.LEADING, pad, 20));
buttonPanel.add(colorBut);
buttonPanel.add(labelBut);
}
void addEverything() //Here things are done with Layouts.
{
//add the label to the top of the window.
this.getContentPane().add(BorderLayout.NORTH, label);
//add button inside the panel.
setButtonInPanel();
//add that panel that has button to the frame.
this.getContentPane().add(BorderLayout.SOUTH, buttonPanel);
//add the graphics canvas to the frame.
this.getContentPane().add(BorderLayout.CENTER, firstCanvas);
}
class PaintCanvas extends JPanel
{
public void paintComponent(Graphics g)
{
int red = (int) (Math.random() * 255);
int green = (int) (Math.random() * 255);
int blue = (int) (Math.random() * 255);
Color randomColor = new Color(red, green, blue);
g.setColor(randomColor);
g.fillRect(0, 0, getWidth(), getHeight());
}
}
class ColorListener implements ActionListener
{
public void actionPerformed(ActionEvent e){
firstCanvas.repaint();
}
}
class LabelListener implements ActionListener
{
public void actionPerformed(ActionEvent e){
if ( label.getText().equals("I will change"))
label.setText("yes yes yes clicked");
else
label.setText("I will change");
}
}
public static void main(String[] args) {
GuiAnimation gui = new GuiAnimation();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setSize(500,600);
gui.setVisible(true);
}
}
这是上面代码的输出。到目前为止一切顺利。
但是当我开始从右侧滑动时,会发生以下情况:
现在窗口的右墙向左移动,但按钮是静止的。继续我们得到:
但是,如果我们从左侧调整大小,我们会得到:
这里的按钮似乎与框架一起向右移动(保持与框架边界的距离)。这与前一种情况相反。但为什么?怎么样?
最后,我们有:
继续此操作,“ColorChange”按钮也变得部分不可见。
如果我们从右向左滑动而不是从左向右滑动,为什么会发生这两种不同的事情?
我已经搜索过,但我无法找到准确的答案,所以最后我在这里问:为什么和如何?
【问题讨论】:
-
不要在paintComponent() 方法中生成随机颜色。每次调整框架大小时,背景都会改变。根据添加到框架的按钮,它应该仅在您单击“颜色更改”按钮时更改。因此,当您单击按钮时,您应该生成随机颜色并使用该颜色调用 setBackground(...) 方法。然后面板将自行重新绘制。
标签: java swing window panel frame