下面是一个窗口的代码,当用户单击一个按钮时,该窗口会更改颜色,并在单击另一个按钮时更改标签的文本。
它有两个按钮、一个用于保存按钮的面板、一个标签和一个用于图形的面板。
概念解释:
首先,我添加了label
to the North
的一部分frame
使用默认值BorderLayout
。然后我添加了两个buttons
在一个单独的面板中,我添加了panel
to the South
主要的一部分frame
。然后我添加了panel
对于图形中的Center
主要的frame
.
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”按钮也变得部分不可见。
如果我们从右向左滑动与从左向右滑动,为什么会发生这两种不同的情况?
我已经搜索过,但无法找到准确的答案,所以最后我在这里问:为什么和如何?