为什么如果我将框架的宽度和高度设置为 400(例如,可用空间较小),我该如何解决它以及如何在不剪切内容的情况下在中心放置一些内容? Example
public class Main extends JPanel{
static int width = 400;
static int height = 400;
static int arcWidth = 400;
static int arcHeight = 400;
public static void main(String args[]){
JFrame frame = new JFrame();
JFrame mainContent = new JFrame();
Main panel = new Main();
frame.setSize(width, height);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Clock");
frame.add(panel);
frame.setVisible(true);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(Color.BLACK);
g2.setStroke(new BasicStroke(4,BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
g.drawArc(width/2 -arcWidth/2, height/2 - arcHeight/2, arcWidth, arcHeight, 0, 360);
}
}
最佳答案
首先使用“实际”值而不是“魔法”值
getWidth
和 getHeight
将告诉您组件的“实际”大小是多少
@Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(Color.BLACK);
g2.setStroke(new BasicStroke(4,BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
g.drawArc(getWidth()/2 -arcWidth/2, getHeight()/2 - arcHeight/2, arcWidth, arcHeight, 0, 360);
}
关于出现问题的原因,请参阅:
关于java - 为什么 JFrame 不居中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48857994/