我是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();
}
}
}