How do I cover all my JButton with the ImageIcon given?
my JButtoon size is 90x90 and my Image as well
I also set a text to my JButton (the text is necessary for the program to work)
Code: (I get a padding inside mi button)
btnBoton[i][j].setText(Integer.toString(i)+","+Integer.toString(j));
btnBoton[i][j].setIcon(new ImageIcon("img//"+num+".jpg"));
(When I comment my setText):
//btnBoton[i][j].setText(Integer.toString(i)+","+Integer.toString(j));
btnBoton[i][j].setIcon(new ImageIcon("img//"+num+".jpg"));
I'm trying to acomplish as the second image but without commenting my setText
you can use these two methods to place text at the center of buttons
btnBoton[i][j].setHorizontalTextPosition(JButton.CENTER);
btnBoton[i][j].setVerticalTextPosition(JButton.CENTER);
and texts will be placed in center of buttons,
if you want to assign a value to buttons and don't showing any text, instead of .setText(),create a new class like MJButton which extends JButton and create a String field to it named tag or data or etc. then encapsulate the field and use .setTag() and .getTag() to do so.
class MJButton extends JButton {
private String tag;
public MJButton(String tag, Icon icon) {
super( icon);
this.tag = tag;
}
public MJButton() {
super();
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
}
so use this new class to create buttons, in two ways:
1: btnBoton[i][j] = new MJButton();
and call .setTag() for them:
btnBoton[i][j].setTag(Integer.toString(i)+","+Integer.toString(j));
2: assign icon and tag to button in one line using second constructor
btnBoton[i][j] = new MJButton((Integer.toString(i)+","+Integer.toString(j)), new ImageIcon("img//"+num+".jpg"));
Related
I am working on a simple image guessing game. Instead of having a jLabel for each image, I'm using only one jLabel and it changes its icon using arrays when a button is clicked after the image has been guessed correctly.
But how can I code it so that the answer required in the jTextField (txtAnswer) is determined by the icon set in the jLabel?
So for instance, if the current icon is of the Aston Martin DBS and the user guesses correctly, the icon will then change to the Ferrari 458. What must I do then to ensure that the txtAnswer will now require the user to enter "Ferrari 458" to guess correctly based on the image icon that is set?
Here is the code I currently have:
private static String[] imageList = {"/carGuessPackage/2010 Aston Martin DBS.jpg", "/carGuessPackage/2010 Ferrari 458 Italia.jpg"};
//This method is called in the constructor to set the first image on startup
public void firstIcon()
{
ImageIcon image;
image = new javax.swing.ImageIcon(getClass().getResource(imageList[0]));
lblImage.setIcon(image);
}
private void btnCheckActionPerformed(java.awt.event.ActionEvent evt) {
ImageIcon image;
if(imageList[0].equals(true))
{
if("Aston Martin DBS".equals(txtAnswer.getText()))
{
image = new javax.swing.ImageIcon(getClass().getResource(imageList[1]));
lblImage.setIcon(image);
}
else
{
JOptionPane.showMessageDialog(this, "Incorrect");
}
}
}
Check out the JLabel.setIcon() method. You would need and array of Icon objects, and they would be passed to the existing JLabel.
I want to have several JavaFX Buttons that update one Label in my Application with text. For testing purposes it's just Button Text.
What I did at first worked fine and looked like this:
String Text = "...";
public void kons() {
System.out.println("Works...");
System.out.println(Text);
Tekst.setText(Text);
Button G4 = new Button("Spadantes");
G4.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
Text = G4.getText();
kons();
}
});
Then I decided to stylize my buttons with CSS and because I wanted to have several groups of buttons stylized in different way I subclassed JavaFX Button class in this way:
public class Buttons extends Button {
public Buttons(String text) {
super(text);
getStylesheets().clear();
getStylesheets().add("./Buttons.css");
Which still worked. But now I want my event handler to be moved to Button subclass (to avoid copy-pasting exactly same code into each and every button of mine). What I did looks like this:
public class Buttons extends Button {
public Buttons(String text) {
super(text);
getStylesheets().clear();
getStylesheets().add("./Buttons.css");
setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
Main.Text = getText();
Main.kons();
}
});
}
}
Main is my extend Application class
Tekst is my label.
And sadly it throws me exception about calling non-stathic method and variable from static context. From what I understand instances are static and definitions are non-static. I tried to change everything "in the way" to static but it gives me red wall of errors after clicking button (nothing in compilation process). I also tried to call instance of my Application somehow but I have no idea how (from what I understand extend Application class intantiates itself on it's own while starting program so there's no "name" by which I can call it's Label.
What I'm looking for is "quick and dirty solution" to be able to use subclassed buttons (or other sliders, text-fields, etc.) that can call a method that updates something "on screen".
[EDIT] I'm using newest Java there is of course. In case it matters.
Instead of subclassing, why not just write a utility method that creates the buttons for you? I would also not recommend making the text variable an instance variable: just reference the Label directly.
public class SomeClass {
private Label tekst ;
// ...
private Button createButton(String buttonText) {
Button button = new Button(buttonText);
button.getStylesheets().add("Buttons.css") ;
button.setOnAction(e -> tekst.setText(buttonText));
return button ;
}
}
Then, from within the same class, when you need one of those buttons you just do
Button button = createButton("Text");
If you really want to subclass (which just seems unnecessary to me), you need to pass a reference to the label to the subclass:
public class LabelUpdatingButton extends Button {
public LabelUpdatingButton(String text, Label labelToUpdate) {
super(text);
getStylesheets().add("Buttons.css");
setOnAction(e -> labelToUpdate.setText(getText()) );
}
}
Then from your class that assembles the UI you can do
public class Main extends Application {
#Override
public void start(Stage primaryStage) {
Label tekst = new Label();
Button someButton = new LabelUpdatingButton("Button text", tekst);
// etc...
}
}
But again, creating a subclass that does nothing other than define a constructor that calls public API methods is redundant, imo.
Also, it's a bit unusual to create an entire stylesheet just for your buttons. Typically you would set a style class on the Button:
button.getStyleClass().add("my-button-class");
and then in the stylesheet you add to the Scene do
.my-button-class {
/* styles for this type of button */
}
I want to have a JInternalFrame that will be able to handle JTabbedPane much like the Eclipse IDE. I want the tabs to sit on top of the title bar. Each tab should have its own close button. The InternalFrame should also have a close button so that a user can close all the tabs in one go.
This is what I have:
This is what I want to have (screenshot taken from Eclipse IDE):
I don't know how I can achieve this. Can anyone please point me in the right direction?
EDIT:
Based on a comment to look into UI Delegate, I created a UI delegate subclass that is able to remove the menu, but there are some problems with this:
It looks kind of funny in comparison to a normal JInternalFrame, even though I haven't done anything to it but comment out the "createActionMap" and "add(menuBar)" lines.
I can't find anywhere in the library code to indicate how the title bar and contentPane positions are set - obviously I want to move the position of the contentPane to overlap the title bar.
Here are the codes:
public class MyInternalFrameUI extends BasicInternalFrameUI {
public MyInternalFrameUI(JInternalFrame b) {
super(b);
// TODO Auto-generated constructor stub
}
public static ComponentUI createUI(JComponent b) {
return new MyInternalFrameUI((JInternalFrame)b);
}
protected JComponent createNorthPane(JInternalFrame w) {
titlePane = new MyBasicInternalFrameTitlePane(w);
return titlePane;
}
}
public class MyBasicInternalFrameTitlePane extends BasicInternalFrameTitlePane {
public MyBasicInternalFrameTitlePane(JInternalFrame f) {
super(f);
}
protected void installTitlePane() {
installDefaults();
installListeners();
createActions();
enableActions();
//createActionMap(); // This method is package protected and not visible
setLayout(createLayout());
assembleSystemMenu();
createButtons();
addSubComponents();
}
protected void addSubComponents() {
//add(menuBar); // Remove this to disable the menu
add(iconButton);
add(maxButton);
add(closeButton);
}
}
To answer one part with the close button. A solution is to add the close button yourself (there is no option for that built in Swing).
You have to implement the closeTab(…) method or a better solution would be a callback handler
protected class CloseTabButton extends JPanel {
private JLabel titleLabel;
protected CloseTabButton(JTabbedPane aTabbedPane,
final AbstractObservableObjectJPanel<M> aDetailPanel,
String aTitle, Icon anIcon) {
setOpaque(false);
titleLabel = new JLabel(aTitle, anIcon, JLabel.LEFT);
add(titleLabel);
ImageIcon closeImage = new ImageIcon(
CloseTabButton.class.getResource("/images/icon_normal.png"));
Image img = closeImage.getImage();
Image newimg = img.getScaledInstance(16, 16,
java.awt.Image.SCALE_SMOOTH);
ImageIcon closeIcon = new ImageIcon(newimg);
ImageIcon closeImageRollover = new ImageIcon(
CloseTabButton.class.getResource("/images/icon_roll.png"));
Image imgRoll = closeImageRollover.getImage();
Image newimgRoll = imgRoll.getScaledInstance(16, 16,
java.awt.Image.SCALE_SMOOTH);
ImageIcon closeIconRoll = new ImageIcon(newimgRoll);
JButton btClose = new JButton(closeIcon);
btClose.setPreferredSize(new Dimension(15, 15));
add(btClose);
btClose.setOpaque(false);
btClose.setContentAreaFilled(false);
btClose.setBorderPainted(false);
btClose.setRolloverIcon(closeIconRoll);
btClose.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent aE) {
closeTab(aDetailPanel);
}
});
aTabbedPane.setTabComponentAt(
aTabbedPane.indexOfComponent(aDetailPanel), this);
}
public JLabel getTitleLabel() {
return titleLabel;
}
}
To add keyboard shortcuts you can add them to the input map via
KeyStroke ctrlW = KeyStroke.getKeyStroke(KeyEvent.VK_W,
InputEvent.CTRL_DOWN_MASK);
getRootPane()
.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
.put(ctrlW, disposeAction.getValue(Action.NAME));
DisposeAction is just an Action that also calls closeTab(…)
I made a game using NetBeans design tool, called WordHunt. It looks like this:
I need to make a class that will apply a mouseover effect to those 16 labels I have. This is the code that changes the icon B when enter the mouse:
private void b1MouseEntered(java.awt.event.MouseEvent evt) {
b1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ip/imag/" +B+ ".png")));
}
I had applied a default icon to the label.
After making that class, instead of writing:
b1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ip/imag/" +B+ ".png")));
to write className(b1 ,B);
For the next label, the same thing
className(b2 ,C);
Observation: b1 is a label and I have all letters icon in .png format from A to Z.
Can anybody give me an idea of how I can do that?
If I understand what you want to do, you can use this method:
public void setRolloverIcon(Icon rolloverIcon)
defined in the class JButton to configure the rollover icon.
Just create a simple class like this:
class HoverEffectButton extends JButton{
HoverEffectButton(Image img1, Image img2) {
super(new ImageIcon(img1));
this.setRolloverIcon(new ImageIcon(img2));
}
}
Hope this will help.
And of course you can create a helper class that permits to load an image according to the image name
class AssetsHelper{
private static final String DEFAULT_ASSETS_ROOT = "assets/";
private static final String DEFAULT_IMAGE_SUBFIX = ".png";
public static Image loadImage(String name){
BufferedImage img = null;
try {
img = ImageIO.read(new File(DEFAULT_ASSETS_ROOT + name + DEFAULT_IMAGE_SUBFIX));
} catch (IOException e) {
....
}
return img;
}
}
How about something like this: (rough draft)
// for storage so we don't load it for each mouse-over
HashMap<String, ImageIcon> images = new HashMap<String, ImageIcon>();
void setIcon(JLabel button, String image)
{
if (images.containsKey(image))
return images.get(image);
else
{
String path = "/ip/imag/" + image + ".png";
ImageIcon icon = new ImageIcon(getClass().getResource(path));
images.put(image, icon);
return icon;
}
}
And then:
setIcon(b1, "B");
But you should probably consider using buttons so you can use setRolloverIcon rather than MouseEntered.
public class MyButton extends JButton {
private ImageIcon normalIcon;
private ImageIcon hoverIcon;
public MyButton(String normalURL) {
String hoverURL = normalURL.replaceFirst("\\.png$", "-hover.png");
normalIcon = new ImageIcon(getClass().getResource("/ip/imag/" +B+ ".png"); // or so
hoverICon = ...
}
private void b1MouseEntered(MouseEvent evt) {
setIcon(hoverIcon);
}
}
Firstly at the top of your code add this import:
import javax.swing.ImageIcon;
//Then you only need to write
new ImageIcon(...);
Instead of:
new javax.swing.ImageIcon(...)
Already shorter :)
Then you can create a hashmap of the images preloaded where each instance of B is the key and the loaded icon is the value.
if i get u well i think you want just an image and not evry image to chang when mouse is on it right. if that is the case what u should do is to get the position of each image in a buffer and compare it with the mouse x n y position to know wc image to change. I hope this solve your problem
How can I display a series of images one by one every time the user clicks the next button?
I have few images stored in array. I used button next to go from image to image. How to programme the button? I used action listener but I just don't know how to get back to the array.
I know I'm being lazy here by not writing the entire code, but here goes anyway.
class whatEver implements ActionListener{
JButton btnNext = new JButton();
static int fileNumber = 0;
static int totalFiles;
void functionLoadInterface () //Function with
{
btnNext.addActionListener(this);
//Initialize array ImageArray with file paths.
}
public void cycleImage()
{
String file = ImageArray[fileNumber%totalFiles];
//Code to load the image wherever follows
}
public void actionPerformed(ActionEvent e)
{
filenumber++;
this.cycleImage();
}