为什么我的Button不会改变位置或移动?

时间:2016-02-19 01:38:48

标签: java jgrasp

我有这个代码可以使用,但每次更改坐标时,它都不起作用!我已经尝试了几乎所有的东西(希望有一个解决方案)来解决这个问题,但没有任何作用。我基本上希望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);   
  }
}

2 个答案:

答案 0 :(得分:1)

您可以将FlowLayout用于JFrame

// this line added
frame.setLayout(new FlowLayout(FlowLayout.LEFT));
frame.add(button);
frame.add(label);
frame.add(label2);

答案 1 :(得分:0)

感谢您的帮助。我刚刚在Oracle上找到了帮助我使用zip的Oracle。以下是我为使其发挥作用所做的工作:

>>> print(list([x, y] for x, y in zip(a, b)))
[[[1, 2, 3], 'Python'], [[4, 5, 6], 'Java']]

它有效,它完全符合我的要求。但我现在需要的是如何设置按钮的大小。