如何指定以下面板的坐标,而不是使其与中心对齐。
我已经尝试了很多,并使用了不同的布局,但是仍然无法正常工作。请帮我解决这个问题。谢谢!
这是我的代码。
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Lesson2 extends JFrame {
private static final long serialVersionUID = -198253288329146091L;
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Lesson2 frame = new Lesson2();
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Lesson2() {
contentPane = new JPanel();
setContentPane(contentPane);
JPanel panel = new JPanel() {
private static final long serialVersionUID = -5974584127539186578L;
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.GREEN);
g.fillRect(0, 0, 500, 500);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(500, 500);
}
};
contentPane.add(panel);
}
}
这是现在的样子的一个例子 https://prnt.sc/moe3al
这是使用具有设定大小的空布局编辑的最终代码
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Lesson1 extends JFrame {
private static final long serialVersionUID = -198253288329146091L;
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Lesson1 frame = new Lesson1();
frame.setSize(1000, 1000);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Lesson1() {
contentPane = new JPanel();
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panel = new JPanel() {
private static final long serialVersionUID = -5974584127539186578L;
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.GREEN);
g.fillRect(0, 0, 500, 500);
}
};
panel.setLayout(null);
panel.setSize(500, 500);
contentPane.add(panel);
}
}
答案 0 :(得分:-2)
所有Swing / AWT容器都将FlowLayout用作默认布局管理器,这导致组件居中。如果需要更多控制,可以通过调用contentPane.setLayout(null)并通过panel.setBounds()设置组件的坐标来使用Absolute Positioning,但是请注意,它可能无法优雅地处理窗口调整大小。