我是 JAVA 的初学者。我的问题是我的 GUI 有一个按钮。如果按下按钮,它应该在 GUI 上打印一些文本。但是当我按下按钮时。它会显示一个全新的框架,然后显示文本。我怎样才能将所有内容保持在同一个框架中,每次按下按钮时,都会弹出新文本。
1.构建了整个GUI
package JuiceFactory;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class JuiceFactory extends JFrame{
private CustomTextFeild customTextFeild;
private CustomButton customButton;
public JuiceFactory() {
JFrame jf = new JFrame("Welcome to a Juice Factory");
jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JPanel jPanel = new JPanel();
jPanel.setLayout(new BorderLayout(5,5));
jPanel.setBorder(BorderFactory.createLineBorder(Color.GRAY,10));
customTextFeild = new CustomTextFeild();
customButton = new CustomButton();
jPanel.add(customTextFeild,BorderLayout.CENTER);
jPanel.add(customButton,BorderLayout.EAST);
customButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new Juice();
}
});
jf.setContentPane(jPanel);
jf.setLocationRelativeTo(null);
jf.pack();
jf.setVisible(true);
}
public void printMessage(String Message){
customTextFeild.addText(Message);
}
}
2.JButton的偏好
class CustomButton extends JButton {
public static int Height = 20,Width=100;
public CustomButton(){
setOpaque(true);
new JButton();
setText("Order Juice");
}
public Dimension getPreferredSize(){
return (new Dimension(Width,Height)) ;
}
}
3.JTextFeild 偏好
class CustomTextFeild extends JTextArea{
private static final int GAP = 5;
public CustomTextFeild(){
setOpaque(true);
setBorder(BorderFactory.createLineBorder(Color.YELLOW,GAP,true));
setLineWrap(true);
setText("Juice Producing process.......\n");
}
public Dimension getPreferredSize(){
return (new Dimension(100,100)) ;
}
public void addText(String words){
append(words+"\n");
}
}
package JuiceFactory;
//where the program begins
public class Main extends CustomTextFeild{
public Main(){
new Juice();
}
public static void main(String[] args) {
JuiceFactory juiceFactory = new JuiceFactory();
}
}
4.显示过程
package JuiceFactory;
public class Juice extends JuiceFactory implements Runnable{
public Juice(){
Thread t1 = new Thread(this);
t1.start();
}
@Override
public void run() {
try {
printMessage("Put Fruits into the mixer.......");
Thread.sleep(3000);
printMessage("Juice is done!");
} catch (InterruptedException e){
e.printStackTrace();
}
}
}