Max*_*Max 6 java swing transparency jtextarea background-color
我在设置文本后设置JTextArea的背景颜色时遇到问题.代码如下:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
public class Test extends JFrame {
private JTextArea area;
public Test() {
this.setLayout(new BorderLayout());
this.add(this.area = new JTextArea(), BorderLayout.CENTER);
this.add(new JButton(clickAction), BorderLayout.SOUTH);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setPreferredSize(new Dimension(500, 200));
this.pack();
this.area.setText("this is just a test");
this.setVisible(true);
}
Action clickAction = new AbstractAction("Click") {
@Override
public void actionPerformed(ActionEvent e) {
area.setBackground(new Color(0, 0, 123, 138));
// repaint();
}
};
public static void main(String[] args) {
new Test();
}
}
Run Code Online (Sandbox Code Playgroud)
如果单击该按钮,JTextArea的背景会发生变化,但我也会在文本区域中获得一些工件."重新绘制"似乎解决了这个问题,但在我的应用示例中,它没有帮助,所以我想知道是否有更好的解决方案.

jef*_*eff -1
我最近在学校做的一个项目也遇到了同样的问题。您也必须在框架上调用重绘(因此我更改了 ActionListener 以在构造函数中采用 JFrame)。我还重新排列了代码以使用 JFrame 的内容窗格。这似乎对我有用:
public Test() {
this.area = new JTextArea();
this.getContentPane().setLayout(new BorderLayout());
this.getContentPane().add(area, BorderLayout.CENTER);
JButton button = new JButton(new MyClickAction(this));
button.setText("Click Me!");
this.getContentPane().add(button, BorderLayout.SOUTH);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setPreferredSize(new Dimension(500, 200));
this.area.setText("this is just a test");
this.pack();
this.setVisible(true);
}
public static void main(String[] args) {
new Test();
}
private class MyClickAction extends AbstractAction
{
private JFrame frame;
public MyClickAction(JFrame frame) {
this.frame = frame;
}
@Override
public void actionPerformed(ActionEvent e) {
area.setBackground(new Color(0, 0, 123, 138));
frame.repaint();
}
}
Run Code Online (Sandbox Code Playgroud)