tags:

views:

184

answers:

2

Hi,

I would like to add java's default questionIcon to a corner button in a Scrollpane, however the image doesn't fit correctly (since the button is very small). What should i do to make the icon fit correctly?

Here is the code, It works, so you can try it out and see for yourselfs the problem :)

import javax.swing.*;

public class CornerButton extends JFrame 
{
    public CornerButton()
    {

     JTextArea area = new JTextArea(20, 20);
     JScrollPane scroll = new JScrollPane(area);
     JButton btn = new JButton(UIManager.getIcon("OptionPane.questionIcon"));
     scroll.setCorner(ScrollPaneConstants.LOWER_RIGHT_CORNER, btn);
     this.add(scroll);
    }

    public static void main(String[] args) 
    {
     // TODO Auto-generated method stub
     CornerButton mainFrame = new CornerButton();

     mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     mainFrame.setVisible(true);
     mainFrame.setSize(200,200);
    }
}

NB. I posted the same question on Sun's forums but no one answered, hope I find some help from here :)

thanks in advance.

A: 

You could try increasing the width of the JScrollBars so that the button has more room to be displayed. For example:

scroll.getVerticalScrollBar().setPreferredSize(new Dimension(30, 30));
scroll.getHorizontalScrollBar().setPreferredSize(new Dimension(30, 30));
Herminator
OMG how couldn't I have thought about that... Thanks m8 your right it works like this.
Spi1988
+1  A: 

If you would prefer not to violate the look and feel, you might just resize the icon image and create a new icon like this:

import javax.swing.*;
import java.awt.*;

public class CornerButton extends JFrame
{
    public CornerButton()
    {
        JTextArea area = new JTextArea(20, 20);
        JScrollPane scroll = new JScrollPane(area);
        Icon icn = UIManager.getIcon("OptionPane.questionIcon");
        int neededWidth = scroll.getVerticalScrollBar().getPreferredSize().width;
        int neededHeight = scroll.getHorizontalScrollBar().getPreferredSize().height;
        Image img = ((ImageIcon) icn).getImage();
        ImageIcon icon = new ImageIcon(img.getScaledInstance(neededWidth, neededHeight, Image.SCALE_AREA_AVERAGING));
        JButton smallBtn = new JButton(icon);
        scroll.setCorner(ScrollPaneConstants.LOWER_RIGHT_CORNER, smallBtn);
        this.add(scroll);
    }

    public static void main(String[] args) 
    {
        CornerButton mainFrame = new CornerButton();

        mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        mainFrame.setVisible(true);
        mainFrame.setSize(200,200);
    }
}

It looks pretty good too.

clartaq