ImageIcon Border
Hi all,
I'm looking to create a white rectangular border around my ImageIcon on a JLabel, not around the Jlabel. Any suggestions would be appreciated. Thanks.
-roger
Here's something to get you started:
ImageIcon imageIcon = new ImageIcon(getClass().getResource("myIcon.gif"));
int borderWidth = 1;
int spaceAroundIcon = 2;
Color borderColor = Color.WHITE;
BufferedImage bi = new BufferedImage(imageIcon.getIconWidth() + (2 * borderWidth + 2 * spaceAroundIcon),
imageIcon.getIconHeight() + (2 * borderWidth + 2 * spaceAroundIcon), BufferedImage.TYPE_INT_ARGB);
Graphics2D g = bi.createGraphics();
g.setColor(borderColor);
g.drawImage(imageIcon.getImage(), borderWidth + spaceAroundIcon, borderWidth + spaceAroundIcon, null);
g.drawRect(0, 0, bi.getWidth() - 1, bi.getHeight() - 1);
g.dispose();
JLabel label = new JLabel("MyText", new ImageIcon(bi), JLabel.LEFT);
Similar Messages
-
How can I remove the gradient background & border from an ImageIcon?
Problem1: Hey, I have a program that randomly displays a stop sign that I'm supposed to click on as fast as I can. And I created a gif with the stop sign, with it's background transparent. But when I added it to my application using an ImageIcon, whatever's supposed to be transparent in the gif is shown up as a gradient. There's also a border around the ImageIcon. Is there any way to get rid of these? Thanks
Problem 2: I also have a background for my entire application, but it stays the same size no matter if I maximize the application or run it on a different screen size. Is there any way to scale a background (it's animated), to the full screen?
Thanks again! It's for a project due tomorrow. I'm doing final touches.
Here's some of my code. It's really long, so I took out what I think is related. JButton stopSign1 = new JButton();
this.getContentPane().add(stopSign1,null);
ImageIcon stopSign = new ImageIcon("Dead_End.gif");
stopSign1.setBounds(new Rectangle(randomX, randomY, 150, 150));
stopSign1.setIcon(stopSign);
stopSign1.setVisible(false);Try stopSign1.setBorder(null);
stopSign1.setOpaque(false);Also, in future, post Swing questions in the Swing forum. -
hi, i do a program to create "business case table", but i've a problem in the 2nd part of the table, because in my 2nd table i have a JComboBox with image, when i click the combobox the images are show, but when select some figure the cell don�t keep the image, only keep the text.
Anyone can help me???
Here is my principal class that create the principal screen and tables:
/* Poseidon */
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;
import javax.swing.table.*;
* Summary description for Poseidon
*2052102
public class Poseidon extends JFrame
// Variables declaration
private JTabbedPane jTabbedPane1;
private JPanel contentPane, paineltabela, painelgrafo, painelvariavel, paineltarefa;
private JTable tabelavariavel,tabelatarefa, tabelateste;
private JScrollPane scrollvariavel, scrolltarefa;
private int totallinhas, alt, al, linhastarefa,cont, linhas, tamanholinhas,
controlalinhas, index, contastring;
private String variavel;
private JComboBox combobox;
JMenuItem sair, abrir, guardar, miadtarefa, miadvariavel;
JTable [] tabelasvar = new JTable[30];
JFrame w;
// End of variables declaration
public Poseidon()
super("Poseidon");
initializeComponent();
this.setVisible(true);
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always regenerated
* by the Windows Form Designer. Otherwise, retrieving design might not work properly.
* Tip: If you must revise this method, please backup this GUI file for JFrameBuilder
* to retrieve your design properly in future, before revising this method.
private void initializeComponent()
JMenuBar barra = new JMenuBar();
setJMenuBar(barra);
TratBarra trat = new TratBarra();
tabelavariavel = new JTable();
tabelatarefa = new JTable();
tabelavariavel.getTableHeader().setReorderingAllowed(false);
tabelavariavel.setModel(new DefaultTableModel());
tabelavariavel.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
tabelavariavel.setBackground(Color.cyan);
tabelatarefa.getTableHeader().setReorderingAllowed(false);
tabelatarefa.setModel(new DefaultTableModel());
tabelatarefa.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
tabelatarefa.setBackground(Color.white);
CaixaCombinacao combobox = new CaixaCombinacao();
DefaultCellEditor editor = new DefaultCellEditor(combobox);
tabelatarefa.setDefaultEditor(Object.class, editor);
painelvariavel = new JPanel();
painelvariavel.setLayout(new GridLayout(1, 0));
painelvariavel.setBorder(new TitledBorder("Variaveis"));
painelvariavel.setBounds(15, 35, 490, 650);
painelvariavel.setVisible(false);
this.add(painelvariavel);
scrollvariavel = new JScrollPane();
scrollvariavel.setViewportView(tabelavariavel);
painelvariavel.add(scrollvariavel);
paineltarefa = new JPanel();
paineltarefa.setLayout(new GridLayout(1,0));
paineltarefa.setBorder(new TitledBorder("Tarefas"));
paineltarefa.setBounds(506, 35, 490,650);
paineltarefa.setVisible(false);
this.add(paineltarefa);
scrolltarefa = new JScrollPane();
scrolltarefa.setViewportView(tabelatarefa);
paineltarefa.add(scrolltarefa);
tamanholinhas = 1;
linhas=1;
cont=0;
JMenu arquivo = new JMenu("Arquivo");
JMenu mtabela = new JMenu("Tabela");
arquivo.setMnemonic(KeyEvent.VK_A);
mtabela.setMnemonic(KeyEvent.VK_T);
miadvariavel = new JMenuItem("Adicionar Variavel");
miadtarefa = new JMenuItem("Adicionar Tarefa");
abrir = new JMenuItem("Abrir");
guardar = new JMenuItem("Guardar");
sair = new JMenuItem("Sair");
sair.addActionListener(trat);
miadvariavel.addActionListener(trat);
miadtarefa.addActionListener(trat);
mtabela.add(miadvariavel);
miadvariavel.setMnemonic(KeyEvent.VK_V);
mtabela.add(miadtarefa);
miadtarefa.setMnemonic(KeyEvent.VK_F);
arquivo.add(abrir);
abrir.setMnemonic(KeyEvent.VK_B);
arquivo.add(guardar);
guardar.setMnemonic(KeyEvent.VK_G);
arquivo.addSeparator();
arquivo.add(sair);
sair.setMnemonic(KeyEvent.VK_S);
barra.add(arquivo);
barra.add(mtabela);
jTabbedPane1 = new JTabbedPane();
contentPane = (JPanel)this.getContentPane();
paineltabela = new JPanel();
painelgrafo = new JPanel();
// jTabbedPane1
jTabbedPane1.addTab("Tabela", paineltabela);
jTabbedPane1.addTab("Grafo", painelgrafo);
jTabbedPane1.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e)
painelvariavel.setVisible(false);
// contentPane
contentPane.setLayout(null);
addComponent(contentPane, jTabbedPane1, 11,10,990,690);
// paineltabela
paineltabela.setLayout(null);
// painelgrafo
painelgrafo.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
// Poseidon
this.setTitle("UMa Poseidon");
this.setLocation(new Point(2, 1));
this.setSize(new Dimension(558, 441));
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.setExtendedState(MAXIMIZED_BOTH);
/** Add Component Without a Layout Manager (Absolute Positioning) */
private void addComponent(Container container,Component c,int x,int y,int width,int height)
c.setBounds(x,y,width,height);
container.add(c);
// TODO: Add any appropriate code in the following Event Handling Methods
private void jTabbedPane1_stateChanged(ChangeEvent e)
System.out.println("\njTabbedPane1_stateChanged(ChangeEvent e) called.");
// TODO: Add any handling code here
// TODO: Add any method code to meet your needs in the following area
private class TratBarra implements ActionListener{
public void actionPerformed(ActionEvent e){
if(e.getSource() == sair){
int op = JOptionPane.showConfirmDialog(null, "Deseja mesmo fechar o aplicativo?","Sair", JOptionPane.YES_NO_OPTION);
if(op == JOptionPane.YES_OPTION){
System.exit(0);
if(e.getSource() == miadvariavel){
final JFrame w = new JFrame();
new AdVariavel(w);
if(e.getSource() == miadtarefa){
final JFrame w = new JFrame();
new AdTarefa(w);
//============================= Testing ================================//
//= =//
//= The following main method is just for testing this class you built.=//
//= After testing,you may simply delete it. =//
//======================================================================//
public static void main(String[] args)
Spash sp = new Spash(3000);
sp.mostraTela();
JFrame.setDefaultLookAndFeelDecorated(true);
JDialog.setDefaultLookAndFeelDecorated(true);
try
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
catch (Exception ex)
System.out.println("Failed loading L&F: ");
System.out.println(ex);
new Poseidon();
//= End of Testing =
private class AdVariavel extends JDialog
// Variables declaration
private JLabel jLabel1;
private JTextField jTextField1;
private JButton varOK;
private JButton varCancel;
private JPanel contentPane;
private JTextField jTextField2;
private JList listadominio;
private JScrollPane jScrollPane1;
private JButton varAdiciona;
private JButton varRemove;
private JPanel jPanel1;
private DefaultListModel modelo1;
// End of variables declaration
public AdVariavel(Frame w)
super(w);
initializeComponent();
// TODO: Add any constructor code after initializeComponent call
this.setVisible(true);
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always regenerated
* by the Windows Form Designer. Otherwise, retrieving design might not work properly.
* Tip: If you must revise this method, please backup this GUI file for JFrameBuilder
* to retrieve your design properly in future, before revising this method.
private void initializeComponent()
modelo1 = new DefaultListModel();
jLabel1 = new JLabel();
jTextField1 = new JTextField();
varOK = new JButton();
varCancel = new JButton();
contentPane = (JPanel)this.getContentPane();
jTextField2 = new JTextField();
listadominio = new JList(modelo1);
jScrollPane1 = new JScrollPane();
varAdiciona = new JButton();
varRemove = new JButton();
jPanel1 = new JPanel();
// jLabel1
jLabel1.setText("Nome da vari�vel:");
// jTextField1
jTextField1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
jTextField1_actionPerformed(e);
// varOK
varOK.setText("OK");
varOK.setMnemonic(KeyEvent.VK_O);
varOK.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
varOK_actionPerformed(e);
// varCancel
varCancel.setText("Cancelar");
varCancel.setMnemonic(KeyEvent.VK_C);
varCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
varCancel_actionPerformed(e);
// contentPane
contentPane.setLayout(null);
addComponent(contentPane, jLabel1, 12,12,105,18);
addComponent(contentPane, jTextField1, 118,10,137,22);
addComponent(contentPane, varOK, 170,227,83,28);
addComponent(contentPane, varCancel, 257,227,85,28);
addComponent(contentPane, jPanel1, 12,42,332,180);
// jTextField2
jTextField2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
jTextField2_actionPerformed(e);
// listadominio
listadominio.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e)
listadominio_valueChanged(e);
// jScrollPane1
jScrollPane1.setViewportView(listadominio);
// varAdiciona
varAdiciona.setText("Adicionar");
varAdiciona.setMnemonic(KeyEvent.VK_A);
varAdiciona.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
varAdiciona_actionPerformed(e);
// varRemove
varRemove.setText("Remover");
varRemove.setMnemonic(KeyEvent.VK_R);
varRemove.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
varRemove_actionPerformed(e);
// jPanel1
jPanel1.setLayout(null);
jPanel1.setBorder(new TitledBorder("Dominio:"));
addComponent(jPanel1, jTextField2, 17,22,130,22);
addComponent(jPanel1, jScrollPane1, 165,21,154,144);
addComponent(jPanel1, varAdiciona, 56,50,89,28);
addComponent(jPanel1, varRemove, 57,84,88,28);
// AdTarefas
this.setTitle("Adicionar Variavel");
this.setLocation(new Point(1, 0));
this.setSize(new Dimension(367, 296));
this.setLocationRelativeTo(null);
this.setResizable(false);
/** Add Component Without a Layout Manager (Absolute Positioning) */
private void addComponent(Container container,Component c,int x,int y,int width,int height)
c.setBounds(x,y,width,height);
container.add(c);
// TODO: Add any appropriate code in the following Event Handling Methods
private void jTextField1_actionPerformed(ActionEvent e)
System.out.println("\njTextField1_actionPerformed(ActionEvent e) called.");
// TODO: Add any handling code here
private void varOK_actionPerformed(ActionEvent e)
System.out.println("\nvarOK_actionPerformed(ActionEvent e) called.");
if (jTextField1 == null){
return;
if (jTextField1.getText().length()<1){
JOptionPane.showMessageDialog(null,"N�o introduziu nenhuma variavel","AVISO", 1 );
jTextField1.requestFocus();
return;
else {
if (modelo1.getSize() == 0){
JOptionPane.showMessageDialog(null,"N�o introduziu nenhum dominio","AVISO", 1 );
return;
else{
painelvariavel.add(scrollvariavel);
index = 0;
variavel = jTextField1.getText();
contastring = variavel.length();
System.out.println(contastring);
DefaultTableModel dtm = (DefaultTableModel)tabelavariavel.getModel();
tabelavariavel.getTableHeader().setBackground(Color.yellow);
dtm.addColumn(variavel, new Object[]{});
al = modelo1.getSize();
totallinhas = al;
for(int i = 0;i < modelo1.getSize();i++){
listadominio.setSelectedIndex(index) ;
Object dominio = listadominio.getSelectedValue();
dtm.addRow(new Object[]{dominio});
index ++;
tabelasvar[cont] = tabelavariavel;
cont++;
System.out.println(cont);
for(int i=0;i<cont;i++){
tabelateste = tabelasvar;
linhas = tabelateste.getRowCount();
if (linhas >= tamanholinhas){
tamanholinhas = linhas;
for (int i=0;i<cont;i++){
tabelateste = tabelasvar[i];
System.out.println(linhas);
linhas = tabelateste.getRowCount();
tabelateste.setRowHeight((tamanholinhas/linhas)*20);
tabelasvar[i] = tabelateste;
System.out.println(tabelateste);
tabelavariavel = new JTable();
scrollvariavel = new JScrollPane();
painelvariavel.add(tabelavariavel);
tabelavariavel.setBackground(Color.cyan);
tabelavariavel.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
scrollvariavel.setViewportView(tabelavariavel);
painelvariavel.setVisible(true);
tabelavariavel.getTableHeader().setReorderingAllowed(false);
this.setVisible(false);
miadtarefa.setEnabled(true);
miadvariavel.setEnabled(true);
DefaultTableModel dtm = (DefaultTableModel)tabelatarefa.getModel();
tabelatarefa.getTableHeader().setBackground(Color.yellow);
controlalinhas = tamanholinhas - linhastarefa;
for(int i = 0;i < controlalinhas;i++){
dtm.addRow(new Object[]{});
linhastarefa++;
tabelatarefa.setRowHeight((tamanholinhas/linhas)*20);
// TODO: Add any handling code here
private void varCancel_actionPerformed(ActionEvent e)
System.out.println("\nvarCancel_actionPerformed(ActionEvent e) called.");
this.setVisible(false);
private void jTextField2_actionPerformed(ActionEvent e)
System.out.println("\njTextField2_actionPerformed(ActionEvent e) called.");
// TODO: Add any handling code here
private void listadominio_valueChanged(ListSelectionEvent e)
System.out.println("\nlistadominio_valueChanged(ListSelectionEvent e) called.");
if(!e.getValueIsAdjusting())
Object o = listadominio.getSelectedValue();
System.out.println(">>" + ((o==null)? "null" : o.toString()) + " is selected.");
// TODO: Add any handling code here for the particular object being selected
private void varAdiciona_actionPerformed(ActionEvent e)
System.out.println("\nvarAdiciona_actionPerformed(ActionEvent e) called.");
if(jTextField2.getText().length()>=1){
modelo1.addElement(jTextField2.getText());
jTextField2.setText("");
jTextField2.requestFocus();
private void varRemove_actionPerformed(ActionEvent e)
System.out.println("\nvarRemove_actionPerformed(ActionEvent e) called.");
int index = listadominio.getSelectedIndex();
modelo1.remove(index);
// TODO: Add any method code to meet your needs in the following area
private class AdTarefa extends JDialog
// Variables declaration
private JLabel jLabel1;
private JTextField jTextField1;
private JButton tarOK;
private JButton tarCancel;
private JPanel contentPane;
private JPanel jPanel1;
// End of variables declaration
public AdTarefa(Frame w)
super(w);
initializeComponent();
// TODO: Add any constructor code after initializeComponent call
this.setVisible(true);
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always regenerated
* by the Windows Form Designer. Otherwise, retrieving design might not work properly.
* Tip: If you must revise this method, please backup this GUI file for JFrameBuilder
* to retrieve your design properly in future, before revising this method.
private void initializeComponent()
jLabel1 = new JLabel();
jTextField1 = new JTextField();
tarOK = new JButton();
tarCancel = new JButton();
contentPane = (JPanel)this.getContentPane();
// jLabel1
jLabel1.setText("Nome da tarefa:");
// jTextField1
jTextField1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
jTextField1_actionPerformed(e);
// tarOK
tarOK.setText("OK");
tarOK.setMnemonic(KeyEvent.VK_O);
tarOK.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
tarOK_actionPerformed(e);
// tarCancel
tarCancel.setText("Cancelar");
tarCancel.setMnemonic(KeyEvent.VK_C);
tarCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
tarCancel_actionPerformed(e);
// contentPane
contentPane.setLayout(null);
addComponent(contentPane, jLabel1, 12,12,105,18);
addComponent(contentPane, jTextField1, 118,10,120,22);
addComponent(contentPane, tarOK, 10,50,83,28);
addComponent(contentPane, tarCancel, 153,50,85,28);
// AdTarefas
this.setTitle("Adicionar Tarefa");
this.setLocation(new Point(1, 0));
this.setSize(new Dimension(250, 120));
this.setLocationRelativeTo(null);
this.setResizable(false);
/** Add Component Without a Layout Manager (Absolute Positioning) */
private void addComponent(Container container,Component c,int x,int y,int width,int height)
c.setBounds(x,y,width,height);
container.add(c);
// TODO: Add any appropriate code in the following Event Handling Methods
private void jTextField1_actionPerformed(ActionEvent e)
System.out.println("\njTextField1_actionPerformed(ActionEvent e) called.");
// TODO: Add any handling code here
private void tarOK_actionPerformed(ActionEvent e)
System.out.println("\ntarOK_actionPerformed(ActionEvent e) called.");
if (jTextField1 == null){
return;
if (jTextField1.getText().length()<1){
JOptionPane.showMessageDialog(null,"N�o introduziu nenhuma tarefa","AVISO", 1 );
jTextField1.requestFocus();
return;
else{
String variavel = jTextField1.getText();
DefaultTableModel dtm = (DefaultTableModel)tabelatarefa.getModel();
dtm.addColumn(variavel,new Object[]{});
controlalinhas = tamanholinhas - linhastarefa;
for(int i = 0;i < controlalinhas;i++){
dtm.addRow(new Object[]{});
linhastarefa++;
for(int i=0; i < tabelatarefa.getColumnCount(); i++){
tabelatarefa.getColumnModel().getColumn(i).setPreferredWidth(100);
tabelatarefa.getColumnModel().getColumn(i).setResizable(false);
tabelatarefa.getTableHeader().setBackground(Color.yellow);
tabelatarefa.setRowHeight((tamanholinhas/linhas)*20);
paineltarefa.setVisible(true);
tabelatarefa.getTableHeader().setReorderingAllowed(true);
this.setVisible(false);
miadtarefa.setEnabled(true);
miadvariavel.setEnabled(true);
// TODO: Add any handling code here
private void tarCancel_actionPerformed(ActionEvent e)
System.out.println("\ntarCancel_actionPerformed(ActionEvent e) called.");
this.setVisible(false);
now the code to create the JComboBox is here:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class CaixaCombinacao extends JComboBox{
ImageIcon[] imagens;
String[] op = {"x", "check"};
public CaixaCombinacao(){
imagens = new ImageIcon[op.length];
Integer[] intArray = new Integer[op.length];
for (int i = 0; i < op.length; i++) {
intArray[i] = new Integer(i);
imagens[i] = createImageIcon("imagens/" + op[i] + ".gif");
this.addItem(imagens);
if (imagens[i] != null) {
imagens[i].setDescription(op[i]);
JComboBox lista = new JComboBox(intArray);
ComboBoxRenderer renderer= new ComboBoxRenderer();
lista.setRenderer(renderer);
protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = CaixaCombinacao.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
return null;
class ComboBoxRenderer extends JLabel
implements ListCellRenderer {
public ComboBoxRenderer() {
setOpaque(true);
setHorizontalAlignment(CENTER);
setVerticalAlignment(CENTER);
public Component getListCellRendererComponent(
JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
int selectedIndex = ((Integer)value).intValue();
if (isSelected) {
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
} else {
setBackground(list.getBackground());
setForeground(list.getForeground());
ImageIcon icon = imagens[selectedIndex];
String opc = op[selectedIndex];
setIcon(icon);
return this;I'm sure 90% of the code posted here has nothing to do with displaying images in a JTable.
Here is an example that shows how to display an icon in a table:
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
public class TableIcon extends JFrame
public TableIcon()
String[] columnNames = {"Picture", "Description"};
Object[][] data =
{new ImageIcon("copy16.gif"), "Copy"},
{new ImageIcon("add16.gif"), "Add"},
DefaultTableModel model = new DefaultTableModel(data, columnNames);
JTable table = new JTable( model )
// Returning the Class of each column will allow different
// renderers to be used based on Class
public Class getColumnClass(int column)
return getValueAt(0, column).getClass();
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane( table );
getContentPane().add( scrollPane );
public static void main(String[] args)
TableIcon frame = new TableIcon();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setVisible(true);
}If this doesn't help then post a similiar demo program that shows the problems you are having, not your entire application. -
JLabel ImageIcon not opaque.
Hi I am having a little problem with my program that I am trying to develop.
I have created a JFrame and instead of having the background the usual grey I have used an image.
I then wanted to create some nice big buttons with nice smooth curved edges but was having trouble using the JButton so decicded to use a JLabel and attach a MouseListener to it. This seems to be working fine at the mo.
The only problem is that instead of my nice gradient filled background being displayed I get a big white border around the JLabel. The rest of the background is perfectly displayed having only a problem around the JLabel. I have tried not using a background image and it shows the JLabel correctly and the button looks nice and smooth.
I think it might be something to do with the rendering sequence maybe but I am at a loss. If any one has any ideas on how to fix it or a better way of doing it I would be most grateful.
Many thanks for your help in advance.
Matt
PS now heres my code:
public class GUI extends JFrame implements MouseListener {
ImageIcon icon;
JPanel buttonPanel = new JPanel();
public GUI(){
super("Property Works - Estate Agent Management System");
icon = new ImageIcon("images/bg.jpg");
JPanel panel = new JPanel(){
protected void paintComponent(Graphics g){
//g.drawImage(icon.getImage(), 0, 0, null);
Dimension d = getSize();
//g.drawImage(icon.getImage(), 0, 0, d.width, d.height, null);
super.paintComponent(g);
panel.setOpaque(false);
addButton();
panel.add(buttonPanel);
getContentPane().add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setExtendedState(JFrame.MAXIMIZED_BOTH);
setVisible(true);
public void addButton(){
ImageIcon icon1 = new ImageIcon("images/buttons/addProperty.gif");
JLabel addProperty = new JLabel(icon1);
addProperty.setOpaque(false);
addProperty.setToolTipText("Add a new property");
addProperty.addMouseListener(this);
JLabel tester = new JLabel("Tester");
tester.setOpaque(false);
buttonPanel.add(addProperty);
buttonPanel.add(tester);
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
System.out.println("Button Clicked");
}Swing related questions should be posted in the Swing forum.
Use the "code" tags when you post code so the formatting is retained.
The code you posted doesn't compile so we can't see the incorrect behaviour.
Using code I already have I do not see any white border around the image. I tested using a "Duke" image which is found in many of the Swing tutorial examples. Maybe your image is the problem. -
Xp: bug: jbutton: transparent + no border
hi,
we have tested our swing-application under win-xp and must see that the jbuttons doesn't be shown correctly. this problem does exist only under win-xp. in win9x, winnt, win2k it works perfectly.
we use own designed buttons with transparent gif's and no borders. here is an example:
(look+feel = system)
ivjButNext = new javax.swing.JButton();
ivjButNext.setName("ButNext");
ivjButNext.setBounds(350, 5, 103, 42);
ivjButNext.setOpaque(false);
ivjButNext.setBackground(new java.awt.Color(0,100,255));
ivjButNext.setForeground(java.awt.Color.black);
ivjButNext.setIcon(new javax.swing.ImageIcon(getClass().getResource("but_1.gif")));
ivjButNext.setPressedIcon(new javax.swing.ImageIcon(getClass().getResource("but_2.gif")));
ivjButNext.setDisabledIcon(new javax.swing.ImageIcon(getClass().getResource("but_3.gif")));
ivjButNext.setFocusPainted(false);
ivjButNext.setBorderPainted(false);
ivjButNext.setFont(new java.awt.Font("Arial", 1, 12));
ivjButNext.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
ivjButNext.setText(resLocale.getString("next"));
ivjButNext.setSelected(true);we get the following problems
1. the buttons will not be transparent. we don't know if the gif not be shown correctly or the button-background.
2. the border is still visible. the borderpainted/focuspainted-command doesn't work correctly
thx for prof. answers
oliverIt is because XP laf doesn't have the same behavior as previous Wndows laf (skins!).
if you want to have your own design change the UI for the buttons :
JButton b = new JButton("Test");
b.setUI(new BasicButtonUI());
b.setBorder(BasicBorders.getButtonBorder()); // don't forget for buttons only
JToggleButton tb = new JToggleButton("Test");
tb.setUI(new BasicToggleButtonUI());If you want to set it for all buttons:
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
catch (Exception e) {
e.printStackTrace();
UIManager.put("ToggleButtonUI", "javax.swing.plaf.basic.BasicToggleButtonUI");
UIManager.put("ButtonUI", "javax.swing.plaf.basic.BasicButtonUI");(don't forget to set also the border for the JButtons if you want it)
Denis -
ImageIcons in a JLabel get their top-most row of pixels cut off
Hello. I've added a "Loading..." screen to my application that basically consists of a JWindow with a background image. However, I've noticed something odd when adding an ImageIcon to a JLabel. It seems that any image I add gets its top row of pixels cut off. The small program below illustrates this.
import javax.swing.*;
import java.awt.*;
public class JLabelTest {
static final String WINDOW_IMAGE = "my_image.jpg";
* Create and display the loading screen
private static void displayLoadingScreen()
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JWindow winLoadingScreen = new JWindow();
ImageIcon loadingImg = new ImageIcon(WINDOW_IMAGE);
JLabel lblImage = new JLabel(loadingImg);
winLoadingScreen.getContentPane().add(lblImage);
winLoadingScreen.pack();
System.out.println("label dimensions: " + lblImage.getSize().width + " x " + lblImage.getSize().height);
System.out.println("image icon dimensions: " + loadingImg.getIconWidth() + " x " + loadingImg.getIconHeight());
winLoadingScreen.setLocation(100, 100);
winLoadingScreen.setVisible(true);
* Entry point
* @param args
public static void main(String[] args)
SwingUtilities.invokeLater(new Runnable() {
public void run()
displayLoadingScreen();
}(Obviously, replace my_image.jpg with something else if you'd like to run the code on your own machine.)
When I run the program with, say, an 800 x 600 resolution image, the output I get is:
label dimensions: 800 x 599
image icon dimensions: 800 x 600As you can see, the image gets "shortened" by one pixel when added to the JLabel. If you look at the image that is displayed, you can see that it's the top row that gets cut off. I've tried changing the layout of the JWindow that the JLabel is being added to, but that didn't change anything. I've tried using a number of different images in varying formats, and the same thing happens to all of them.
Any ideas? Thanks in advance.Have you tried to set label's preferredSize manually?
What happens when you add empty border t the label with some insets?
regards,
Stas -
Hello,
I've just about finished a program I've been working on for the last few weeks. But I need some help with one more thing. What I want to do is somehow build into my If and Else statements some code that will change the ImageIcon to a certain picture depending on where the click was. For instance, in my code right now I have code in place:
if (x < 200) // if the click is below 200 on the x axis
setTitle("LEFT (" + x + ", " + y + ")");
else if (x > 440) // if the click is above 440 on the x axis
setTitle("RIGHT (" + x + ", " + y + ")");
.....And such. This is just in place until I get the code in that will change the ImageIcon. I am thinking that I will need to set up an ImageIcon arrary, then have the code be something like
"if (x > 200) and ImageIcon index = 1
set ImageIcon index (4)"
and so on for the rest of the if statements. How would I go about doing this? Is there an easier way than an arrary? Is it possible to have "and" in the "if" statement? My full code is below for more info.
// tourWelby.java
// tourWelby
// A Program that involves a virtual interactive tour of Welby.
// Documentation for this program is located in the 'tourWelby'
// folder.
// Copyright (c) 2005. All rights reserved.
// this imports the necessary Java Packages
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
// this is the main class for the program. It implements the MouseListener
// which is very important to the operation of the program
public class tourWelby extends JFrame implements MouseListener {
// this sets up the label used in the co-ordinate JPanel on the program
private JLabel label;
// this sets up the label used in the image JPanel on the program
private JLabel imageLabel;
// this sets up the label used in the title JPanel on the program
private JLabel titleLabel;
// this sets up the co-ordinate integers
int x,y;
// these methods involve the MouseListener and are used for the program to listen
// to and respond to the mouse
public void mouseReleased(MouseEvent e) { }
public void mouseEntered(MouseEvent e) { }
public void mousePressed(MouseEvent e) { }
public void mouseDragged(MouseEvent e) { }
public void mouseExited(MouseEvent e) { }
// the mouseClicked method makes the program respond to mouse clicks
public void mouseClicked(MouseEvent e) {
// this finds the x and y co-ordinates where the user has clicked
x = e.getX();
y = e.getY();
// this sets the title of the frame to display the cursor co-ordinates; and the
// position the user is facing (Forward, Back, Left, or Right) depending on where
// the co-ordinate is that was clicked on (through use of the IF and ELSE statements)
if (x < 200) // if the click is below 200 on the x axis
setTitle("LEFT (" + x + ", " + y + ")");
else if (x > 440) // if the click is above 440 on the x axis
setTitle("RIGHT (" + x + ", " + y + ")");
else if (y < 200) // if the click is below 200 on the y axis
setTitle("FORWARD (" + x + ", " + y + ")");
else if (y > 280) // if the click is above 280 on the y axis
setTitle("BACK (" + x + ", " + y + ")");
// insert comments...
public tourWelby() { // insert comments
// this creates the program's frame, sets its colour, and makes it not resizable
super("Tour Welby");
setResizable(false);
setBackground(Color.BLACK);
// sets up a new JButton for quitting the program.
// also sets up the size and location of the quit button and adds a Mnemonic for
// keyboard control
JButton quitButton = new JButton("Quit");
quitButton.setSize(80,30);
quitButton.setLocation(176,580);
quitButton.setMnemonic('Q');
// setups up a new JButton called aboutBoxButton, which brings up the About Box.
// also sets up the size and location of the about box button and adds a Mnemonic for
// keyboard control
JButton aboutBoxButton = new JButton("About");
aboutBoxButton.setSize(80,30);
aboutBoxButton.setLocation(86,580);
aboutBoxButton.setMnemonic('A');
// the container is what holds all of the components of the program (all of the JPanels,
// JMenuBar, etc). The quit button and about box button are added at this stage
Container content = getContentPane();
getContentPane().add(quitButton);
getContentPane().add(aboutBoxButton);
// makes a new JButton for use in the About Box and sets up its colour, size and location
JButton aboutCloseButton = new JButton("OK");
aboutCloseButton.setBackground(Color.BLACK);
aboutCloseButton.setForeground(Color.BLACK);
aboutCloseButton.setSize(60,30);
// makes a new JTextPane for use in the About box, and sets the Text, colours, border, and
// makes it uneditable. Also adds the aboutCloseButton and its position in the TextPane
JTextPane aboutpane = new JTextPane();
aboutpane.setText("text goes in here");
aboutpane.setForeground(Color.RED);
aboutpane.setBackground(Color.BLACK);
aboutpane.setBorder(BorderFactory.createMatteBorder(2,2,2,2, Color.RED));
aboutpane.setEditable(false);
aboutpane.add(aboutCloseButton);
aboutCloseButton.setLocation(4,400);
// sets up a JFrame for the About Box, adds the JTextPane aboutpane to the About Box.
// also sets the colours, size, location, visibility of the frame and makes it non resizable
final JFrame aboutFrame = new JFrame("About Tour Welby");
aboutFrame.setSize(400, 460);
aboutFrame.setLocation(210,160);
aboutFrame.getContentPane().add(aboutpane);
aboutFrame.setBackground(Color.BLACK);
aboutFrame.setVisible(false);
aboutFrame.setResizable(false);
// creates the labels for use in the JPanels
titleLabel = new JLabel();
imageLabel = new JLabel();
// sets the text, font, and colour for the label used in theTitleArea
titleLabel.setText("Tour Welby");
titleLabel.setFont(new Font("Charcoal", Font.BOLD, 48));
titleLabel.setForeground(Color.RED);
// sets up the ImageIcon which is used on the JLabel "imageLabel"
ImageIcon theImage = new ImageIcon("images/1f.jpg");
// sets the size of the imageLabel used in theArea, sets the imageIcon to the imageLabel
// and makes it visible.
imageLabel.setSize(new java.awt.Dimension(640, 480));
imageLabel.setIcon(theImage);
imageLabel.setVisible(true);
// IMPORTANT: sets the MouseListener to run on the imageLabel specified.
// This allows the user to click on various parts of the imageLabel and have the
// program respond accordingly by loading other images and setting title
// to the co-ordinates of the mouse click
imageLabel.addMouseListener(this);
// sets a border (and defines its width and colour) to the imageLabel
imageLabel.setBorder(BorderFactory.createMatteBorder(2,2,2,2, Color.RED));
// makes a new JMenuBar for use in the frame and sets the menu bar colour
JMenuBar menu = new JMenuBar();
menu.setBackground(Color.BLACK);
// makes a new menu, a File menu for use in the menu bar, sets the colours of the menu
// and adds a Mnemonic for keyboard control
JMenu fileMenu = new JMenu("File");
fileMenu.setBackground(Color.BLACK);
fileMenu.setForeground(Color.WHITE);
fileMenu.setMnemonic('F');
// makes a menu item called About and adds a Mnemonic for keyboard control
JMenuItem aboutItem = new JMenuItem("About");
aboutItem.setMnemonic('A');
// makes a menu item called Quit and adds a Mnemonic for keyboard control
JMenuItem quitItem = new JMenuItem("Quit");
quitItem.setMnemonic('Q');
// this adds the various menu items to the menus
fileMenu.add(aboutItem);
fileMenu.add(quitItem);
// installs the menu bar in the frame and puts the menus into the menu bar
super.setJMenuBar(menu);
menu.add(fileMenu);
// sets up the JPanel for the title area of the frame, and its size, colour, border and label
JPanel theTitleArea = new JPanel();
theTitleArea.setPreferredSize(new Dimension(644, 70));
theTitleArea.setBackground(Color.BLACK);
theTitleArea.setBorder(BorderFactory.createMatteBorder(2,2,2,2, Color.RED));
theTitleArea.add(titleLabel);
// sets up the main JPanel for the the frame, and its size, colour, and border
JPanel theArea = new JPanel();
theArea.setPreferredSize(new Dimension(820, 680));
theArea.setBorder(BorderFactory.createMatteBorder(2,2,2,2, Color.RED));
// adds the the JPanel theTitleArea, and the JLabel imageLabel in the
// order in which they need to appear
theArea.add(theTitleArea);
theArea.add(imageLabel);
// adds theArea (and subsequently all other JPanels etc) to the container, puts all of
// the JPanels in order in the container, and makes the container visible
getContentPane().add(theArea);
pack();
setVisible(true);
// These are the ActionListners for the program (the quit button, about box button, about
// button, about menu item, quit menu item). Also the WindowListeners are here for the
// main frame (super) and the About Box
quitButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) { System.exit(0); }
}); // action listener for the Quit button
aboutBoxButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) { aboutFrame.setVisible(true); }
}); // action listener for the About Box button (the button that displays the about box)
aboutCloseButton.addActionListener(new ActionListener( ) {
public void actionPerformed(ActionEvent e) { aboutFrame.setVisible(false); }
}); // action listener for the About Box OK button (the button that closes the about box)
aboutItem.addActionListener(new ActionListener( ) {
public void actionPerformed(ActionEvent e) { aboutFrame.setVisible(true); }
}); // action listener for the About menu item
quitItem.addActionListener(new ActionListener( ) {
public void actionPerformed(ActionEvent e) { System.exit(0); }
}); // action listener for the Quit menu item
super.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {System.exit(0);}
}); // window listener for the main frame (super)
aboutFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) { }
}); // window listener for the About Box
// insert comments
public static void main (String args[]) {
new tourWelby();
}Thanks.A JFrame extends a Frame. The latter class has the setIconImage
method, so you can use that ...
kind regards,
Jos -
Quick question - JButton containing an Image - removing the Images border?
Hi, I have a JButton with an image inside it.
I would like the JButton to have a border, but not the image when it is clicked.
It currently looks like this - here
As you can see, there are two borders (this is once the button has been clicked).
The one around the JButton is the one I wish to keep, the one around the ImageIcon is the one I would like removed.
I am sure there is a simple way to do this - I'm sure I have managed it before.
part of the code used to create:
JButton money = new JButton();
money.setBackground(buttonColor);
money.setIcon(new ImageIcon ("money.gif");That thin blue box is indicating the button has focus. It appears even if the button just shows text and has no icon. Here is an example where I get rid of it on btn1 but not btn2.
And in the future, please post Swing questions to the Swing forum.
import java.awt.*;
import javax.swing.*;
public class ButtonExample {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable(){
public void run() {
new ButtonExample().launch();
void launch() {
JPanel cp = new JPanel();
JButton btn1 = new JButton("button 1");
btn1.setFocusPainted(false);
JButton btn2 = new JButton("button 2");
cp.add(btn1);
cp.add(btn2);
JFrame frame = new JFrame("ButtonExample");
frame.setContentPane(cp);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} -
Cannot convert from ImageIcon to Image
Please tell me why I'm getting error: I have seen many example of this both in this forum and other places.
Type mismatch: cannot convert from ImageIcon to Image[b]
Thanks in advance
here's my code, I m using fileupload to load my images:
<%@ page import="java.util.List"%>
<%@ page import="java.util.Iterator"%>
<%@ page import="java.io.File" %>
<%@ page import="java.io.IOException"%>
<%@ page import="java.io.*"%>
<%@ page import="java.awt.image.ImageFilter"%>
<%@ page import="java.awt.Color"%>
<%@ page import="java.awt.image.ImageProducer"%>
<%@ page import="java.awt.image.ReplicateScaleFilter"%>
<%@ page import="java.awt.image.FilteredImageSource"%>
<%@ page import="javax.swing.*"%>
<%@ page import="java.awt.image.BufferedImage"%>
<%@ page import="java.awt.Image"%>
<%@ page import="java.awt.Graphics"%>
<%@ page import="java.awt.Toolkit"%>
<%@ page import="com.sun.image.codec.jpeg.JPEGCodec"%>
<%@ page import="com.sun.image.codec.jpeg.JPEGImageEncoder"%>
<%@ page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@ page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<center><table border="2">
<tr><td><h1>Your files uploaded </h1></td></tr>
<%
//setting the target w + h
int targetWidth=0;
int targetHeight=0;
//session values used to rename loaded image.
String adID = "EM225";
session.setAttribute("adID", adID);
String fileName = null;
// String imageid = request.getParameter("imgageID");
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart) {
} else {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = null;
try {
items = upload.parseRequest(request);
} catch (FileUploadException e) {
System.out.println("Unable to load image" + e.getMessage());
Iterator itr = items.iterator();
while(itr.hasNext()) {
FileItem item = (FileItem) itr.next();
if (item.isFormField()) {
//String name = item.getFieldName(); //This will get the field names. for eg. if u have a hidden field this line will get the hidden filed name.
//value = item.getString();
//out.println(value);
} else {
try {
File fullFile = new File(item.getName());
fileName = fullFile.getName();
String id = (String)session.getAttribute("adID");
String newName = id+fileName;
//passing renamed uploaded image.
Image sourceImage = new ImageIcon(Toolkit.getDefaultToolkit().getImage(newName));
// Calculate the target width and height
float scale = 50/100;
targetWidth = (int)(sourceImage.getWidth(null)*scale);
targetHeight = (int)(sourceImage.getHeight(null)*scale);
BufferedImage resizedImage = this.scaleImage(sourceImage,targetWidth,targetHeight);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(baos);
encoder.encode(resizedImage);
byte[] b = baos.toByteArray();
// File tosave = new File(getServletContext().getRealPath("/"),resizedImage);
// item.write(tosave);
} catch (Exception e) {
System.out.println("Unable to save the image" + e.getMessage());
%>
<%!
private BufferedImage scaleImage(Image sourceImage, int width, int height){
ImageFilter filter = new ReplicateScaleFilter(width,height);
ImageProducer producer = new FilteredImageSource
(sourceImage.getSource(),filter);
Image resizedImage = Toolkit.getDefaultToolkit().createImage(producer);
return this.toBufferedImage(resizedImage);
private BufferedImage toBufferedImage(Image image){
image = new ImageIcon(image).getImage();
BufferedImage bufferedImage = new BufferedImage(image.getWidth(null),image.getHeight(null),BufferedImage.TYPE_INT_RGB);
Graphics g = bufferedImage.createGraphics();
g.setColor(Color.white);
g.fillRect(0,0,image.getWidth(null),image.getHeight(null));
g.drawImage(image,0,0,null);
g.dispose();
return bufferedImage;
%>
</table>
</center>
</table>
</center>Hello. So, it's difficult to say, but the following line is probably the cause of the problem.:
Image sourceImage = new ImageIcon(Toolkit.getDefaultToolkit().getImage(newName));Basically, you are making an ImageIcon by passing an image, but perhaps you can just replace the line with this:
Image sourceImage = Toolkit.getDefaultToolkit().getImage(newName);I use ImageIcon when reading from files, such as:
BufferedImage image = ImageIO.read(file);
Icon icon = new ImageIcon(image);However, if you already have an Image, I don't see why you just can't just use the Image reference. Perhaps someone more wise will have a more concise answer. Good luck. -
Having some problems with ImageIcons and JLabels
I'm making a checkers game, and so far it's going pretty well.
I've got the basic game down, and you can move pieces, jump, your turn ends when you can't jump anymore, etc...
However, I've had three problems:
1.) I'm using JLabels to display my board (8 x 8.. well actually 9 x 9 for an outer row labelled A,B,C,D.. 1,2,3,4...) Anyway, I create the JLabels using something that looks like \:
JLabel square = new JLabel(new ImageIcon("pic.png"));
Now, the picture loads properly, but it seems like the picture is being cropped, and the top and bottom are getting chopped off, so my 36 x 36 pixel *.gif appears to be 36 x 30.
You can see how there is a gap created in:
http://img235.imageshack.us/img235/7765/prob13ky.jpg
Now the problem may be with the GridLayout I am using, but I set the distance between the components in the container to be 0, 0 so I don't think that GridLayout is chopping my icons. I've also tried setPreferredSize(new Dimension(36,36))
for both my ImageIcons and JLabels and for my container (which I set to size 2000,2000, just to make sure there was room). If anyone can help me, it's be appreciated.
2.) I used to be able to view my outside row/column of squares that said A,B,C,D.... and 1,2,3,4... with the square in the corner having a random pic. For some reason now (have no clue why) I now see only the pic in the corner, and then a little gray smudge diagonally under it.
Pic:
http://img347.imageshack.us/img347/8308/prob24im.jpg
I don't know what's wrong. I'm pretty sure it's none of the new methods I've written, as those are all in my static void main (String[] ar) ...... and if I comment all the methods in my main except where I first make the JFrame and set it visible, it still turns out like that. repaint() doesn't help.
3.) For some reason, when I move another window (AIM, the console window, etc...) over my Swing window, it "erases" (turns gray, just wipes clean) the part where I have my squares that have pieces.
What's weird is that:
The border pieces (err.. my one visible corner piece from my second problem) don't get wiped, and some debugging text and JLabels (in a different JPanel) are fine. I don't think the JPanel matters though; the border pieces and the playing squares (which get wiped) are in the same JPanel and same array of squares.
repaint(); also erases ALL of my playing squares, whereas moving a window over them would only erase the part that the window covered.
Also, I added a mouseListener so that whenever I move the mouse over a square, it changes the image (to a tinted version, so you know the mouse is over it) and when you move the mouse away, it returns to normal. However, if I wildly swing the mouse around the area, it seems to lock up and freeze for a few seconds. Is there anything I can do to prevent this??
Thanks in advance.It is hard to tell what your problems are without any code at all (I saw your images, but that doesn't make it easy to see what is wrong in your code). If you do post code, please use code tags (see button above posting box).
I've seen your MouseListener problem before--we had the exact same issue in our code at work. It would freeze up while it processed all of the mouse events (unbearably slow). I'm not at work right now, so I don't recall how it was fixed. Essentially, you need to only process the event periodically. You need to only update the image if the mouse switches squares. Or, only update the image if the distance from the last mouse event is more than some specified amount. We might also have checked the time difference between mouse events before processing a new one. I could look at the code at work tomorrow, if you are still having trouble. -
Image button without border !!!
Hi guys
I have created a button with an image. But, the border surrounding the button is disturbing. I have written the following code :
searchButton = new JButton ("", new ImageIcon ("c:/SEClientFiles/3sr03b.gif"));
searchButton.setMargin( new Insets(0, 0, 0, 0));
searchButton.setOpaque(false);
searchButton.setBounds(540, 60, 90, 40);
p.add(searchButton);
searchButton.addActionListener(this);I just want to remove the border and have a plain image as a button. Could anyone please help me out ?
Thanks in advance.
Regards
kbhatiause
searchButton.setBorderPainted(false);THANKS A LOT !!! -
Hi group,
You know when you start up Mozilla you get a little picture which flashes up breathing fire? I wanna make a frame do that! I've got it so it flashes up a picture for 3 seconds and disposes of itself. From the main application it is run as a thread. I run it by calling
new showflash().
Here is the code ...
import java.awt.*;
import javax.swing.*;
import java.awt.geom.*;
public class Flashpan extends JPanel {
private ImageIcon m_icon;
public Flashpan () {
JFrame frame = new JFrame("Border Title Bar");
frame.setSize(669, 525);
Container content = frame.getContentPane();
content.add(this);
m_icon = new ImageIcon("image.jpg");
/*flash the window*/
frame.setVisible(true);
/* 3 second delay */
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
/*kill the window*/
frame.setVisible(false);
frame.dispose();
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
m_icon.paintIcon(this, g2d, 10, 10);
public static void showflash() {
new Flashpan();
Now the question is How do I make the window borders disappear. I have only one object contained in the frame, the picture. I want everything to disappear without killing it except this picture object? How do I do it? Im sure many people must have done this!! Maybe my code sucks.. pls forgive me :P
Ive been looking at Inset() BorderLayout() etc.. etc.. but cant seem to work it out or find an example. I thought maybe it was frame.Inset(0,0,0,0) but I was wrong.Bingo, Ta for that....
Complete code is as follows (screen centers now)
import java.awt.*;
import javax.swing.*;
import java.awt.geom.*;
public class Flashpan extends JPanel {
private ImageIcon m_icon;
public Flashpan () {
JWindow frame = new JWindow();
frame.setSize(640, 480);
/* Get the size of the screen */
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
/* Determine the new location of the window */
int w = frame.getSize().width;
int h = frame.getSize().height;
int x = (dim.width - w) / 2;
int y = (dim.height - h) / 2;
/* Move the window */
frame.setLocation(x, y);
Container content = frame.getContentPane();
content.add(this);
m_icon = new ImageIcon("image.jpg");
/*flash the window*/
frame.setVisible(true);
/* 3 second delay */
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
/*kill the window*/
frame.setVisible(false);
frame.dispose();
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
m_icon.paintIcon(this, g2d, 0, 0);
public static void showflash() {
new Flashpan();
greg -
Jtable Header's border disappear after placing an icon on it
I tried this in java 1.4
it works fine but the border between the headers of my JTable diappear
Anyone knows why?
ImageIcon icon = new ImageIcon(pathoficon);
DefaultTableCellRenderer headerRenderer =new DefaultTableCellRenderer();
headerRenderer.setIcon(pathoficon);
TableColumnModel colmod = jtable.getColumnModel();
colmod.getColumn(col).setHeaderRenderer(headerRenderer);
jtable.getTableHeader().resizeAndRepaint();Its because DefaultTableCellRenderer isn't quite the mustard for a header renderer. Mine is shown below, the crucial line being setBorder(UIManager.getBorder("TableHeader.cellBorder"));
private class SortHeaderRenderer extends DefaultTableCellRenderer
RenderInfo r_;
SortHeaderRenderer(RenderInfo r)
r_ = r;
public Component getTableCellRendererComponent(javax.swing.JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column)
if (table != null)
JTableHeader header = table.getTableHeader();
if (header != null)
setForeground(header.getForeground());
setBackground(header.getBackground());
setFont(header.getFont());
setText((value == null) ? "" : value.toString());
setBorder(UIManager.getBorder("TableHeader.cellBorder"));
setHorizontalAlignment(SwingConstants.CENTER);
setHorizontalTextPosition(SwingConstants.LEFT);
// Check if we are the primary sort column and if so, which
// direction the sort is in
if ((orderItems_ != null) && (orderItems_.contains(r_)))
if (sortDescending_)
setIcon(sortDescending__.getIcon());
else
setIcon(sortAscending__.getIcon());
else
setIcon(null);
return this;
}Never mind about anything else because that's specific to me. -
anyone know how to change the border dimensions for the set of buttons? for the image the border is fine but for the buttons it takes up half the frame where the buttons only take up a quarter of the frame
import javax.swing.*;
import java.awt.*;
import javax.swing.border.*;
public class TestImageIcon extends JFrame{
private ImageIcon myicon = new ImageIcon("C:/Users/Documents/NetBeansProjects/OOPjava/src/Chapter15/image/my.jpg");
private JButton okbt = new JButton("OK");
private JButton cancelbt = new JButton("Cancel");
public TestImageIcon(){
JPanel p2 = new JPanel();
p2.setLayout(new GridLayout(1,1,10,20));
p2.add(new JLabel(myicon));
okbt.setForeground(Color.ORANGE);
okbt.setBackground(Color.red);
JPanel p1 = new JPanel();
p1.setLayout(new FlowLayout());
p1.add(okbt);
p1.add(cancelbt);
p1.setBorder(new TitledBorder("Two Buttons"));
p2.setBorder(new TitledBorder("My picture"));
setLayout(new GridLayout(2, 1, 5, 5));
add(p2);
add(p1);
public static void main(String[] args){
TestImageIcon frame = new TestImageIcon();
frame.setTitle("TestImageIcon");
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.setVisible(true);
} Edited by: 87654321 on 07-Sep-2011 06:12Don't use a GridLayout for the content pane of the frame. The GridLayout makes all components the same size.
Use the BorderLayout which is the default layout for a frame anyway.
//setLayout(new GridLayout(2, 1, 5, 5));
//add(p2);
//add(p1);
add(p2, BorderLayout.CENTER);
add(p1, BorderLayout.NORTH); -
Border not rendering properly on JPanel
This is just a general question to see if I'm the only one having this problem or whether it is just a bug.
I've got a Jframe with a couple of Jpanels within it. I want a border round one of the panels but for some reason the border only shows fully around 3 edges and only partly along the edge adjacent to the other JPanel.
I thought this might be a layering problem with the panel without the border being placed on top of the border itself but I've had a similar problem with some JTextField. I've got 3 JTextFields in a JPanel each having their own border but every now and again the border will disappear from around the bottom JTextField.
I realise this may well be a problem specific to my system or OS (Win 2000) but I thought I'd just check.
Thanks, ClarkieThanks for replying so quickly. Here is a cut down version of my code. I appologise now for using NetBeans as I believe this is frowned upon by many users of these forums.
* NewJFrame.java
* Created on 14 August 2006, 15:17
package ets;
import java.awt.*;
import javax.swing.*;
* @author administrator
public class sscce extends javax.swing.JFrame
/** Creates new form NewJFrame */
public sscce()
initComponents();
this.setIconImage(new ImageIcon("images/redtick48x48.gif").getImage());
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">
private void initComponents()
java.awt.GridBagConstraints gridBagConstraints;
panelCont = new javax.swing.JPanel();
panelNav = new javax.swing.JPanel();
panelBtnsAndImg = new javax.swing.JPanel();
panelNavBtns = new javax.swing.JPanel();
btnNav_client = new javax.swing.JButton();
btnNav_job = new javax.swing.JButton();
btnNav_inv = new javax.swing.JButton();
btnNav_cert = new javax.swing.JButton();
btnNav_admin = new javax.swing.JButton();
panelLogout = new javax.swing.JPanel();
panelMain = new javax.swing.JPanel();
panelClientMenu = new javax.swing.JPanel();
panelClientMent_title = new javax.swing.JPanel();
labClientMent_title = new javax.swing.JLabel();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("ETS - Client Management System");
setBackground(new java.awt.Color(255, 255, 255));
setExtendedState(javax.swing.JFrame.MAXIMIZED_BOTH);
setName("mainFrame");
panelCont.setLayout(new java.awt.BorderLayout());
panelCont.setBackground(new java.awt.Color(255, 255, 255));
panelNav.setLayout(new java.awt.BorderLayout());
panelNav.setBackground(new java.awt.Color(255, 255, 255));
panelNav.setMaximumSize(new java.awt.Dimension(150, 150));
panelNav.setPreferredSize(new java.awt.Dimension(150, 100));
panelBtnsAndImg.setLayout(new java.awt.GridLayout(0, 1));
panelBtnsAndImg.setBackground(new java.awt.Color(255, 255, 255));
panelBtnsAndImg.setMaximumSize(new java.awt.Dimension(150, 32767));
panelNavBtns.setLayout(new java.awt.GridLayout(0, 1));
panelNavBtns.setBackground(new java.awt.Color(255, 255, 255));
btnNav_client.setText("Clients");
panelNavBtns.add(btnNav_client);
btnNav_job.setText("Jobs");
panelNavBtns.add(btnNav_job);
btnNav_inv.setText("Invoices");
panelNavBtns.add(btnNav_inv);
btnNav_cert.setText("Certificates");
panelNavBtns.add(btnNav_cert);
btnNav_admin.setText("Admin");
panelNavBtns.add(btnNav_admin);
panelBtnsAndImg.add(panelNavBtns);
panelNav.add(panelBtnsAndImg, java.awt.BorderLayout.NORTH);
panelLogout.setLayout(new java.awt.BorderLayout());
panelLogout.setBackground(new java.awt.Color(255, 255, 255));
panelLogout.setMaximumSize(new java.awt.Dimension(150, 32767));
panelNav.add(panelLogout, java.awt.BorderLayout.CENTER);
panelCont.add(panelNav, java.awt.BorderLayout.WEST);
panelMain.setLayout(new java.awt.CardLayout());
panelMain.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
panelClientMenu.setLayout(new java.awt.GridBagLayout());
panelClientMenu.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
panelClientMent_title.setLayout(new java.awt.BorderLayout());
labClientMent_title.setFont(new java.awt.Font("Tahoma", 0, 36));
labClientMent_title.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
labClientMent_title.setText("Main Panel");
panelClientMent_title.add(labClientMent_title, java.awt.BorderLayout.CENTER);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.ipadx = 5;
gridBagConstraints.ipady = 15;
panelClientMenu.add(panelClientMent_title, gridBagConstraints);
panelMain.add(panelClientMenu, "card2");
panelCont.add(panelMain, java.awt.BorderLayout.CENTER);
getContentPane().add(panelCont, java.awt.BorderLayout.CENTER);
jMenu1.setText("Menu");
jMenuBar1.add(jMenu1);
setJMenuBar(jMenuBar1);
pack();
}// </editor-fold>
* @param args the command line arguments
public static void main(String args[])
Toolkit tk = java.awt.Toolkit.getDefaultToolkit();
java.awt.EventQueue.invokeLater(new Runnable()
public void run()
sscce s = new sscce();
s.setExtendedState(javax.swing.JFrame.MAXIMIZED_BOTH);
s.setVisible(true);
// Variables declaration - do not modify
private javax.swing.JButton btnNav_admin;
private javax.swing.JButton btnNav_cert;
private javax.swing.JButton btnNav_client;
private javax.swing.JButton btnNav_inv;
private javax.swing.JButton btnNav_job;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JLabel labClientMent_title;
private javax.swing.JPanel panelBtnsAndImg;
private javax.swing.JPanel panelClientMent_title;
private javax.swing.JPanel panelClientMenu;
private javax.swing.JPanel panelCont;
private javax.swing.JPanel panelLogout;
private javax.swing.JPanel panelMain;
private javax.swing.JPanel panelNav;
private javax.swing.JPanel panelNavBtns;
// End of variables declaration
}Also, I sometimes get a diagonal line going from the top left corner of a container to the first element when the JFrame is resized or reloaded from the Taskbar.
Thanks again, Clarkie
Maybe you are looking for
-
Looking for Custom BIOS for Laptop *MSI GE70 Apache Pro 061* Win 8.1 64
I installed two G Skill Ripjaws 8GB 2133 Mhz Ram chips into my Apache Pro laptop. The speeds only show up as 1000 Mhz. I am trying to get a custom BIOS so I can make the necessary changes to that will allow my memory to run up to speed. Can anyone ou
-
How to update many tables in PL/SQL
Hi all, I have to update EMPNIC colum in all the tables using PL/SQL. There are over 700 tables in the database that has the same column name 'EMPNIC' I create one table called 'UPDATEEMPNIC' According to that table I have to update all the tables. T
-
I cannot get my i mac to boot after I turn on. I get a bright white screen followed by an icon with a ? in the middle of it. I also hear the some knocking in the computer as the HD rotates???
-
Is sgen available on Solaris 7?
Does anyone knows if the sgen (scsi generic driver) available on Solaris 7. It's available on the Solaris 8 but I couldn't find it on the 7.
-
I had my library on my old work computer, that is no longer available. I want to download my library to my home computer. Can I simply hook my 3rd gen. Nano up to my home computer and download my library? Thank you in advance for your help!! Rick T