我试图制作一个框架,在面板中控制操作,并在鼠标在控制面板中执行某些操作后创建一个 TextArea
以某种方式使用react。不知道为什么它不想在控制面板(北面板)内按下鼠标时更改 TextArea 的状态(背景颜色)。
我猜想 MouseEventHandler
类中对 textArea
对象的引用有问题,但不知道如何修复它。我用 getSource()
方法搜索,看来我是对的,但不知道如何使它正确。
主要
package MainPackage;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
public class Main {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
// Draw a frame
final DrawFrame frame = new DrawFrame(500, 500);
// Add yes-no confirmation of closing the application
frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
int confirmInt = JOptionPane.showOptionDialog(null,
"Are you sure?", "Exit confirmation",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE, null, null, null);
if (confirmInt == JOptionPane.YES_OPTION) {
frame.dispose();
}
}
});
// Create a textField
JTextArea textArea= new JTextArea();
//Set textField's variables
textArea.setBackground(Color.RED);
textArea.setPreferredSize(new Dimension(500, 300));
frame.add(textArea, BorderLayout.PAGE_END);
// Add a drawPanel
JPanel drawPanel = new JPanel(new BorderLayout());
//Set drawPanel's variables
drawPanel.setBackground(Color.CYAN);
drawPanel.setPreferredSize(new Dimension(500, 200));
drawPanel.addMouseListener(new MouseEventHandler(textArea));
frame.add(drawPanel, BorderLayout.PAGE_START);
//Set frame visible
frame.setVisible(true);
}
});
}
}
绘图框
package MainPackage;
import javax.swing.JFrame;
public class DrawFrame extends JFrame {
private static final long serialVersionUID = 8914767267085394262L;
public DrawFrame(int width, int height) {
setSize(width, height);
setTitle("MouseTest");
}
}
鼠标操作 包主包;
import java.awt.Color;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JTextArea;
class MouseEventHandler extends Main implements MouseListener
{ private JTextArea textArea;
public MouseEventHandler(JTextArea textArea)
{
textArea = this.textArea;
}
public void mouseClicked(MouseEvent event) {
textArea.setBackground(Color.BLUE);
}
public void mousePressed(MouseEvent event) {
}
public void mouseReleased(MouseEvent event) {
}
public void mouseEntered(MouseEvent event) {
}
public void mouseExited(MouseEvent event) {
}
}
最佳答案
查看您的 MouseEventHandler 构造函数。应该是:
public MouseEventHandler(JTextArea textArea) {
this.textArea = textArea;
}
比它有效。面板是蓝色的。
关于Java,swing,面板和文本区域,不会改变颜色,可能引用错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21945037/