Reputation: 1517
I'd like to create a simple GUI based 'Echo' application with the ability to scroll up and down through previous input. So far, everything is working except when I add the JTextPane to the JScrollPane, I lose the input and the scroll never appears.
Can someone point me in the right direction?
Here is the code I have so far:
import java.awt.*;
import javax.swing.*;
public class FileReaderGui {
private JFrame frame;
private JPanel inputPanel;
private JTextField userInput;
private JScrollPane scrollPane;
private JTextPane display;
JButton print;
public void show() {
frame = new JFrame();
frame.setSize(400, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buildInputPanel();
buildDisplayPanel();
frame.getContentPane().add(inputPanel, BorderLayout.SOUTH);
frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
frame.setVisible(true);
}
public void buildDisplayPanel() {
display = new JTextPane();
scrollPane = new JScrollPane(display);
}
public void buildInputPanel() {
inputPanel = new JPanel();
userInput = new JTextField();
userInput.setColumns(20);
inputPanel.add(userInput);
print = new JButton("Print");
print.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String current = display.getText();
String input = userInput.getText();
String newText = String.format("%s\n%s", current, input);
display.setText(newText);
}
});
inputPanel.add(print);
}
}
And, here is the caller:
public class FileReader {
public void go() {
FileReaderGui gui = new FileReaderGui();
gui.show();
}
public static void main(String[] args) {
new FileReader().go();
}
}
Upvotes: 0
Views: 840
Reputation: 1075
Just got a chance to test the code, my suggestion in the comments works for me.
Either way here are two options:
public void buildDisplayPanel() {
display = new JTextPane();
scrollPane = new JScrollPane();
scrollPane.getViewport().add(display);
}
or as I suggested above:
public void buildDisplayPanel() {
display = new JTextPane();
scrollPane = new JScrollPane(display);
}
They both seem to work for me in my tests locally.
As eluded to in the JavaDoc I linked in the comment above, the JScrollPane
displays the associated JViewport
, which can be retrieved and added to (first example) or created upon initialization (second example); you could also use the setViewport()
function described for JScrollPane
Upvotes: 1
Reputation: 324078
I'd say you should have scrollPane = new JScrollPane(display);
I also agree with the above.
Did you reorder your code to make sure you created the text pane before creating the scrollpane?
//scrollPane = new JScrollPane();
//display = new JTextPane();
//scrollPane.add(display);
display = new JTextPane();
scrollPane = new JScrollPane(display);
If that doesn't help then post your SSCCE
that includes you main() method to execute your code.
Upvotes: 1