我試圖改變我的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);
}
的JLabel,JButton的....已(在API實現)水平和垂直對齊 – mKorbel