我想让用户能够用鼠标“绘图”(单击并拖动)来创建和调整JTextArea的大小。同样,我希望文本区域可以重新调整。
这样的事情:
浮现在脑海中,但作为一个JTextArea而不仅仅是一个正方形。
Java中有什么东西可以让我轻松做到这一点吗?我首先想到允许用户绘制一个矩形,然后抓住坐标和大小来创建JTextArea。我不确定如何进行大小调整。
编辑:“组件调整器/ Reszing”是我正在寻找的术语,我在这里添加它以防其他人正在寻找类似的东西!
答案 0 :(得分:2)
通过调用setBounds(...)可以很容易地调整JTextArea的大小 - 或者更好地保存它的JScrollPane,但是你需要在容器上使用null或类似的(JLayeredPane)布局保存JTextArea并且可能需要在调整JScrollPane大小后重新绘制容器。您还必须重新验证滚动窗格的视口,以便重新布置它所包含的文本区域。
如,
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
@SuppressWarnings("serial")
public class ResizeableTextArea extends JPanel {
private static final int PREF_WIDTH = 700;
private static final int PREF_HEIGHT = 500;
private static final int ROWS = 60;
private static final int COLS = 80;
private static final Color RECT_COLOR = new Color(180, 180, 255);
private JTextArea textArea = new JTextArea(ROWS, COLS);
private JScrollPane scrollPane = new JScrollPane(textArea);
private int x, y, width, height;
private boolean drawRect = false;
public ResizeableTextArea() {
setLayout(null);
add(scrollPane);
MyMouseAdapter myMouseAdapter = new MyMouseAdapter();
addMouseListener(myMouseAdapter);
addMouseMotionListener(myMouseAdapter);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (drawRect) {
g.setColor(RECT_COLOR);
g.drawRect(x, y, width, height);
}
}
@Override
public Dimension getPreferredSize() {
return new Dimension(PREF_WIDTH, PREF_HEIGHT);
}
private class MyMouseAdapter extends MouseAdapter {
private int innerX, innerY;
@Override
public void mousePressed(MouseEvent e) {
x = e.getX();
y = e.getY();
innerX = x;
innerY = y;
width = 0;
height = 0;
drawRect = true;
}
@Override
public void mouseDragged(MouseEvent e) {
calcBounds(e);
drawRect = true;
ResizeableTextArea.this.repaint();
}
@Override
public void mouseReleased(MouseEvent e) {
calcBounds(e);
drawRect = false;
scrollPane.setBounds(x, y, width, height);
scrollPane.getViewport().revalidate();
ResizeableTextArea.this.repaint();
}
private void calcBounds(MouseEvent e) {
width = Math.abs(innerX - e.getX());
height = Math.abs(innerY - e.getY());
x = Math.min(innerX, e.getX());
y = Math.min(innerY, e.getY());
}
}
private static void createAndShowUI() {
JFrame frame = new JFrame("ResizeableTextArea");
frame.getContentPane().add(new ResizeableTextArea());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
答案 1 :(得分:2)
答案 2 :(得分:2)
您应该可以使用Component Resizer。
答案 3 :(得分:1)
那不是很好idea,确定可以将Image or ImageIcon作为BackGround,更好地用于JLabel Icon,然后你可以{{3很容易