[英]Change JTextArea value from another class
如何允許另一個類從另一個類修改JTextArea?
例如,假設我有2個類:
Panel.java
public class Panel extends JPanel
{
private JTextArea instructions;
public Panel()
{
instructions = new JTextArea(15,15);
add(instructions);
}
}
MenuBar.java
public class MenuBar extends JMenuBar
{
private JMenuItem openMenuItem,;
public MenuBar()
{
JMenu fileMenu = new JMenu("File");
openMenuItem = new JMenuItem("Open");
fileMenu.add(openMenuItem);
add(fileMenu);
MenuListener listener = new MenuListener();
openMenuItem.addActionListener(listener);
}
private class MenuListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
if( event.getSource() == openMenuItem )
{
// change value of JTextArea from Panel.java
}
}
}
}
如何從MenuBar.class修改指令JTextArea(Panel.java)?
首先,由於以下行中的逗號,MenuBar的代碼片段無法編譯:
private JMenuItem openMenuItem,;
現在您有了一個類屬性指令,它是類Panel中的JTextArea對象。 這是私人的,所以只有班級小組才能到達,這很好。 如果要通過其他類獲取或設置該屬性的值,可以為其添加getter / setter。
在Panel中添加以下代碼:
public void setInstructions(JTextArea instructions) {
this.instructions = instructions;
}
public JTextArea getInstructions() {
return instructions;
}
setInstructions是您要查找的方法,您可以將指令TextArea設置為您傳遞的值作為參數。
請使用以下代碼修改MenuBar中的私有類,以顯示我的意思。
private class MenuListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
if( event.getSource() == openMenuItem )
{
Panel panel = new Panel(); //I don't know where you get your panel data from so I create a new one
panel.setInstructions(new JTextArea("I'm a text area and I have instructions")); //set the JTextArea value
System.out.println(panel.getInstructions().getText()); //test print to show how you can get the JTextArea text
}
}
}
我還添加了一個測試打印來驗證setter的工作原理。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.