我正在尝试更改 JFrame 中按钮的大小。我看到这个问题的每个回复都说要使用 button.setPreferredSize(new Dimension(x, y)) 或 button.setSize(new Dimension(x, y)),但这些都不起作用。按钮标题显示在正确的位置,但按钮占据了整个屏幕。我还尝试将按钮添加到框架而不是窗格中。当我这样做时,按钮的大小是正确的,但它在图像之外。如何定位和调整此按钮的大小以使其显示在图像上?
public ImageTest(String title, String imageSource, int minimum, int middle, int maximum, int curr, boolean x) { // Extends JFrame...
frame = new JFrame();
frame.setTitle(title);
frame.setLayout(new GridBagLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
maxim = maximum;
minim = minimum;
mercSize(minim, maxim, curr); //change size of mercury in thermometer
pane = new PaintPane(new ImageIcon(imageSource).getImage());
pane.setLayout(new BorderLayout());
frame.add(pane);
b1 = new JButton("Increase Temp");
b1.setPreferredSize(new Dimension(100, 100)); //Button does not work yet
b1.setBorder(BorderFactory.createEmptyBorder(560,250,0,0));
b1.setLocation(95, 45);
pane.add(b1);
frame.pack();
min = new JLabel("" + minimum);
min.setFont(min.getFont().deriveFont(Font.BOLD, 28));
if(x == true) min.setForeground(Color.BLACK); //Changes the font color to match the image
else min.setForeground(Color.WHITE);
min.setVerticalAlignment(JLabel.TOP);
min.setVerticalTextPosition(JLabel.TOP);
min.setBorder(BorderFactory.createEmptyBorder(445, 150, 0, 0)); //Positions the text
pane.add(min);
frame.pack();
mid = new JLabel("" + middle);
mid.setFont(mid.getFont().deriveFont(Font.BOLD, 28));
if(x == true) mid.setForeground(Color.BLACK); //Changes the font color to match the image
else mid.setForeground(Color.WHITE);
mid.setVerticalAlignment(JLabel.TOP);
mid.setVerticalTextPosition(JLabel.TOP);
mid.setBorder(BorderFactory.createEmptyBorder(240, 150, 0, 0)); //Positions the text
pane.add(mid);
frame.pack();
max = new JLabel("" + maximum);
max.setFont(max.getFont().deriveFont(Font.BOLD, 28));
if(x == true) max.setForeground(Color.BLACK); //Changes the font color to match the image
else max.setForeground(Color.WHITE);
max.setVerticalAlignment(JLabel.TOP);
max.setVerticalTextPosition(JLabel.TOP);
max.setBorder(BorderFactory.createEmptyBorder(35, 150, 0, 0)); //Positions the text
pane.add(max);
frame.pack();
temp = new JLabel("Current Temperature: " + curr);
temp.setFont(temp.getFont().deriveFont(Font.BOLD, 28));
if(x == true) temp.setForeground(Color.BLACK); //Changes the font color to match the image
else temp.setForeground(Color.WHITE);
temp.setVerticalAlignment(JLabel.TOP);
temp.setVerticalTextPosition(JLabel.TOP);
temp.setBorder(BorderFactory.createEmptyBorder(560, 120, 0, 0)); //Positions the text
pane.add(temp);
frame.pack();
error = new JLabel();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}