Connection of JButton and JTextField? - java

I just want to know how to do a new frame via typing a specific character then if you click the Jbutton, all the information (of that character) will pop up - for example a picture or a text.
For example, if I type the word "Dog", a picture of a dog and the information about it will pop out on a new window. Is this possible without database?
I want to do it without a database if it's possible.
Here's my code:
import java.awt.FlowLayout;
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JOptionPane;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.BorderFactory;
import javax.swing.JOptionPane;
//Bago
import java.awt.GridBagLayout; // Para mahatihati yung panel
import java.awt.GridBagConstraints; // para customize yung pagkahati ng panel
class ProgDraftMain {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
ProgDraft gui = new ProgDraft();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setResizable(true);
gui.pack();
gui.setVisible(true);
}
});
}
}
class ProgDraft extends JFrame {
private ImageIcon image1;
private JLabel label1;
private JTextField textField1;
private JButton butones;
private JTextField textField;
ProgDraft() {
JPanel mainPanel = new JPanel(new BorderLayout());
JLabel title = new JLabel("Dog Check", JLabel.CENTER);
Font font = new Font("Gigi", Font.BOLD, 50);
title.setFont(font);
mainPanel.add(title, BorderLayout.NORTH);
String text = "Dogs" + "<br>"
+ "Cute dogs are everywhere" + "<br>" + "<br>"
+ "Take care and stay safe!" + "<br>"
+ "I love my dogs" + "<br>" + "<br>" + "<br>"
+ "Please help!";
JLabel dog = new JLabel("<html><div style=\"text-align: center;\">" + text + "</html>");
dog.setHorizontalAlignment(JLabel.CENTER);
mainPanel.add(dog);
ImageIcon pics = new ImageIcon(getClass().getResource("Capture.png"));
JLabel logo = new JLabel(pics);
logo.setHorizontalAlignment(JLabel.CENTER);
logo.setBorder(BorderFactory.createEmptyBorder(10, 0, 10, 0));
logo.setToolTipText("PIcture.");
JPanel iconFieldPanel = new JPanel();
iconFieldPanel.setLayout( new GridBagLayout() );
GridBagConstraints gc = new GridBagConstraints();
gc.anchor = GridBagConstraints.CENTER; // Saan ikakabit yung component
gc.weightx = 0.5; // (left and right)Space between sa edge nung panel at component
gc.weighty = 0.5; // (top and bottom)^
gc.gridx = 0; //saang cell x-axis
gc.gridy = 0; //^ y axis naman
iconFieldPanel.add(logo, gc);
gc.gridy = 1;
JLabel titleBut = new JLabel("Enter Dog Code:");
iconFieldPanel.add(titleBut, gc);
gc.gridy = 2;
textField = new JTextField(10);
iconFieldPanel.add(textField, gc );
JButton buton1 = new JButton("OK");
gc.gridy = 3;
iconFieldPanel.add( buton1, gc);
JPanel iconFieldWrapper = new JPanel();
iconFieldWrapper.add(iconFieldPanel);
mainPanel.add(iconFieldWrapper, BorderLayout.SOUTH); // add icon and field to bottom
getContentPane().add(mainPanel);
}
}

The following code may help you to solve your problem,
import java.awt.Button;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class PopupExample implements ActionListener
{
JFrame frame;
JTextField t1;
JButton btn;
public PopupExample()
{
frame=new JFrame();
frame.setLayout(null);
frame.setSize(700,700);
frame. setLocation(300,10);
t1=new JTextField();
t1.setBounds(82,10,100,20);
frame.add(t1);
btn=new JButton("SUBMIT");
btn.setBounds(200,10,100,20);
btn.addActionListener(this);
frame.add(btn);
frame.setVisible(true);
}
public static void main(String ar[])
{
PopupExample obj=new PopupExample();
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==btn)
{
String input=t1.getText();
if(input.equals("dog"))
{
JOptionPane.showMessageDialog(null,"my dog");
//you can popup new frame here about dog
//create the object of new class (which contain dog details)here.
//you can use show()
}
}
}
}

It is possible to write a program without database but you have to think about a way to store the data. For database concern, I guess you mean how to store the code and picture of these dogs.

Yes, we can do that without database, but you need to write different logic i.e. hard coding like based on the condition
Example: After getting the data from the text field
String a=xx.getText().toString().trim();if(a.equals("dog"))
{
//call the iframe which u need
}
Note: As you need to store all the images in your working directory, or store all the frames with different names which includes images and information regarding the image and call them according to your requirement.

Related

How to Get these JLabels to be Displayed in my JFrame?

I am attempting to make a "sentence randomizer" that, when a button is pressed, makes a grammatically correct sentence, that may not make any sense, by looping different types of words from a separate folder and separate files. It also alternates colors in each panel. I so far am able to get the JButton to show up, but I can't seem to figure out how to get the panels to appear? Here is my code so far for the UI:
package user_interface;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.util.ArrayList;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import code.sentence;
import user_interface.RandomButtonListener;
public class sentenceUI {
private sentence _s;
private JButton _rando;
public sentenceUI() {
_s = new sentence(this);
JFrame f = new JFrame("Ryan Ellis' Lab 9");
f.setLayout(new BoxLayout(f.getContentPane(), BoxLayout.Y_AXIS));
JPanel topPanel = new JPanel();
f.add(topPanel);
JPanel lowerPanel = new JPanel();
f.add(lowerPanel);
_rando = new JButton("Random Sentence");
_rando.addActionListener(new RandomButtonListener(_s, this));
lowerPanel.add(_rando);
Color c1 = Color.BLUE;
Color c2 = new Color( 255 - c1.getRed(), 255 - c1.getGreen(), 255 - c1.getBlue());
for(int i = 0; i < 8; i++){
JLabel _l = new JLabel();
_l.setBackground(c1);
_l.setForeground(c2);
Color temp = c1;
c1 = c2;
c2 = temp;
_l.setBorder(BorderFactory.createEmptyBorder(0,0,8,5));
_l.setFont(new Font("Comic Sans", Font.BOLD, 18));
topPanel.add(_l);
}
ArrayList<String> _slst = new ArrayList<String>();
_slst.add("WordLists/adjectives.txt");
_slst.add("WordLists/adverbs.txt");
_slst.add("WordLists/determiners.txt");
_slst.add("WordLists/nouns.txt");
_slst.add("WordLists/verbs.txt");
ArrayList<ArrayList<String>> list = new ArrayList<ArrayList<String>>();
list.add(_slst);
int i = 0;
list.get(i % 5);
f.add(topPanel, BorderLayout.PAGE_START);
f.add(lowerPanel, BorderLayout.PAGE_END);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
}
private void createRButton(String string, JPanel lowerPanel) {
createRButton("Random", lowerPanel);
}
You're adding topPanel twice to the JFrame, here
JPanel topPanel = new JPanel();
f.add(topPanel);
and here:
f.add(topPanel, BorderLayout.PAGE_START);
f.add(lowerPanel, BorderLayout.PAGE_END);
and in the 2nd addition, you're adding it as if the JFrame currently used a BorderLayout, but it's not since you've given it a BoxLayout.
Instead, only add the topPanel once, and in a logical way. Also consider giving your JLabel's some dummy text, such as " " so that they have some size when you first pack() your GUI.
Also, your labels are being added but they have no size and are non-opaque and so can't be seen. For example try this within your for loop to see for yourself:
JLabel _l = new JLabel("Label " + i); // to give labels size
_l.setOpaque(true); // so you can see the background color
_l.setBackground(c1);
_l.setForeground(c2);

Word count for a scrollable JTextArea (scrollPane) word count

I have been trying to make a program where data inputted into a JTextArea, would then be counted and then displayed on a JLabel the number of words, after a button is clicked.
However the code I have tried to use, just shows the value of 1 everytime.
Any idea why?
`
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class SPanel extends JPanel {
public SPanel(){
final TextAPanel textPanel = new TextAPanel();
final JLabel outputLabel = new JLabel();
JButton click = new JButton ("Click");
click.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
String word = textPanel.inputBox.getText();
System.out.println("Test: " +word);
}
});
}
}
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class TextAPanel extends JPanel {
public JTextArea inputBox = new JTextArea(20,10);
public JScrollPane scrollPane = new JScrollPane(inputBox);
TextAreaPanel(){
JLabel title = new JLabel("Please type in the box below:");
inputBox.setLineWrap(true);
setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
gc.anchor = GridBagConstraints.NORTHWEST;
gc.gridx = 0;
gc.gridy = 0;
add(title,gc);
gc.gridx = 0;
gc.gridy = 1;
add(scrollPane, gc);
}
}
Just to put it in context, my JTextArea is on a seperate panel / class to the panel containing the button and JLabel.
Every time I run the program and click the button, after inputting some words the value is always one even if the text box is empty.
Well, if you create a new TextAPanel and assign it to the textPanel variable - then when you try to get input you get nothing, because the newly created panel doesn't contain anything. If textPanel is a field in your class, you should just remove the textPanel = new TextAPanel(); line and it should work fine. If you get a NullPointerException, it means you forgot to initialize it earlier in the code, you should probably do it in the constructor.
EDIT: OK, I made it work, the code is below. I have no idea how your program compiled, because in your TextAPanel class you had TextAreaPanel() method/constructor, which caused compilation error in my Eclipse. Anyway, I got this working, you'll need to complete it, but this should get you started:
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
#SuppressWarnings("serial")
public class SPanel extends JPanel {
public SPanel() {
final TextAPanel textPanel = new TextAPanel();
this.add(textPanel);
final JLabel outputLabel = new JLabel();
JButton click = new JButton("Click");
click.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
String word = textPanel.inputBox.getText();
System.out.println("Test: " + word);
System.out.println(word.split("\\s+").length);
}
});
this.add(click);
}
public static void main(String[] args) {
JFrame f = new JFrame();
f.add(new SPanel());
f.setVisible(true);
}
}
#SuppressWarnings("serial")
class TextAPanel extends JPanel {
public JTextArea inputBox = new JTextArea(20, 10);
public JScrollPane scrollPane = new JScrollPane(inputBox);
TextAPanel() {
JLabel title = new JLabel("Please type in the box below:");
inputBox.setLineWrap(true);
setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
gc.anchor = GridBagConstraints.NORTHWEST;
gc.gridx = 0;
gc.gridy = 0;
add(title, gc);
gc.gridx = 0;
gc.gridy = 1;
add(scrollPane, gc);
}
}

GridBagLayout Java

Hi again i've put in my original code just to let you see what i was talking about for the GridBagConstrainsts thats i was trying to put each image to be stuck to the south of the panel immediately next to each other
package prototype;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Image;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JCheckBox;
//Declare the class which extends JFrame and
//implements ActionListener to enable bottons to respond whenever clicked or selected
public class Master extends JFrame implements ActionListener {
//create the bottons visible by the user
JButton check = new JButton("");
JButton playList = new JButton("");
JButton update = new JButton("");
JButton quit = new JButton("");
JCheckBox tick = new JCheckBox("Tick");
JPanel top = new JPanel();
public static void main(String[] args) {
//declare object of the class
Master jf = new Master();
}
public Master() {
setLayout(new BorderLayout());
setSize(1050, 400);
setTitle("Master");
// close application only by clicking the quit button
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
//show the frame in the middle of the screen when run
setLocationRelativeTo(null);
top.add(new JLabel("Select an option by clicking one of the buttons below"));
add("North", top); // add the text above to the upper part of the frame (North)
JPanel bottom = new JPanel();
bottom.setLayout(new GridBagLayout());
bottom.add(check);
check.addActionListener(this);
bottom.add(playList);
playList.addActionListener(this);
bottom.add(update);
update.addActionListener(this);
bottom.add(quit);
quit.addActionListener(this);
add("South", bottom);
//make the frame non resizable but visible
setResizable(true);
setVisible(true);
try{
Image img = ImageIO.read(getClass().getResource("gui/Exit.png"));
Image resize = img.getScaledInstance(290, 180, 18);
quit.setIcon(new ImageIcon(resize));
img = (bottom, new JLabel("NAME"), 0,0,1,1, GridBagConstraints.SOUTH);
}catch(Exception e){
}
try{
Image img = ImageIO.read(getClass().getResource("gui/Untitled.png"));
Image resize = img.getScaledInstance(290, 180, 18);
check.setIcon(new ImageIcon(resize));
}catch(Exception e){
}
try{
Image img = ImageIO.read(getClass().getResource("gui/CPL.png"));
Image resize = img.getScaledInstance(290, 180, 18);
playList.setIcon(new ImageIcon(resize));
}catch(Exception e){
}
try{
Image img = ImageIO.read(getClass().getResource("gui/UpdateLib.png"));
Image resize = img.getScaledInstance(290, 180, 18);
update.setIcon(new ImageIcon(resize));
}catch(Exception e){
}
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == check) {
new CheckLibrary();
} else if (e.getSource() == update) {
new UpdateLibrary();
} else if (e.getSource() == quit) {
System.exit(0);
} else if (e.getSource() == playList) {
new CreatePlaylist();
}
}
}
For that purposes you need to use anchor and weighty properties of GridBagConstraints.
In next example I set JTextField to the south:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Example extends JFrame {
public Example (){
JTextField f = new JTextField(20);
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.SOUTHEAST;
c.weighty = 1;
add(f,c);
}
public static void main(String...strings ){
Example e = new Example();
e.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
e.pack();
e.setLocationRelativeTo(null);
e.setVisible(true);
}
}
If you need to fill all horizontal space by component add next :
c.weightx = 1;
c.fill = GridBagConstraints.HORIZONTAL;
For Image you can use JLabel instead of JTextField in my example :
JLabel l = new JLabel(new ImageIcon(getClass().getResource(PATH_TO_IMAGE)));
You cannot add an image directly to a JPanel. What you can do instead is to set the image to be the image icon of a JPanel or JLabel and add that to whatever you're trying to make.

How do I get my JButton to both switch the JPanel and close the JFrame?

I've managed to get the JButton buttonOne in class Database to switch panels, but at the same time it's opening a new JFrame to do this. How can I change it so it just changes the JFrame panel without having to open another JFrame? I have a feeling I could do this if I could return both JPanel and JFrame but I don't know how to do so. Thanks for any help :
First class, with the JFrame and the JPanel that is being switched to on click of 'buttonOne' :
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDatabaseFarme;
import javax.swing.JLabel;
public class Database{
//Running the GUI
public static void main(String[] args) throws IOException {
Database gui2 = new Database();
gui2.mainPanel();
}
JDatabaseFarme mainPanel() throws IOException {
// GridBagLayout/Constraint
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(15,15,15,15);
final JDatabaseFarme DatabaseFarme = new JDatabaseFarme("Lohn Jocke and the Quest for Qualia"); //Had to set DatabaseFarme to final for the action listener
//JPanel panel = new JPanel(new GridBagLayout()); (??)
final JComponent panel = new JLabel(new ImageIcon(ImageIO.read(new File("res/FinalBG.png")))); //Had to set panel to final for the action listener
panel.setLayout(new GridBagLayout());
////// Creating JButtons/Icons for the buttons ////
BufferedImage buttonIcon = ImageIO.read(new File("res/PlayGame.png"));
JButton button = new JButton ("", new ImageIcon(buttonIcon));
BufferedImage buttonIcon2 = ImageIO.read(new File("res/Scoreboard.png"));
JButton buttonTwo = new JButton ("", new ImageIcon(buttonIcon2));
BufferedImage buttonIcon3 = ImageIO.read(new File("res/SQLs.png"));
JButton buttonThree = new JButton ("",new ImageIcon(buttonIcon3));
// Scoreboard button ActionListener
buttonThree.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
//removed some code from here
try {
panel.setVisible(false);
SQLsPanel a = new SQLsPanel();
JComponent SQLsPanel = a.SQLsPanel();
DatabaseFarme.add(SQLsPanel);
DatabaseFarme.getContentPane().add(BorderLayout.CENTER, SQLsPanel);
SQLsPanel.setVisible(true);
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
////// Creating/adding button rollover images /////
BufferedImage buttonIcon1b = ImageIO.read(new File("res/PlayGameHigh.png"));
button.setRolloverIcon(new ImageIcon(buttonIcon1b));
BufferedImage buttonIcon2b = ImageIO.read(new File("res/ScoreboardHigh.png"));
buttonTwo.setRolloverIcon(new ImageIcon(buttonIcon2b));
BufferedImage buttonIcon3b = ImageIO.read(new File("res/SQLsHigh.png"));
buttonThree.setRolloverIcon(new ImageIcon(buttonIcon3b));
// Setting up GridBagConstraints for each JButton
gbc.weightx=1;
gbc.weighty=0;
gbc.gridx=0;
gbc.gridy=0;
gbc.anchor = GridBagConstraints.CENTER;
panel.add(button, gbc); //PLAY GAME
gbc.weightx=1;
gbc.weighty=0;
gbc.anchor = GridBagConstraints.CENTER;
gbc.gridx=0;
gbc.gridy=1;
panel.add(buttonTwo,gbc); //SCOREBOARD
gbc.weightx=1;
gbc.weighty=0;
gbc.anchor = GridBagConstraints.CENTER;
gbc.gridx=0;
gbc.gridy=2;
panel.add(buttonThree,gbc); //SQLS
// JDatabaseFarme settings
DatabaseFarme.add(panel);
DatabaseFarme.getContentPane().add(BorderLayout.CENTER, panel);
DatabaseFarme.setSize(860,500);
DatabaseFarme.setLocationRelativeTo(null);
DatabaseFarme.setDefaultCloseOperation(JDatabaseFarme.EXIT_ON_CLOSE);
DatabaseFarme.setResizable(false);
DatabaseFarme.setVisible(true);
// JButton icon details
button.setBorder(BorderFactory.createEmptyBorder());
button.setContentAreaFilled(false);
buttonTwo.setBorder(BorderFactory.createEmptyBorder());
buttonTwo.setContentAreaFilled(false);
buttonThree.setBorder(BorderFactory.createEmptyBorder());
buttonThree.setContentAreaFilled(false);
return DatabaseFarme;
}
}
My second class, it contains the JButton that needs to change panel and close the JDatabaseFarme :
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDatabaseFarme;
import javax.swing.JLabel;
public class SQLsPanel {
JComponent SQLsPanel() throws IOException {
final JComponent SQLsPanel = new JLabel(new ImageIcon(ImageIO.read(new File("res/HowToPlayBG.png"))));
SQLsPanel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
BufferedImage buttonOneIcon = ImageIO.read(new File("res/Database.png"));
JButton buttonOne = new JButton("",new ImageIcon(buttonOneIcon));
BufferedImage buttonOneIconB = ImageIO.read(new File("res/DatabaseHigh.png"));
buttonOne.setRolloverIcon(new ImageIcon(buttonOneIconB));
buttonOne.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
SQLsPanel.setVisible(false);
try {
Database passme = new Database();
JDatabaseFarme DatabaseFarmeA = passme.mainPanel();
DatabaseFarmeA.add(SQLsPanel);
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
gbc = new GridBagConstraints();
gbc.insets = new Insets(15,15,15,15);
gbc.weighty = 1;
gbc.weightx = 1;
gbc.gridx = 1;
gbc.gridy = 3;
gbc.anchor = GridBagConstraints.PAGE_END;
SQLsPanel.add(buttonOne, gbc);
buttonOne.setBorder(BorderFactory.createEmptyBorder());
buttonOne.setContentAreaFilled(false);
return SQLsPanel;
}
}
Try the following:
final JFrame frame = new JFrame("Lohn Jocke and the Quest for Qualia"); //Had to set frame to final for the action listener
final String name = frame.getName();
Add the variable 'name' just below where you declare the JFrame.
// JFrame settings
frame.add(panel);
frame.getContentPane().add(BorderLayout.CENTER, panel);
frame.setSize(860,500);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setVisible(true);
if(Frame.getFrames().length > 1){
Frame[] f = Frame.getFrames();
for(Frame frames : f){
if(!frames.getName().equals(name)){
frames.dispose();
}
}
}
Add this below where you set the JFrame settings.
what happens is when you call this
MainMenu passme = new MainMenu();
From the InstructionsPanel you are creating a new JFrame from your class constructor in addition to the current frame you already have(Hence why you end up with 2). what I have tried to do is get the name of your new Frame you are creating(with the name variable), then using the loop at the bottom wipe all other Frames away leaving you with the new one with which to display your Panel.(Frame.getFrames() returns a list of all frames, I then iterate over removing all the ones that aren't needed)
You may want to tweak it if you add more JFrames in future but hopefully this will be somewhat effective for you for now at least.(i have tried to replicate your code with dummy images to grasp at the problem for this 'fix' so apologies if I have misunderstood the issue here )
Hope this helps.

is there a way to set a jbutton on top of a jbutton?

I am wondering about this since we are making a game in Swing and we made our map tiles into jButtons instead of jPanels for whatever reason. Now we want to put units on top of them so the map background is still shown when the unit is on top of them. Anyone know if this is possible?
OK, so I am not sure this is really what you are looking for and how your application is currently set up, but this is an example to have JButtons on top of each other (if this is not what you are looking for, consider posting an SSCCE and give more details). There are other alternatives and better way to handle such thing, but since you asked JButton over a JButton, here is a snippet showing that:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.plaf.ButtonUI;
import javax.swing.plaf.basic.BasicButtonUI;
public class TestButtonGrid {
protected int x;
protected int y;
protected void initUI() throws MalformedURLException {
final JFrame frame = new JFrame();
frame.setTitle(TestButtonGrid.class.getSimpleName());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JPanel panel = new JPanel(new GridBagLayout());
ImageIcon icon = new ImageIcon(new URL("http://manhack-arcade.net/pivot/isdrawing/tile_bluerock.png"));
ImageIcon unit = new ImageIcon(new URL("http://static.spore.com/static/image/500/642/783/500642783372_lrg.png"));
ButtonUI ui = new BasicButtonUI();
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.BOTH;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
gbc.gridx = i;
gbc.gridy = j;
JButton button = new JButton(icon);
button.setBorderPainted(false);
button.setPreferredSize(new Dimension(icon.getIconWidth(), icon.getIconHeight()));
button.setUI(ui);
button.setOpaque(false);
panel.add(button, gbc);
if (i == j) {
// Choose a layout that will center the icon by default
button.setLayout(new BorderLayout());
JButton player = new JButton(unit);
player.setPreferredSize(new Dimension(unit.getIconWidth(), unit.getIconHeight()));
player.setBorderPainted(false);
player.setUI(ui);
player.setOpaque(false);
button.add(player);
}
}
}
frame.add(panel);
frame.setResizable(false);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
new TestButtonGrid().initUI();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
});
}
}
It might be a better idea to have a panel which contains buttons. Your panel could then use a mouse event listener to perform an action when clicked on.
The advantage of using a jPanel is that you can set a layout within it, which will make positioning your buttons in it much easier.
Well it is possible to put a JButton Over an other JButton you just wont be able to see it.
CardLayout cl = new CardLayout();
JPanel jpnlMain = new JPanel(cl);
jpnlMain.add(new JButton(), "FIRST");
jpnlMain.add(new JButton(), "SECOND");
Then Maybe you could create a Class that Extends Either the Cardlayout or the JPanel to make it show both Items.
EDIT
Made a little Test and HJere is a Button in a Button Buttonception!!
Main class:
import javax.swing.JFrame;
public class Test {
public static void main(String[] arg0){
SpecialButton sp = new SpecialButton();
JFrame jf = new JFrame();
jf.add(sp);
jf.setVisible(true);
jf.pack();
}
}
Special Button Class:
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class SpecialButton extends JButton{
SpecialButton(){
super();
JButton jbtnMid = new JButton();
JLabel jlblMid = new JLabel(new ImageIcon(this.getClass().getResource("/Images/arrowUpIcon.png")));
jbtnMid .add(jlblMid);
this.add(jbtnMid);
this.setVisible(true);
}
}

Categories