JPanel 中没有显示矩形
No rectangle shown in JPanel
我试图在 JPanel
中绘制一个矩形,但矩形未显示。我错过了什么?
这是我到目前为止所尝试过的方法。
public class selectSeat extends JFrame {
JPanel panel = new JPanel();
public static void main(String[] args) {
selectSeat frameTabel = new selectSeat("","","");
}
public selectSeat(String title, String day, String time)
{
super("Select Seat");
setSize(350,350);
setLocation(500,280);
panel.setLayout(null);
RectDraw rect= new RectDraw();
panel.add(rect);
getContentPane().add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
private static class RectDraw extends JPanel
{
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawRect(230,80,10,10);
g.setColor(Color.RED);
g.fillRect(230,80,10,10);
}
public Dimension getPreferredSize() {
return new Dimension(50, 20); // appropriate constants
}
}
}
您正在绘制矩形,但它位于 280、80 处,远远超出可见 JPanel 的范围。理解绘图位置是相对于JPanel自身内部坐标的。
注意到您正在使用绝对布局(空布局)。需要 Component.setbounds 才能将对象定位到位。
public Test(String title, String day, String time)
{
super("Select Seat");
setSize(350,350);
setLocation(500,280);
panel.setLayout(null);
RectDraw rect= new RectDraw();
rect.setBounds(0, 0, 100, 100);
panel.add(rect);
getContentPane().add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
查看详情:
https://docs.oracle.com/javase/tutorial/uiswing/layout/problems.html
注意:尝试使用 Ctrl+Shift+F1 也可以从 AWT 获取调试消息。
我试图在 JPanel
中绘制一个矩形,但矩形未显示。我错过了什么?
这是我到目前为止所尝试过的方法。
public class selectSeat extends JFrame {
JPanel panel = new JPanel();
public static void main(String[] args) {
selectSeat frameTabel = new selectSeat("","","");
}
public selectSeat(String title, String day, String time)
{
super("Select Seat");
setSize(350,350);
setLocation(500,280);
panel.setLayout(null);
RectDraw rect= new RectDraw();
panel.add(rect);
getContentPane().add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
private static class RectDraw extends JPanel
{
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawRect(230,80,10,10);
g.setColor(Color.RED);
g.fillRect(230,80,10,10);
}
public Dimension getPreferredSize() {
return new Dimension(50, 20); // appropriate constants
}
}
}
您正在绘制矩形,但它位于 280、80 处,远远超出可见 JPanel 的范围。理解绘图位置是相对于JPanel自身内部坐标的。
注意到您正在使用绝对布局(空布局)。需要 Component.setbounds 才能将对象定位到位。
public Test(String title, String day, String time)
{
super("Select Seat");
setSize(350,350);
setLocation(500,280);
panel.setLayout(null);
RectDraw rect= new RectDraw();
rect.setBounds(0, 0, 100, 100);
panel.add(rect);
getContentPane().add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
查看详情: https://docs.oracle.com/javase/tutorial/uiswing/layout/problems.html
注意:尝试使用 Ctrl+Shift+F1 也可以从 AWT 获取调试消息。