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);
}
}
Related
I'm creating a chat but that doesn't matter. I have no issues yet, all is working fine, but I want to change the UI appearance so the user can have a bigger JTextArea instead of a button occupying more space than needed. Also, I would want to resize the JTextArea rather than writing several text in only one line. Finally, I have to thank you for spending your time helping me :D
Objectives:
Set size of JLabel or JTextArea so the button stays smaller.
Expand JLabel when text is reaching the right limit and put it in a new line (kinda WhatsApp).
Code:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JTextArea;
import javax.swing.BorderFactory;
import javax.swing.JLabel;
import javax.swing.JTextField;
class MyFirstChatSO extends JFrame {
JLabel title;
JTextArea messages;
JTextField text;
JButton send;
public MyFirstChatSO () {
setLayout(new BorderLayout(0,10));
title = new JLabel("-Chat-");
title.setHorizontalAlignment(JLabel.CENTER);
title.setFont(new Font("Gabriola",Font.ITALIC,34));
add(title, BorderLayout.NORTH);
messages = new JTextArea();
messages.setEnabled(false);
messages.setBorder(BorderFactory.createLineBorder(new Color(168,168,168),2,true));
add(messages, BorderLayout.CENTER);
JPanel subPanel = new JPanel();
subPanel.setLayout(new GridLayout(0,2));
text = new JTextField();
subPanel.add(text);
send = new JButton("Send");
subPanel.add(send);
add(subPanel, BorderLayout.SOUTH);
}
public static void main(String[] args) {
MyFirstChatSO chat = new MyFirstChatSO();
chat.setSize(600,450);
chat.setLocationRelativeTo(null);
chat.setVisible(true);
chat.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
If any other methods such as using different layoutsManagers are the solution it would be good to know about it.
Another fail, but this time with GridBagLayout (I don't know how to use it, help me pls):
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JTextArea;
import javax.swing.BorderFactory;
import javax.swing.JLabel;
import javax.swing.JTextField;
class MyFirstChatSO extends JFrame {
JLabel title;
JTextArea messages;
JTextField text;
JButton send;
public MyFirstChatSO () {
setLayout(new BorderLayout(0,10));
title = new JLabel("-Chat-");
title.setHorizontalAlignment(JLabel.CENTER);
title.setFont(new Font("Gabriola",Font.ITALIC,34));
add(title, BorderLayout.NORTH);
messages = new JTextArea();
messages.setEnabled(false);
messages.setBorder(BorderFactory.createLineBorder(new Color(168,168,168),2,true));
add(messages, BorderLayout.CENTER);
JPanel subPanel = new JPanel();
subPanel.setLayout(new GridBagLayout());
GridBagConstraints gb = new GridBagConstraints();
gb.weightx = 1;
gb.weighty = 1;
gb.fill = GridBagConstraints.HORIZONTAL;
text = new JTextField();
gb.gridx = 0;
gb.gridy = 0;
gb.gridwidth = 6;
gb.fill = GridBagConstraints.HORIZONTAL;
subPanel.add(text,gb);
send = new JButton("Send");
gb.gridx = 7;
gb.gridy = 0;
subPanel.add(send,gb);
add(subPanel, BorderLayout.SOUTH);
}
public static void main(String[] args) {
MyFirstChatSO chat = new MyFirstChatSO();
chat.setSize(600,450);
chat.setLocationRelativeTo(null);
chat.setVisible(true);
chat.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
Another fail, but this time with GridBagLayout (I don't know how to use it, help me pls):
Yes, you need to understand how it works. Always have How to Use GridBagLayout and the JavaDocs available ;)
So, I started with...
JPanel subPanel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 1;
gbc.weighty = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(4, 4, 4, 4);
text = new JTextArea(1, 80);
text.setBorder(new CompoundBorder(new LineBorder(Color.DARK_GRAY), new EmptyBorder(4, 4, 4, 4)));
subPanel.add(text, gbc);
gbc.insets = new Insets(0, 0, 0, 0);
gbc.weightx = 0;
gbc.weighty = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
send = new JButton("Send");
subPanel.add(send, gbc);
And I ended up with something like...
But wait a second, this example is using a JTextArea?! Why!?
Ah, that's because I'm a sneaky, cheaty pants ;)
By using a JTextArea this way, you get an auto expanding text field, for free. Now, it's important to remember, that this is unconstrained, meaning that the user could keeping pressing enter and making the JTextArea fill up more and more space.
To fix that becomes complicated and I'd look into the Scrollable interface for some ideas
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.
I want to align my two of my components to the top left corner of the window.
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
public class MainFrame extends JFrame {
public MainFrame() {
JPanel mainPanel = new JPanel(new BorderLayout());
JPanel gridbagPanel = new JPanel();
this.setLayout(new BorderLayout());
gridbagPanel.setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
JLabel nameLabel = new JLabel(player.getName());
nameLabel.setHorizontalAlignment(SwingConstants.CENTER);
nameLabel.setFont(new Font("Serif",Font.PLAIN,24));
mainPanel.add(nameLabel, BorderLayout.NORTH);
JLabel money = new JLabel("Pinigai: "+new Integer(player.getMoney()).toString());
gc.gridx = 0;
gc.gridy = 0;
gc.anchor = GridBagConstraints.PAGE_START;
gc.insets = new Insets(2,0,0,2);
gridbagPanel.add(money,gc);
JLabel job = new JLabel("Darbas: "+new Integer(player.getSkin()).toString());
gc.gridx = 0;
gc.gridy = 1;
gc.insets = new Insets(2,0,0,2);
gc.anchor = GridBagConstraints.LINE_START;
gridbagPanel.add(job, gc);
mainPanel.setBorder(new EmptyBorder(10,10,10,10));
mainPanel.add(gridbagPanel,BorderLayout.WEST);
add(mainPanel);
getContentPane().revalidate();
}
}
It currently looks like this:
And I would like the lines with numbers in the top left corner.
Note that I'm aware that both JFrame("this" class) and the mainPanel are using BorderLayouts.
Another non-related question: When should I create a new GridBagConstraints object? Why can't I just store one in a private instance variable for all usage needed?
The beauty of GridBagLayout, is that column/row sizes are not fixed (ie, not every row/column has to be the same size, like in GridLayout)
You can "encourage" certain components to occupy more space within their given area then others.
Things like weightx and weighty describe how much of the available space a row/column should occupy. Add in the NORTHWEST anchor constraint and you should begin to see the desired effect.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
public class MainFrame extends JFrame {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new MainFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public MainFrame() {
JPanel mainPanel = new JPanel(new BorderLayout());
JPanel gridbagPanel = new JPanel();
this.setLayout(new BorderLayout());
gridbagPanel.setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
JLabel nameLabel = new JLabel("Bebras");
nameLabel.setHorizontalAlignment(SwingConstants.CENTER);
nameLabel.setFont(new Font("Serif", Font.PLAIN, 24));
mainPanel.add(nameLabel, BorderLayout.NORTH);
JLabel money = new JLabel("Pinigai: " + new Integer(66484).toString());
gc.gridx = 0;
gc.gridy = 0;
gc.anchor = GridBagConstraints.NORTHWEST;
gc.insets = new Insets(2, 0, 0, 2);
gridbagPanel.add(money, gc);
JLabel job = new JLabel("Darbas: " + new Integer(126).toString());
gc.gridx = 0;
gc.gridy = 1;
gc.insets = new Insets(2, 0, 0, 2);
gc.anchor = GridBagConstraints.NORTHWEST;
gc.weightx = 1;
gc.weighty = 1;
gridbagPanel.add(job, gc);
mainPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
mainPanel.add(gridbagPanel, BorderLayout.WEST);
add(mainPanel);
getContentPane().revalidate();
}
}
Normally, I would add a "filler" component into the component, using it to push all the other components to where I want them, but this will come down to what it is you want to achieve.
Take a look at How to use GridBagLayout for more details
Im more of a fan of Box Layouts to achieve this type of static positioning in swing. see the example below:
import java.awt.Dimension;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class main extends JFrame {
public static void main(String[] args) throws InterruptedException {
main m = new main();
m.setVisible(true);
}
public main() {
// setup stuff
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setBounds(100, 100, 500, 500);
// this is the panel I will add to the frame
JPanel innerPanel = new JPanel();
// give it a Y axis to stuff is added top to bottom
innerPanel.setLayout(new BoxLayout(innerPanel, BoxLayout.Y_AXIS));
// this is a temp panel ill used to add the labels
JPanel tPanel = new JPanel();
// its an x axis to add stuff left to right
tPanel.setLayout(new BoxLayout(tPanel, BoxLayout.X_AXIS));
// create and add a label to the temp panel
JLabel label = new JLabel("Some text");
tPanel.add(label);
// use our stretchy glue to fill the space to the right of the label
tPanel.add(Box.createHorizontalGlue());
// add the temp panel to the inner panel
innerPanel.add(tPanel);
// create a spacer with 0 width and 10 height
innerPanel.add(Box.createRigidArea(new Dimension(0, 10)));
// reinitialize the temp panel for another label
tPanel = new JPanel();
tPanel.setLayout(new BoxLayout(tPanel, BoxLayout.X_AXIS));
label = new JLabel("Some other text");
// add the other label to the temp panel
tPanel.add(label);
// more stretchy glue
tPanel.add(Box.createHorizontalGlue());
// add the temp panel
innerPanel.add(tPanel);
// add verticle stretchy glue to fill the rest of the space below the
// labels
innerPanel.add(Box.createVerticalGlue());
// add to the frame
this.add(innerPanel);
}
}
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.
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);
}
}