• 0

Extending JButton issues


Question

Hey all. I want to create some custom buttons throughout my program so I thought I could create a new class that extends JButton, then override the methods I want, however it's not working like I wanted.

So I wanted to start with the following. I don't want the border painted and I dont want the area filled, so I tried overriding the methods. The docs say it has a boolean b, so I tried setting that to false. Now since I overrode it, I'm missing the rest of the method correct? If so, how do I find the rest of it? Is this the best way to achieve what I want. The scenario is I have several buttons and I want to change them, like a css sheet. (I tried using JavaFX but that seems insane)


import javax.swing.JButton;

@SuppressWarnings("serial")
public class SCJButton extends JButton {
/**
* @param args
*/


public SCJButton(String label){
super(label);
}

@Override
public void setBorderPainted(boolean b){
b = false;
}

@Override
public void setContentAreaFilled(boolean b){
b=false;
}

}
[/CODE]

Link to comment
Share on other sites

3 answers to this question

Recommended Posts

  • 0

I'm not sure I'm understanding your question correctly, but can't you use the base-class methods to achieve what you want?


import javax.swing.JButton;

@SuppressWarnings("serial")
public class SCJButton extends JButton {
/**
* @param args
*/


public SCJButton(String label){
super(label);
}

@Override
public void setBorderPainted(boolean b){
super.setBorderPainted(false);
}

@Override
public void setContentAreaFilled(boolean b){
super.setContentAreaFilled(false);
}

}
[/CODE]

This would force the border and content area not to be filled I think (my knowledge of Java and the JButton class is pretty limited), but it's bad because it diverts from user expectations (i.e. [i]"I did setBorderPainted(true), but it still shows false!"[/i]). I think you'd be better off just throwing an exception in those methods instead. Like this:

[code]
public SCJButton(String label){
super(label);
super.setBorderPainted(false);
super.setContentAreaFilled(false);
}

@Override
public void setBorderPainted(boolean b){
throw new UnsupportedOperationException("SCJButton class does not support borders");
}

@Override
public void setContentAreaFilled(boolean b){
throw new UnsupportedOperationException("SCJButton class does not support filling the content area");
}

}
[/CODE]

That still sucks IMO, but there's not much more you can do without inheriting from java.awt.Container, and it'd take you a long time to re-implement all the component methods.

Link to comment
Share on other sites

  • 0

Well if I wanted like 5 of the same buttons, styled the same way, I thought I could create my own button class and create them, so when I change the style of the button class it will change all 5 buttons at once.

Link to comment
Share on other sites

This topic is now closed to further replies.