JLabel refresh icon with updated image - java

I'm trying to make an experiment in image manipulation.
Basically I have an image that is continously updated by a timer and i display that image in a JLabel.
My problem is that JLabel does'nt refresh the image.
Here is my timer code:
Timer timer = new Timer(200, new ActionListener() {
public void actionPerformed(ActionEvent e) {
count++;
System.out.println("timer");
System.out.println(filename);
ImageIcon icon = new ImageIcon(filename);
label = new JLabel();
label.setIcon(icon);
label.setText(""+count);
panel = new JPanel();
panel.add(label);
frame.getContentPane().removeAll();
frame.getContentPane().add(panel);
frame.repaint();
frame.validate();
try{
FileWriter fstream;
fstream = new FileWriter(filename,true);
BufferedWriter out = new BufferedWriter(fstream);
out.write("text to append");
out.close();
}catch (Exception ex){
System.err.println("Error: " + ex.getMessage());
}
}
});
Where filename is path to my image.
Image is displayed but JLabel never refresh my image.
I tested my code and is working if I swich between two different images...
EDIT:
I solved by duplicate every time last image created and renaming with a timestamp.

label = new JLabel();
label.setIcon(icon);
label.setText(""+count);
panel = new JPanel();
panel.add(label);
frame.getContentPane().removeAll();
frame.getContentPane().add(panel);
frame.repaint();
frame.validate();
Replace all that with something like:
label.setIcon(icon);
If the label is not visible at that point, declare it as a class attribute of the outer class or at the same level as the frame (which is obviously accessible in that snippet).

Related

How can I color this frame/border of my JTextArea?

I wanted to make a TextEditor and tried to change some colors. But I still have difficulties changing the color of the JFrame of the JTextArea (I mean this white border) and also don't know how I can make this text area so that it always changes the size to the selected JFrame size.
TextEditorPicture
TextEditorPicture2
public class TextEditor extends JFrame implements ActionListener {
JTextArea textArea;
JScrollPane scrollPane;
JLabel fontLabel;
JSpinner fontSizeSpinner;
JButton fontColorButton;
JComboBox fontBox;
JMenuBar menuBar;
JMenu fileMenu;
JMenuItem openItem;
JMenuItem saveItem;
JMenuItem exitItem;
TextEditor(){
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("TextEditor");
this.setSize(500,500);
this.setMinimumSize(new Dimension(500,0));
this.setMaximumSize(new Dimension(500, Integer.MAX_VALUE));
this.setVisible(true);
this.setLayout(new FlowLayout());
this.setLocationRelativeTo(null);
this.getContentPane().setBackground(Color.decode("#252025"));
//Text Area
textArea = new JTextArea();
textArea.setVisible(true);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
textArea.setFont(new Font("SF Mono Regular 11", Font.PLAIN,20));
textArea.setBackground(Color.decode("#252025"));
textArea.setForeground(Color.decode("#eaeaea"));
//Scroll Panel Sidebar
scrollPane = new JScrollPane(textArea);
scrollPane.setPreferredSize(new Dimension(500,500));
scrollPane.setMinimumSize(new Dimension(500,0));
scrollPane.setMaximumSize(new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE));
scrollPane.setVisible(true);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
//Font Text
fontLabel = new JLabel("Font: ");
fontLabel.setForeground(Color.decode("#eaeaea"));
//Font Size Spinner
fontSizeSpinner = new JSpinner();
fontSizeSpinner.setPreferredSize(new Dimension(50,25));
fontSizeSpinner.setValue(20);
fontSizeSpinner.getEditor().getComponent(0).setBackground(Color.decode("#252025"));
fontSizeSpinner.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
textArea.setFont(new Font("SF Mono Regular 11",Font.PLAIN,(int) fontSizeSpinner.getValue()));
textArea.setSelectedTextColor(Color.white);
}
});
fontColorButton = new JButton("Color");
fontColorButton.setBackground(Color.decode("#252025"));
fontColorButton.setOpaque(true);
fontColorButton.setBorderPainted(false);
fontColorButton.addActionListener(this);
fontColorButton.setForeground(Color.decode("#eaeaea"));
String[] fonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
//Font Change Box
fontBox = new JComboBox(fonts);
fontBox.addActionListener(this);
fontBox.setBackground(Color.decode("#252025"));
fontBox.setForeground(Color.green);
fontBox.setOpaque(true);
fontBox.setEditable(true);
fontBox.getEditor().getEditorComponent().setBackground(Color.decode("#252025"));
((JTextField) fontBox.getEditor().getEditorComponent()).setBackground(Color.decode("#252025"));
fontBox.setSelectedItem("SF Mono Regular 11");
//Menubar
menuBar = new JMenuBar();
fileMenu = new JMenu("File");
openItem = new JMenuItem("Open");
saveItem = new JMenuItem("Save");
exitItem = new JMenuItem("Exit");
openItem.addActionListener(this);
saveItem.addActionListener(this);
exitItem.addActionListener(this);
fileMenu.add(openItem);
fileMenu.add(saveItem);
fileMenu.add(exitItem);
menuBar.add(fileMenu);
this.setJMenuBar(menuBar);
this.add(fontLabel);
this.add(fontSizeSpinner);
this.add(fontColorButton);
this.add(fontBox);
this.add(scrollPane);
this.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource() == fontColorButton) {
JColorChooser colorChooser = new JColorChooser();
Color color = colorChooser.showDialog(null, "Color", Color.white);
}
if(e.getSource()==fontBox) {
textArea.setFont(new Font((String)fontBox.getSelectedItem(),Font.PLAIN,textArea.getFont().getSize()));
}
//Open
if(e.getSource()==openItem) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File("."));
FileNameExtensionFilter filter = new FileNameExtensionFilter("Text Files", "txt");
fileChooser.setFileFilter(filter);
int response = fileChooser.showOpenDialog(null);
if(response==JFileChooser.APPROVE_OPTION) {
File file = new File(fileChooser.getSelectedFile().getAbsolutePath());
Scanner fileIn = null;
try {
fileIn = new Scanner(file);
if(file.isFile()) {
while(fileIn.hasNextLine()) {
String line = fileIn.nextLine()+"\n";
textArea.append(line);
}
}
} catch (FileNotFoundException e1){
e1.printStackTrace();
} finally {
fileIn.close();
}
}
}
//Save
if(e.getSource()==saveItem) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File("."));
int response = fileChooser.showSaveDialog(null);
if(response==JFileChooser.APPROVE_OPTION) {
File file;
PrintWriter fileOut = null;
file = new File(fileChooser.getSelectedFile().getAbsolutePath());
try {
fileOut = new PrintWriter(file);
fileOut.println(textArea.getText());
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally {
fileOut.close();
}
}
}
//Exit
if(e.getSource()==exitItem) {
System.exit(0);
}
}
}
You need to use multiple layouts. FlowLayout alone is not sufficient.
The center component of a BorderLayout will always stretch to fill the container’s space.
Remember that you can put panels inside panels. Put your font and color labels/fields in a JPanel that uses a FlowLayout, then put that JPanel in the NORTH area of a JPanel that uses a BorderLayout. Your JScrollPane belongs in the center of that same BorderLayout.
Remove all calls to setPreferredSize, setMinimumSize, and setMaximumSize. They are intefering with a layout manager’s ability to properly arrange things. All components have a useful preferred size when they are created.
To set the size of your JScrollPane, use the setRows and setColumns methods of JTextArea. The JScrollPane parent will consult its Scrollable view (that is, the JTextArea) to determine its preferred size.

Why isn't the JPanel showing the ImageIcon?

I have a GridBagConstraints gbcImage and a JLabel that is initialized like this:
gbcImage.gridx = 1; // column 0
gbcImage.gridy = 2; // row 2
gbcImage.ipady = 100;
gbcImage.ipadx = 100;
JLabel label = new JLabel("", null, JLabel.CENTER);
label.setOpaque(true);
label.setBackground(Color.WHITE);
panel.add(label, gbcImage);
Where panel is added to a JFrame.
So I implemented a MouseListener to the label:
public void mouseClicked(MouseEvent e) {
JFileChooser jfc = new JFileChooser();
int iRet = jfc.showOpenDialog(panel);
if (iRet == jfc.APPROVE_OPTION)
{
File file = jfc.getSelectedFile();
try
{
BufferedImage bi = ImageIO.read(file);
image = new ImageIcon(bi);
JLabel label = new JLabel("", image, JLabel.CENTER);
panel.add(label, gbcImage);
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
}
But it didn't work. The image doesn't show in the panel at runtime.
What am I missing?
There is no need to create a new JLabel. The problem is you added a new label to the panel but its default size is (0, 0) because you didn't reavalidate() and repaint() the panel.
There is no need to create a new label.
Instead you keep a reference to the original label (like you do for the panel) and then you just replace the icon:
image = new ImageIcon(bi);
label.setIcon( image );

How do you display an image on a panel in Java? [Beginner]

I need to put a menu in a game, so I've created a frame called menuFrame and a panel called menuPanel. I've been able to get a button and a label with text to appear on this panel, but I can't get an image to display.
Here is the bulk of my code:
try {
JPanel menuPanel = new JPanel();
BufferedImage img = ImageIO.read(this.getClass().getResource("background2.png"));
JLabel menuLabel = new JLabel(new ImageIcon(img));
menuLabel.setSize(800, 540);
menuLabel.setLocation(0, 0);
menuLabel.setVisible(true);
menuPanel.add(menuLabel);
this.add(menuPanel);
menuPanel.grabFocus();
menuPanel.requestFocusInWindow();
} catch (IOException e) {
e.printStackTrace();
}
I've been messing with it for a very long time, and the image simply wont appear. I've tried using just ImageIcon and no BufferedImage and that didn't work. I put the image in the same package as the class.
You could do something like this:
ImageIcon imgIcon = new ImageIcon("background2.png");
JLabel menuLabel = new JLabel();
label.setBounds(0, 0, x, y);
label.setIcon(imgIcon);
try {
JPanel menuPanel = new JPanel();
BufferedImage img = ImageIO.read(this.getClass().getResource("background2.png"));
JLabel menuLabel = new JLabel(new ImageIcon(img));
menuLabel.setSize(800, 540);
menuLabel.setLocation(0, 0);
menuLabel.setVisible(true);
menuPanel.add(menuLabel);
this.add(menuPanel); //This might not work, try the name of the JFrame instance
menuPanel.grabFocus();
menuPanel.requestFocusInWindow();
this.revalidate() //Use the name of the JFrame if this is not a JFrame or if this.add(menuPanel); doesnt work
} catch (IOException e) {
e.printStackTrace();
}

Having trouble adding JScrollBar/JScrollPane to this JTextPane

Ok, so here's a snippet of my code containing the problem:
private JTextField userText;
private ObjectOutputStream output;
private ObjectInputStream input;
private ServerSocket server;
private Socket connection;
private JTextPane images;
private JScrollPane jsp = new JScrollPane(images);
public Server(){
super(name+" - IM Server");
images = new JTextPane();
images.setContentType( "text/html" );
HTMLDocument doc = (HTMLDocument)images.getDocument();
userText = new JTextField();
userText.setEditable(false);
userText.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
sendMessage(event.getActionCommand());
userText.setText("");
}
}
);
add(userText, BorderLayout.NORTH);
add(jsp);
add(images, BorderLayout.CENTER);
images.setEditable(false);
try {
doc.insertString(0, "This is where images and text will show up.\nTo send an image, do\n*image*LOCATION OF IMAGE\n with NO SPACES or EXTRA TEXT.", null );
} catch (BadLocationException e) {
e.printStackTrace();
}
setSize(700,400);
setVisible(true);
ImageIcon logo = new javax.swing.ImageIcon(getClass().getResource("CHAT.png"));
setIconImage(logo.getImage());
}
and when I use it, there's no scrollbar on my JTextPane?! I have tried moving add(jsp); above and below where it is, and moving it below add(images, BorderLayout.NORTH); greys it out?! So what I want to know is how to add this JScrollPane to my JTextPane to give it a scrollbar. Thanks in advance!
Bascially, you actually never add a valid component to the JScrollPane...
private JTextPane images;
private JScrollPane jsp = new JScrollPane(images);
When this executes, images is null, so basically, you are calling new JScrollPane(null);
Then, you basically add images over the top of (replacing) jsp on the frame...
add(jsp);
add(images, BorderLayout.CENTER);
The default position is BorderLayout.CENTER and border layout can only support a single component in any of it's 5 available positions...
Instead, try something like...
public Server(){
super(name+" - IM Server");
images = new JTextPane();
images.setContentType( "text/html" );
HTMLDocument doc = (HTMLDocument)images.getDocument();
userText = new JTextField();
userText.setEditable(false);
userText.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
sendMessage(event.getActionCommand());
userText.setText("");
}
}
);
add(userText, BorderLayout.NORTH);
jsp.setViewportView(images);
add(jsp);
//add(images, BorderLayout.CENTER);
images.setEditable(false);
try {
doc.insertString(0, "This is where images and text will show up.\nTo send an image, do\n*image*LOCATION OF IMAGE\n with NO SPACES or EXTRA TEXT.", null );
} catch (BadLocationException e) {
e.printStackTrace();
}
setSize(700,400);
setVisible(true);
ImageIcon logo = new javax.swing.ImageIcon(getClass().getResource("CHAT.png"));
setIconImage(logo.getImage());
}

Why don't I see the image or the button?

I am trying to add a button over the image. But neither see the button nor the image. Why is that ? I am calling this method from the constructor just after the initComponents method is called by the IDE.
public void initD() {
try {
BufferedImage myPicture = ImageIO.read(new File("C:\\Users\\user\\Documents\\NetBeansProjects\\JavaApplication1\\src\\javaapplication1\\meaning.JPG"));
JLabel picLabel = new JLabel(new ImageIcon(myPicture));
JButton b = new JButton("Press me");
jPanel1.add(picLabel);
jPanel1.add(b);
System.out.println("last statement");
}catch(Exception exc) {
exc.printStackTrace();
}
}
I only see the frame as an output.
I dont know which layout you are using, however you should implement button.setIcon(); like this;
public void initD() {
JButton button = new JButton("Press me");
try {
BufferedImage myPicture = ImageIO.read(new File("C:\\Users\\user\\Documents\\NetBeansProjects\\JavaApplication1\\src\\javaapplication1\\meaning.JPG"));
JLabel picLabel = new JLabel(new ImageIcon(myPicture));
button.setIcon(new ImageIcon(myPicture));
System.out.println("last statement");
}catch(Exception exc) {
exc.printStackTrace();
}
}
In addition you may need to consider resource of your image maybe this implemantation can be helpfull ;
ImageIO.read(getClass().getResource("resources/meaning.JPG")));

Categories

Resources