【发布时间】:2018-05-03 18:28:06
【问题描述】:
我想在图像前面/顶部添加 JTextArea。每当我尝试将其添加到将其定位为 BorderLayout.CENTER/TOP 等的框架中时,文本都会添加到图像上方。当我尝试 frame.add(textArea) 时,整个图像不会显示。
我应该在我的 ComponentImage 类中添加 JTextArea 吗?
这是我的代码:
GUI 类:
package test;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class GUILab {
private Image image;
public JTextArea textArea;
public JPanel bottomPanel;
public JTextField jtf;
public JButton updateButton;
public static void main(String[] args) {
JFrame frame = new JFrame("Frame");
Toolkit kit = Toolkit.getDefaultToolkit();
Dimension screenSize = kit.getScreenSize();
int screenWidth = screenSize.width;
int screenHeight = screenSize.height;
int frameWidth = screenWidth / 2;
int frameHeight = screenHeight / 2;
frame.setSize(frameWidth, frameHeight);
frame.setTitle("");
frame.setLocation(100, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
//Call image
ComponentImage image = new ComponentImage();
frame.add(image, BorderLayout.CENTER);
//TextField: adding to bottomPanel, then add bottomPanel to frame
JTextArea textArea = new JTextArea(8, 20);
JPanel bottomPanel = new JPanel();
JTextField jtf = new JTextField("Test", 25);
JButton updateButton = new JButton("Update");
bottomPanel.add(jtf);
bottomPanel.add(updateButton);
updateButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event) {
textArea.append(jtf.getText()+"\n");
System.out.println(jtf.getText());
}
});
frame.add(bottomPanel, BorderLayout.SOUTH);
//frame.add(textArea);
frame.pack();
frame.setVisible(true);
}
}
ComponentImage 类:
package test;
import java.awt.Graphics;
import javax.swing.JComponent;
import java.awt.Dimension;
import java.awt.Image;
import javax.swing.ImageIcon;
public class ComponentImage extends JComponent {
private Image image;
private int compWidth=400;
private int compHeight=300;
public GUILab guilab;
public void paintComponent(Graphics g) {
image=new ImageIcon("bg1.jpg").getImage();
g.drawImage(image, 0,0,null);
g.drawString("Test", 100, 120);
}
public Dimension getPreferredSize() {
return new Dimension(compWidth, compHeight);
}
}
编辑:澄清一下:当文本输入到 TextField 并单击更新按钮时,该文本应出现在图像顶部
【问题讨论】:
-
您需要将您的文本区域添加到您的
ComponentImage对象中。像image.add(new JScrollPane(textArea))这样的东西。另外ComponentImage extends JPanel也会更好。 -
这太可怕了
public void paintComponent(Graphics g) { image=new ImageIcon("bg1.jpg").getImage();将其替换为public void paintComponent(Graphics g) { super.paintComponent(g);image本身应声明为类的属性并在构造函数或初始化中加载一次方法。另请注意,ComponentImage的首选大小应基于图像大小和添加到其中的文本区域的组合(宽度和高度中的较大者)。我个人倾向于将文本直接写入图像,除非用户.. -
.. 需要编辑或以其他方式将其输入 GUI。
标签: java image swing jtextarea