[英]How come my Button won't change position or move?
我有這段代碼可以正常工作,但是每次更改坐標時,它都行不通! 我已經嘗試了幾乎所有方法(希望有解決方案)來解決此問題,但是沒有任何效果。 我基本上希望button
出現在label
旁邊。
import java.util.*;
import java.awt.*;
import javax.swing.*;
public class jframetest
{
public static void main(String args[])
{
JFrame frame = new JFrame("Not Main");
frame.setPreferredSize(new Dimension(200, 200));
JLabel label = new JLabel("Test");
Random generate = new Random();
Random rand = new Random();
String[] name = {"Landry", "Azariah", "Oakley", "Lennon", "Charlie", "Skyler", "Dakota", "Armani", "Phoenix" , "Justice", "Casey", "Emory", "Remy", "Emerson", "Amari", "Roxie", "Hayden", "River", "Milan", "Tatum", "Jessie", "Finley", "Riley", "Rowan", "Sage", "Jamie", "Rory", "Harley", "Leighton", "Peyton", "Dallas", "Remington", "Quinn", "Alexis", "Sawyer", "Kamryn", "Parker", "Avery", "Eden", "Lyric", "Elliot", "Reese", "Zion", "Rylan", "Jordan", "Taylor", "Morgan", "Kendall", "Rylee", "Ryan", "Reagan", "Logan", "Hunter", "Carter"};
String[] images = new String[]{"image1.jpg", "image2.jpg", "image3.jpg", "image4.jpg", "image5.jpg", "image6.jpg", "image7.jpg", "image8.jpg", "image9.jpg", "image10.jpg", "image11.jpg", "image12.jpg", "image13.jpg"};
int index = (int) (Math.random() * (images.length - 1));
JButton button = new JButton(new ImageIcon(images[index]));
button.setPreferredSize(new Dimension(200, 200));
button.setBounds(5, 5, 100, 50);
JLabel label2 = new JLabel("Customer: " + name[generate.nextInt(54)]);
label2.setBounds(10, 10, 50, 25);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(button);
frame.setVisible(true);
frame.pack();
label.setText("Test");
frame.add(button);
frame.add(label);
frame.add(label2);
}
}
您可以將FlowLayout
用於JFrame
// this line added
frame.setLayout(new FlowLayout(FlowLayout.LEFT));
frame.add(button);
frame.add(label);
frame.add(label2);
謝謝您的幫助。 我剛剛在Oracle網上找到了它,這有助於我使用BorderLayout
。 這是我為使其工作而要做的事情:
frame.add(button, BorderLayout.LINE_START);
它可以工作,並且確實可以實現我想要的功能。 但是我現在需要的是如何設置按鈕的大小。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.