【发布时间】:2017-09-08 18:21:04
【问题描述】:
我对 java 还是很陌生,不久前我写了一个魔术 8 球程序。好吧,我刚刚了解了 JFrames 和 JPanels,所以我想更新它。 我在一些事情上遇到了麻烦,我不知道这是否要求太多,因为以前从未使用过这个网站。我不太了解动作侦听器,我需要帮助将一个放在 b 按钮上,以使其绘制一个新的 JPanel,该 JPanel 绘制我的随机选择器语句。那是另一回事,我如何让它绘制我的数组元素之一?
window
package pack;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class window extends ball {
public static void main (String []args) {
JFrame f = new JFrame("hello");
JPanel p = new JPanel();
JLabel l = new JLabel("What do you ask the magic conch shell?");
JTextField t = new JTextField(25);
JButton b = new JButton();
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) { }
});
//panel
b.setText("Ask");
p.add(l);
p.add(b);
p.add(t);
//frame
f.add(p);
f.setSize(300, 400);
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}}
ball
package pack;
import java.util.Scanner;
import java.util.Random;
public class ball {
public static void main(String[]args) {
String question = ("What do you ask the Magic Conch shell?");
Scanner userInput =new Scanner(System.in);
String answer = userInput.nextLine();
String[] array;
array = new String[8];
array[0] = ("yes");
array[1] = ("no");
array[2] = ("maybe");
array[3] = ("never");
array[4] = ("ask again later");
array[5] = ("positive");
array[6] = ("unlikely");
array[7] = ("yes");
Random dice = new Random();
int n = dice.nextInt(8);
System.out.println(array[n]);
}
}
【问题讨论】:
-
对不起,我刚刚编辑了它
-
make it paint a new JPanel that paints my random chooser statements- 为什么需要在面板上绘制任何东西?只需使用 JLabel 来显示文本。因此,您可以使用所需的组件创建一个简单的 JFrame。您可以将 JLabel 设置为仅显示“”(单个空格)。然后在您的 ActionListener 中,您只需将标签的文本设置为您想要的任何值。
标签: java swing jbutton actionlistener paint