我正在尝试做一个简单的作业,在其中显示一行文本,显示门对象是否打开。在此之下,我直观地表示它(使用 drawRect)方法。在底部我有两个按钮,可以打开或关闭门,从而改变文本和矩形。
编辑:现在可以编译的代码列表:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Test {
public static void main(String[] args) {
// Creates new JFrame called frame, with title "Door"
// (displayed at top of screen).
JFrame frame = new JFrame ("Door");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
TempDoorPanel panel = new TempDoorPanel();
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
}
class Door {
private String state;
private String message;
Door (String state) {
this.state = state;
message = "The door is currently closed.";
}
public boolean isOpen() {
return state.equals ("open");
}
public boolean isClosed() {
return state.equals ("closed");
}
public void setState(String state) {
this.state = state;
}
public String getMessage() {
return message;
}
public void open() {
if (state.equals("open")) {
message = "The door is already open.";
}
else {
state = "open";
message = "The door has been opened.";
}
}
public void drawOpenDoor (Graphics page) {
page.drawRect(100, 100, 100, 100);
}
}
class TempDoorPanel extends JPanel {
private Door door;
private JTextField currentStateOfDoor;
private JButton openDoor;
public TempDoorPanel() {
super.setLayout(new BorderLayout());
door = new Door("closed");
super.setBackground(Color.blue);
super.setPreferredSize(new Dimension (360, 400));
currentStateOfDoor = new JTextField(14);
currentStateOfDoor.setText(door.getMessage());
super.add(currentStateOfDoor, BorderLayout.NORTH);
openDoor = new JButton("Open Door");
class openDoorListener implements ActionListener {
public void actionPerformed (ActionEvent event) {
door.open();
repaintText();
}
}
openDoorListener openlistener = new openDoorListener();
openDoor.addActionListener(openlistener);
JPanel holder = new JPanel();
holder.add(openDoor);
super.add(holder, BorderLayout.SOUTH);
}
private void repaintText() {
currentStateOfDoor.setText(door.getMessage());
// These methods are from Door class.
}
public void paintComponent (Graphics page) {
super.paintComponent(page);
if (door.isOpen())
door.drawOpenDoor(page);
// isOpen is a boolean method from Door class.
}
}
什么有效:
- 按钮一个接一个地出现在屏幕上的正确位置,在 BorderLayout.SOUTH。
- JTextField 出现在正确的位置,在 BorderLayout.NORTH
- 最后,蓝色区域出现在屏幕中央的正确位置。
我要解决的问题:
- 我不知道如何在该蓝色区域的中间正确显示矩形。我试过改变矩形的坐标和大小,这根本不会改变它的大小。我可以让它 drawRect(100, 100, 100, 100) 并且它没有任何改变。
- 我也知道矩形目前隐藏在 JTextField 的左上角后面,但我不知道如何将它移到 BorderLayout 中。
问题:
- 如何在 BorderLayout 中放置一个矩形?
- 在这样的布局中,如何调整通过 drawrect() 绘制的矩形的大小?