I’m new to Java, I would like to know how can I get my textarea from the main class??
This is my code:
public static void main(String[] args) {
UIManager.put("swing.boldMetal", Boolean.FALSE);
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI() {
frame = new JFrame("Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GuiManager animator = new GuiManager();
frame.add(animator, BorderLayout.CENTER);
// Display the window.
frame.pack();
frame.setSize(800, 500);
frame.setVisible(true);
}
and GuiManager:
public GuiManager() {
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
// .............
// Create Scrolling Text Area in Swing
JPanel panelLabel = new JPanel();
panelLabel.setLayout(new FlowLayout()); // No content pane for JPanel.
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout()); // No content pane for JPanel.
JLabel ta1Label = new JLabel("Label One", JLabel.LEFT);
ta1Label.setAlignmentX(Component.LEFT_ALIGNMENT);
JTextArea ta = new JTextArea("", 10, 30);
ta.setLineWrap(true);
JScrollPane sbrText = new JScrollPane(ta);
sbrText.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
JLabel ta2Label = new JLabel("Label2", JLabel.RIGHT);
ta2Label.setAlignmentX(Component.RIGHT_ALIGNMENT);
JTextArea ta2 = new JTextArea("", 10, 30);
ta2.setLineWrap(true);
JScrollPane sbrText2 = new JScrollPane(ta2);
sbrText2.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
panelLabel.add(ta1Label);
panelLabel.add(ta2Label);
panel.add(sbrText);
panel.add(sbrText2);
// Put everything together.
add(panelLabel);
add(panel);
setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
}
My goal is to redirect the output to these textarea, and for some output I need to redirect to the textarea on the left, but sometime I need to output on the textarea on the right. What would be the best solution to do that? Thank you.
Everything that you want to access seems to be in GuiManager. However, you put the declaration for it in a method. This means that it becomes a local variable. Once the method is finished with it’s code, the variable is gone and cannot be accessed any longer.
The fix? Just make it available to all the other classes.
Put that where you declared all your other variables for that class, and take out the one that was located in the ‘createAndShowGUI()’ method.