Is there a way I can replace a string with an image/sprite in JavaSwing? For example, for the string "r"
, I want to replace it with the image of the trainer from Pokemon Silver.
I'm doing this because the "r"
represents a roomba and the GUI will display a map of characters mapped by the roomba. I simply want to replace the "r"
with a sprite to make the GUI be more than just characters. Right now I am able to get the ImageIcon to display on the JTextPane, I just can't choose the location on there. If I'm able to choose the location on JTextPane and have it overlap where the "r"
is, as the "r"
remains stationary, that's also another solution.
Is this even possible or should I just live with the "r"
being the roomba instead of the image?
The following is the code right now. I'm using Intellij and it's UI designer. One of my partners is currently working on the code to get it to print out the grid, but we've decided that "r"
is going to be the roomba, so if I'm able to get the icon to replace the "r"
, I'm good to go.
public class ObstacleMap extends JFrame{
private JComboBox controllerselect;
private JPanel panel;
private JButton button;
private JLabel silvergif;
private JLabel battle;
private JTextPane textPane1;
int manual = 1;
public ObstacleMap() {
setTitle("Control Center");
setContentPane(panel);
pack();
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
textPane1.setVisible(false);
battle.setVisible(false);
textPane1.setEditable (false); //Make text area uneditable
//System.out.println now prints to GUI text area
PrintStream ps = new PrintStream(
new OutputStream() {
public void write(int c){
textPane1.setText(textPane1.getText() + (char) c);
}
}
);
System.setOut(ps);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
textPane1.setVisible(true);
silvergif.setVisible(false);
textPane1.insertIcon(new ImageIcon("src/trainer.gif"));
}
});
controllerselect.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (controllerselect.getSelectedItem() == "Autonomous"){
manual = 0;
}
else if (controllerselect.getSelectedItem() == "PS4 Controller"){
manual = 1;
}
}
});
}
public static void main(String[] args){
ObstacleMap o = new ObstacleMap();
}
}
Here is a screenshot of the GUI:
The icon should be placed in the bottom center area of the JTextPane
, not in the top left corner.