So my goal is to disable buttons on lets say panel B depending one what button they press on panel A. so below I have 2 combo boxes that id like to be able to enable or disable base on the buttons pressed on the first panel. Ive tried googling this problem but I'm new to java so its pretty rough going so far.
heres my sample code of what I'm trying to do.
package pack2;
import java.awt.EventQueue;
import javax.swing.JFrame;
import java.awt.CardLayout;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
public class tessst {
public boolean enableChk1;
public boolean enableChk2;
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
tessst window = new tessst();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public tessst() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new CardLayout(0, 0));
final JPanel panel = new JPanel();
frame.getContentPane().add(panel, "name_15095567731094");
panel.setLayout(null);
final JPanel panel_1 = new JPanel();
frame.getContentPane().add(panel_1, "name_15101078033315");
panel_1.setLayout(null);
JButton select2 = new JButton("2 boxes");
select2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
enableChk1 = true;
enableChk2 = true;
panel_1.revalidate();
frame.repaint();
panel_1.repaint();
frame.repaint();
panel.setVisible(false);
panel_1.setVisible(true);
}
});
select2.setBounds(276, 101, 89, 23);
panel.add(select2);
JButton select1 = new JButton("1 boxes");
select1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
enableChk1 = true;
panel_1.revalidate();
frame.repaint();
panel_1.repaint();
frame.repaint();
panel.setVisible(false);
panel_1.setVisible(true);
}
});
select1.setBounds(59, 101, 89, 23);
panel.add(select1);
JButton select0 = new JButton("no boxes");
select0.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
enableChk1 = false;
enableChk2 = false;
panel_1.revalidate();
frame.repaint();
panel_1.repaint();
frame.repaint();
panel.setVisible(false);
panel_1.setVisible(true);
}
});
select0.setBounds(166, 169, 89, 23);
panel.add(select0);
JComboBox comboBox = new JComboBox();
comboBox.setEnabled(enableChk1);
comboBox.setModel(new DefaultComboBoxModel(new String[] {"1", "2", "3"}));
comboBox.setBounds(52, 100, 61, 20);
panel_1.add(comboBox);
JComboBox comboBox_1 = new JComboBox();
comboBox_1.setEnabled(enableChk2);
comboBox_1.setModel(new DefaultComboBoxModel(new String[] {"1", "2", "3"}));
comboBox_1.setBounds(265, 100, 79, 20);
panel_1.add(comboBox_1);
JButton back = new JButton("go back");
back.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
panel.setVisible(true);
panel_1.setVisible(false);
}
});
back.setBounds(10, 227, 89, 23);
panel_1.add(back);
}
}
I needed to declare my comboBox's above my buttons then declare them as final.
here are the changes
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class tessst {
public boolean enableChk1;
public boolean enableChk2;
JComboBox comboBox;
JComboBox comboBox_1;
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
tessst window = new tessst();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public tessst() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new CardLayout(0, 0));
final JPanel panel = new JPanel();
frame.getContentPane().add(panel, "name_15095567731094");
panel.setLayout(null);
final JPanel panel_1 = new JPanel();
frame.getContentPane().add(panel_1, "name_15101078033315");
panel_1.setLayout(null);
JButton select2 = new JButton("2 boxes");
select2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
enableChk1 = true;
enableChk2 = true;
panel_1.revalidate();
frame.repaint();
panel_1.repaint();
frame.repaint();
panel.setVisible(false);
panel_1.setVisible(true);
comboBox.setEnabled(true);
comboBox_1.setEnabled(true);
}
});
select2.setBounds(276, 101, 89, 23);
panel.add(select2);
JButton select1 = new JButton("1 boxes");
select1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
enableChk1 = true;
panel_1.revalidate();
frame.repaint();
panel_1.repaint();
frame.repaint();
panel.setVisible(false);
panel_1.setVisible(true);
comboBox.setEnabled(true);
}
});
select1.setBounds(59, 101, 89, 23);
panel.add(select1);
JButton select0 = new JButton("no boxes");
select0.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
enableChk1 = false;
enableChk2 = false;
panel_1.revalidate();
frame.repaint();
panel_1.repaint();
frame.repaint();
panel.setVisible(false);
panel_1.setVisible(true);
comboBox.setEnabled(false);
comboBox_1.setEnabled(false);
}
});
select0.setBounds(166, 169, 89, 23);
panel.add(select0);
comboBox = new JComboBox();
comboBox.setEnabled(enableChk1);
comboBox.setModel(new DefaultComboBoxModel(new String[] {"1", "2", "3"}));
comboBox.setBounds(52, 100, 61, 20);
panel_1.add(comboBox);
comboBox_1 = new JComboBox();
comboBox_1.setEnabled(enableChk2);
comboBox_1.setModel(new DefaultComboBoxModel(new String[] {"1", "2", "3"}));
comboBox_1.setBounds(265, 100, 79, 20);
panel_1.add(comboBox_1);
JButton back = new JButton("go back");
back.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
panel.setVisible(true);
panel_1.setVisible(false);
}
});
back.setBounds(10, 227, 89, 23);
panel_1.add(back);
}
}
replace your code with this one. Its working Fine. Hope you are expecting this thing.
Related
So, I have this task where the user guess the correct number just by clicking on the JLabel I have presented for them. What I was trying to is to generate a random number then use if (e.getSource() == random) { } but it seems object and int isn't a compatible operand and I was hoping if someone has any solution to this.
Anyways, here is the source code of what I am doing nothing good since I don't have any solution on my first problem yet.
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.BorderLayout;
import java.awt.Font;
import java.util.Random;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class Test123 {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test123 window = new Test123();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Test123() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
Random generator = new Random();
int num;
num = generator.nextInt(9) + 1;
int count = 0;
frame = new JFrame();
frame.setBounds(100, 100, 405, 195);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel NO1 = new JLabel("1");
NO1.setBounds(20, -26, 43, 183);
NO1.setFont(new Font("Arial", Font.BOLD, 75));
frame.getContentPane().add(NO1);
JLabel NO2 = new JLabel("2");
NO2.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
}
});
NO2.setFont(new Font("Arial", Font.BOLD, 75));
NO2.setBounds(60, -26, 43, 183);
frame.getContentPane().add(NO2);
JLabel NO3 = new JLabel("3");
NO3.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
}
});
NO3.setFont(new Font("Arial", Font.BOLD, 75));
NO3.setBounds(102, -26, 43, 183);
frame.getContentPane().add(NO3);
JLabel NO4 = new JLabel("4");
NO4.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
}
});
NO4.setFont(new Font("Arial", Font.BOLD, 75));
NO4.setBounds(143, -26, 43, 183);
frame.getContentPane().add(NO4);
JLabel NO5 = new JLabel("5");
NO5.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
}
});
NO5.setFont(new Font("Arial", Font.BOLD, 75));
NO5.setBounds(184, -26, 43, 183);
frame.getContentPane().add(NO5);
JLabel NO6 = new JLabel("6");
NO6.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
}
});
NO6.setFont(new Font("Arial", Font.BOLD, 75));
NO6.setBounds(223, -26, 43, 183);
frame.getContentPane().add(NO6);
JLabel NO7 = new JLabel("7");
NO7.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
}
});
NO7.setFont(new Font("Arial", Font.BOLD, 75));
NO7.setBounds(264, -26, 43, 183);
frame.getContentPane().add(NO7);
JLabel NO8 = new JLabel("8");
NO8.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
}
});
NO8.setFont(new Font("Arial", Font.BOLD, 75));
NO8.setBounds(304, -26, 43, 183);
frame.getContentPane().add(NO8);
JLabel NO9 = new JLabel("9");
NO9.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
}
});
NO9.setFont(new Font("Arial", Font.BOLD, 75));
NO9.setBounds(345, -26, 43, 183);
frame.getContentPane().add(NO9);
JLabel CorrectAns = new JLabel("Correct!");
CorrectAns.setEnabled(false);
CorrectAns.setBounds(181, 132, 46, 14);
frame.getContentPane().add(CorrectAns);
NO1.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
if (e.getSource() == num) {
count++;
CorrectAns.setText("Correct!" + count + " attempts");
}
}
});
}
}
MouseEvent#getSource will return the object which trigged the event, in your case, the JLabel.
A "generally" better solution might be to use JButton instead, then take advantage of the ActionListener. I'd attach a single ActionListener to the "correct" button to handle the correct workflow and a ActionListener to the others to handle the incorrect state
See How to Use Buttons, Check Boxes, and Radio Buttons and How to Write an Action Listener for more details
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Twst {
public static void main(String[] args) {
new Twst();
}
public Twst() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
randomButtons();
}
protected void randomButtons() {
removeAll();
List<JButton> buttons = new ArrayList<>(4);
Random rnd = new Random();
Set<Integer> numbers = new HashSet<>();
while (numbers.size() < 4) {
int number = rnd.nextInt(99) + 1;
numbers.add(number);
}
for (Integer number : numbers) {
JButton btn = new JButton(Integer.toString(number));
add(btn);
buttons.add(btn);
}
Collections.shuffle(buttons);
JButton correct = buttons.remove(0);
correct.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
JOptionPane.showMessageDialog(TestPane.this, "Correct");
randomButtons();
}
});
ActionListener wrong = new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
if (evt.getSource() instanceof JButton) {
JButton btn = (JButton) evt.getSource();
btn.setEnabled(false);
}
JOptionPane.showMessageDialog(TestPane.this, "Wrong");
// You could keep a counter or do what ever else you
// want with a wrong guess
}
};
for (JButton btn : buttons) {
btn.addActionListener(wrong);
}
revalidate();
repaint();
}
}
}
I'm actually codding a keypad for an application and I'm encountering a problem. I'm using some empty space in the JDialog I'm creating to place an exist button on the top right corner of the Dialog box. This empty space is creating a border to the dialog box which is unpleasant to see. So I've tried to make panels transparent with setOpaque(false) function, but I achieved nothing. Do I have to use the paint function (which I don't know how to use) ?
Here is my test function without the setOpaque tests I've done :
package test;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.*;
public class Test {
public static JFrame frame;
public static void main(String args[]){
frame = new JFrame();
JPanel panel = new JPanel();
panel.setSize(400, 400);
panel.setBackground(Color.CYAN);
panel.setLayout(new GridBagLayout());
JTextField text = new JTextField("coucou");
panel.add(text);
text.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
text.setText("");
openKeypad(text);
}
});
frame.setContentPane(panel);
frame.setSize(400, 400);
frame.setUndecorated(true);
frame.setLocation(50,0);
frame.setVisible(true);
}
private static void openKeypad(JTextField text) {
KeyPad pad = new KeyPad(frame, text);
}
}
KeyPad class :
package test;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class KeyPad extends JDialog {
private JTextField field;
public KeyPad(JFrame parent, JTextField field_) {
super(parent, true);
//Initializing field
field = field_;
//Setting layout
JPanel panelButton = new JPanel();
panelButton.setLayout(new GridLayout(4, 3));
//Buttons declaration
JButton b0 = new JButton("0");
JButton b1 = new JButton("1");
JButton b2 = new JButton("2");
JButton b3 = new JButton("3");
JButton b4 = new JButton("4");
JButton b5 = new JButton("5");
JButton b6 = new JButton("6");
JButton b7 = new JButton("7");
JButton b8 = new JButton("8");
JButton b9 = new JButton("9");
JButton bp = new JButton(".");
JButton del = new JButton();
JButton close = new JButton();
//Setting buttons icons
try {
Image img = ImageIO.read(new File("ressources/closeIcon.png"));
close.setIcon(new ImageIcon(img));
img = ImageIO.read(new File("ressources/deleteIcon.png"));
del.setIcon(new ImageIcon(img));
close.setOpaque(false);
close.setBorder(new EmptyBorder(0, 0, 0, 0));
close.setContentAreaFilled(false);
}catch (Exception e) {
System.out.println(e);
}
//Buttons sizing
b0.setPreferredSize(new Dimension(64, 64));
b1.setPreferredSize(new Dimension(64, 64));
b2.setPreferredSize(new Dimension(64, 64));
b3.setPreferredSize(new Dimension(64, 64));
b4.setPreferredSize(new Dimension(64, 64));
b5.setPreferredSize(new Dimension(64, 64));
b6.setPreferredSize(new Dimension(64, 64));
b7.setPreferredSize(new Dimension(64, 64));
b8.setPreferredSize(new Dimension(64, 64));
b9.setPreferredSize(new Dimension(64, 64));
bp.setPreferredSize(new Dimension(64, 64));
del.setPreferredSize(new Dimension(64, 64));
close.setPreferredSize(new Dimension(32, 32));
//Adding buttons to the panelButton
panelButton.add(b7);
panelButton.add(b8);
panelButton.add(b9);
panelButton.add(b4);
panelButton.add(b5);
panelButton.add(b6);
panelButton.add(b1);
panelButton.add(b2);
panelButton.add(b3);
panelButton.add(bp);
panelButton.add(b0);
panelButton.add(del);
//Adding Listeners
b0.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('0');
}
});
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('1');
}
});
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('2');
}
});
b3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('3');
}
});
b4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('4');
}
});
b5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('5');
}
});
b6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('6');
}
});
b7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('7');
}
});
b8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('8');
}
});
b9.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('9');
}
});
bp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('.');
}
});
del.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
delDigit();
}
});
close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
disposeDialog();
}
});
//Placing close button
JPanel panelClose = new JPanel();
panelClose.setLayout(new BoxLayout(panelClose, BoxLayout.X_AXIS));
panelClose.add(Box.createRigidArea(new Dimension(64*3, 1)));
panelClose.add(close);
JPanel test = new JPanel();
test.setLayout(new BoxLayout(test, BoxLayout.X_AXIS));
test.add(panelButton);
test.add(Box.createRigidArea(new Dimension(32, 1)));
//Setting main panel
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(panelClose);
panel.add(test);
//Setting and displaying the Dialog Box
this.setContentPane(panel);
this.setUndecorated(true);
this.pack();
this.setVisible(true);
}
private void addDigit(char i) {
field.setText(field.getText() + i);
}
private void delDigit() {
if(field.getText().length() > 0) {
field.setText(field.getText().substring(0, field.getText().length() - 1));
}
}
private void disposeDialog() {
this.dispose();
}
}
/////EDIT///////
Here is my keypad code at the moment if someone wants to use it, feel free.
package mainPackage;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class KeyPad extends JDialog {
private GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
private GraphicsDevice[] gs = ge.getScreenDevices();
private JTextField field;
public KeyPad(JDialog parent, JTextField field_, String placement) {
super(parent, true);
//Initializing field
field = field_;
//Setting layout
JPanel panelButton = new JPanel();
panelButton.setLayout(new GridLayout(4, 3));
//Buttons declaration
JButton b0 = new JButton("0");
JButton b1 = new JButton("1");
JButton b2 = new JButton("2");
JButton b3 = new JButton("3");
JButton b4 = new JButton("4");
JButton b5 = new JButton("5");
JButton b6 = new JButton("6");
JButton b7 = new JButton("7");
JButton b8 = new JButton("8");
JButton b9 = new JButton("9");
JButton bp = new JButton(".");
JButton del = new JButton();
JButton close = new JButton();
//Setting buttons icons
try {
Image img = ImageIO.read(new File("ressources/closeIcon.png"));
close.setIcon(new ImageIcon(img));
img = ImageIO.read(new File("ressources/deleteIcon.png"));
del.setIcon(new ImageIcon(img));
close.setOpaque(false);
close.setBorder(new EmptyBorder(0, 0, 0, 0));
close.setContentAreaFilled(false);
}catch (Exception e) {
System.out.println(e);
}
//Buttons sizing
b0.setPreferredSize(new Dimension(64, 64));
b1.setPreferredSize(new Dimension(64, 64));
b2.setPreferredSize(new Dimension(64, 64));
b3.setPreferredSize(new Dimension(64, 64));
b4.setPreferredSize(new Dimension(64, 64));
b5.setPreferredSize(new Dimension(64, 64));
b6.setPreferredSize(new Dimension(64, 64));
b7.setPreferredSize(new Dimension(64, 64));
b8.setPreferredSize(new Dimension(64, 64));
b9.setPreferredSize(new Dimension(64, 64));
bp.setPreferredSize(new Dimension(64, 64));
del.setPreferredSize(new Dimension(64, 64));
close.setPreferredSize(new Dimension(32, 32));
//Adding buttons to the panelButton
panelButton.add(b7);
panelButton.add(b8);
panelButton.add(b9);
panelButton.add(b4);
panelButton.add(b5);
panelButton.add(b6);
panelButton.add(b1);
panelButton.add(b2);
panelButton.add(b3);
panelButton.add(bp);
panelButton.add(b0);
panelButton.add(del);
panelButton.setOpaque(false);
//Adding Listeners
b0.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('0');
}
});
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('1');
}
});
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('2');
}
});
b3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('3');
}
});
b4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('4');
}
});
b5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('5');
}
});
b6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('6');
}
});
b7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('7');
}
});
b8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('8');
}
});
b9.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('9');
}
});
bp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('.');
}
});
del.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
delDigit();
}
});
close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
disposeDialog();
}
});
//Placing close button
JPanel panelClose = new JPanel();
panelClose.setLayout(new BoxLayout(panelClose, BoxLayout.X_AXIS));
panelClose.add(Box.createRigidArea(new Dimension(64*3, 1)));
panelClose.add(close);
panelClose.setOpaque(false);
JPanel panelButtonWithPadding = new JPanel();
panelButtonWithPadding.setLayout(new BoxLayout(panelButtonWithPadding, BoxLayout.X_AXIS));
panelButtonWithPadding.add(panelButton);
panelButtonWithPadding.add(Box.createRigidArea(new Dimension(32, 1)));
panelButtonWithPadding.setOpaque(false);
//Setting main panel
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(panelClose);
panel.add(panelButtonWithPadding);
panel.setOpaque(false);
//Setting dialog box transparency
panelButton.setOpaque(false);
panelClose.setOpaque(false);
panelButtonWithPadding.setOpaque(false);
panel.setOpaque(false);
//Setting and displaying the Dialog Box
this.setContentPane(panel);
this.setUndecorated(true);
this.setBackground( new Color(0, 0, 0, 0) ); // set transparency on JDialog only
this.pack();
//To place the KeyPad anywhere on the panel
switch(placement) {
case "BOTTOM_LEFT":
this.setLocation(gs[Main.screen].getDefaultConfiguration().getBounds().x, 600 - (int) this.getSize().getHeight());
break;
case "BOTTOM_CENTER":
this.setLocation(gs[Main.screen].getDefaultConfiguration().getBounds().x + (int) ((800 - this.getSize().getWidth())/2) , 600 - (int) this.getSize().getHeight());
break;
case "BOTTOM_RIGHT":
this.setLocation(gs[Main.screen].getDefaultConfiguration().getBounds().x + (int) (800 - this.getSize().getWidth()), 600 - (int) this.getSize().getHeight());
break;
case "CENTER_LEFT":
this.setLocation(gs[Main.screen].getDefaultConfiguration().getBounds().x, (int) (600 - this.getSize().getHeight())/2);
break;
case "CENTER":
this.setLocation(gs[Main.screen].getDefaultConfiguration().getBounds().x + (int) ((800 - this.getSize().getWidth())/2), (int) (600 - this.getSize().getHeight())/2);
break;
case "CENTER_RIGHT":
this.setLocation(gs[Main.screen].getDefaultConfiguration().getBounds().x + (int) (800 - this.getSize().getWidth()), (int) (600 - this.getSize().getHeight())/2);
break;
case "TOP_LEFT":
this.setLocation(gs[Main.screen].getDefaultConfiguration().getBounds().x, 0);
break;
case "TOP_CENTER":
this.setLocation(gs[Main.screen].getDefaultConfiguration().getBounds().x + (int) ((800 - this.getSize().getWidth())/2), 0);
break;
case "TOP_RIGHT":
this.setLocation(gs[Main.screen].getDefaultConfiguration().getBounds().x + (int) (800 - this.getSize().getWidth()), 0);
break;
}
this.setVisible(true);
}
private void addDigit(char i) {
field.setText(field.getText() + i);
}
private void delDigit() {
if(field.getText().length() > 0) {
field.setText(field.getText().substring(0, field.getText().length() - 1));
}
}
private void disposeDialog() {
this.dispose();
}
}
Simple example for making a JFrame transparent:
import java.awt.*;
import static java.awt.GraphicsDevice.WindowTranslucency.TRANSLUCENT;
import javax.swing.*;
class TransparentFrame extends JFrame
{
public TransparentFrame()
{
JPanel panel = new JPanel();
panel.setOpaque( false );
panel.add( new JButton("Button") );
add(panel, BorderLayout.SOUTH);
setUndecorated(true);
setSize(300, 300);
//pack();
// setOpacity(0.5f); // set transparency on frame and components
setBackground( new Color(0, 0, 0, 64) ); // set transparency on frame only
setTitle("Transparent Frame Demo");
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
public static void main(String args[])
{
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
// Exit when translucent windows aren't supported
if (!gd.isWindowTranslucencySupported(TRANSLUCENT))
{
System.err.println( "Translucency is not supported" );
System.exit(0);
}
// Create the GUI on the event-dispatching thread
SwingUtilities.invokeLater(() -> new TransparentFrame().setVisible(true));
}
}
I made the Card Layout Working completely fine but what happened now is I added a keylistener to the object character which is a JLabel so whenever the person presses up the character should move up but it does absolutely nothing!
I also tried replacing it with a button which moves it when clicked and it worked completely fine. Also I tried changing the event meaning I changed that if they press up then the image of the town map would change but still no effect so it seems there is something wrong with my KeyListener
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.*;
import javax.swing.*;
#SuppressWarnings({ "unused", "serial" })
public class FinalBlowzXC extends JFrame implements KeyListener{
public static JPanel game=new JPanel();
public static JPanel mainmenu=new JPanel(null);
public static JPanel loginpanel=new JPanel(null);
public static JPanel tutorial=new JPanel(null);
public static JPanel registration=new JPanel(null);
public static JPanel town_map=new JPanel(null);
public JTextField username= new JTextField("Username");
public JTextField password=new JTextField("Password");
public JLabel bglogin=new JLabel();
public JLabel character=new JLabel();
public JButton log_in=new JButton();
public JButton register=new JButton();
CardLayout page= new CardLayout();
public String level="";
public int charx=350;
public int chary=435;
public static void main(String []args)
{
new FinalBlowzXC().setVisible(true);
}
public FinalBlowzXC()
{
super("Final Blowz Xchanged");
setSize(640,510);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
game.setLayout(page);
game.add(mainmenu, "1");
game.add(loginpanel, "2");
game.add(tutorial, "3");
game.add(registration, "4");
game.add(town_map, "5");
add(game);
opening();
}
public void opening()
{
page.show(game, "1");
JLabel bgmainmenu;
JButton start;
JButton exit;
bgmainmenu = new JLabel();
start = new JButton();
exit = new JButton();
bgmainmenu.setIcon(new ImageIcon(getClass().getResource("/FF-XV.jpg")));
bgmainmenu.setBounds(0,0,640,480);
mainmenu.add(bgmainmenu);
mainmenu.add(start);
start.setBounds(280, 360, 70, 20);
start.setBorder(null);
start.setBorderPainted(false);
start.setContentAreaFilled(false);
start.setOpaque(false);
start.addActionListener(new Start());
exit.setBounds(280, 385, 70, 20);
mainmenu.add(exit);
exit.setBorder(null);
exit.setBorderPainted(false);
exit.setContentAreaFilled(false);
exit.setOpaque(false);
exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
}
class Start implements ActionListener{
public void actionPerformed(ActionEvent e) {
login();
}
}
public void login()
{
page.show(game, "2");
bglogin.setIcon(new ImageIcon(getClass().getResource("/FF-XV Login.jpg")));
bglogin.setBounds(0, 0, 640, 480);
username.setBounds(300, 285, 85, 15);
username.setBorder(null);
username.setForeground(Color.WHITE);
username.setOpaque(false);
password.setBounds(300, 310, 85, 20);
password.setBorder(null);
password.setForeground(Color.WHITE);
password.setOpaque(false);
log_in.setBounds(280, 335, 50, 45);
log_in.setBorder(null);
log_in.setBorderPainted(false);
log_in.setContentAreaFilled(false);
log_in.setOpaque(false);
log_in.addActionListener(new Log_in());
register.setBounds(335, 335, 55, 45);
register.setBorder(null);
register.setBorderPainted(false);
register.setContentAreaFilled(false);
register.setOpaque(false);
register.addActionListener(new Register());
loginpanel.add(username);
loginpanel.add(password);
loginpanel.add(bglogin);
loginpanel.add(log_in);
loginpanel.add(register);
}
class Log_in implements ActionListener{
public void actionPerformed(ActionEvent e)
{
Tutorial();
}
}
class Register implements ActionListener{
public void actionPerformed(ActionEvent e)
{
page.show(game, "4");
}
}
public void Tutorial()
{
page.show(game, "3");
JLabel bgtutorial=new JLabel();
JLabel animeforward=new JLabel();
JLabel animeright=new JLabel();
JLabel animeleft=new JLabel();
JButton next=new JButton();
JLabel animebackward=new JLabel();
bgtutorial.setIcon(new ImageIcon(getClass().getResource("/FF-XV Tutorial.jpg")));
bgtutorial.setBounds(0, 0, 640, 480);
animeforward.setIcon(new ImageIcon(getClass().getResource("walkanimofficialfront.gif")));
animeforward.setBounds(115, 230, 30, 30);
animeright.setIcon(new ImageIcon(getClass().getResource("walkanimofficialright.gif")));
animeright.setBounds(190, 315, 30, 30);
animeleft.setIcon(new ImageIcon(getClass().getResource("walkanimofficialleft.gif")));
animeleft.setBounds(45, 315, 30, 30);
animebackward.setIcon(new ImageIcon(getClass().getResource("walkanimofficialback.gif")));
animebackward.setBounds(115, 405, 30, 30);
next.setBounds(530, 430, 100, 30);
next.setBorder(null);
next.setBorderPainted(false);
next.setContentAreaFilled(false);
next.setOpaque(false);
next.addActionListener(new Next());
tutorial.add(next);
tutorial.add(animeright);
tutorial.add(animeleft);
tutorial.add(animebackward);
tutorial.add(animeforward);
tutorial.add(bgtutorial);
}
class Next implements ActionListener{
public void actionPerformed(ActionEvent e)
{
town();
}
}
public void town()
{
page.show(game, "5");
JLabel map=new JLabel();
map.setIcon(new ImageIcon(getClass().getResource("/FF-XV Town.jpg")));
map.setBounds(0, 0, 640, 480);
character.setIcon(new ImageIcon(getClass().getResource("standfront.png")));
character.setBounds(charx, chary, 30, 35);
town_map.add(character);
town_map.add(map);
}
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_UP)
{
character.setIcon(new ImageIcon(getClass().getResource("walkanimofficialfront.gif")));
character.setLocation(character.getX(), character.getY()+5);
}
if(e.getKeyCode()==KeyEvent.VK_RIGHT)
{
character.setIcon(new ImageIcon(getClass().getResource("walkanimofficialright.gif")));
character.setLocation(character.getX()+5, character.getY());
}
if(e.getKeyCode()==KeyEvent.VK_LEFT)
{
character.setIcon(new ImageIcon(getClass().getResource("walkanimofficialleft.gif")));
character.setLocation(character.getX()-5, character.getY()+5);
}
if(e.getKeyCode()==KeyEvent.VK_DOWN)
{
character.setIcon(new ImageIcon(getClass().getResource("walkanimofficialback.gif")));
character.setLocation(character.getX(), character.getY()-5);
}
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
}
Add following code in your programme.
public static JPanel mainmenu = new JPanel();
public static JPanel loginpanel = new JPanel();
or initialize mainmenu & loginpanel before adding them into the game panel.
when you call game.add(loginPanel, "2") loginPanel is null
I have my original text field in my first frame and I need it to be displayed in my other jframe. The code is:
JButton btnContinue = new JButton("Continue");
btnContinue.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String msg = nameL.getText();
frame2 fram = new frame2 ();
fram.setVisible(true);
frame.dispose();
new order (msg) .setVisible(true);
'nameL' is the textbox the user enters their name in.
This code describe where it should be displayed:
public order(String para){
getComponents();
JLabel lblNewLabel_1 = new JLabel("");
lblNewLabel_1.setBounds(91, 27, 254, 84);
contentPane.add(lblNewLabel_1);
lblNewLabel_1.setText(para);
this is my first class where the user inputs their name
public order(String para){
getComponents();
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Font;
public class frame1 {
public JFrame frame;
public JTextField nameL;
public JTextField textField_1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame1 window = new frame1();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public frame1() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.getContentPane().setEnabled(false);
frame.setResizable(false);
frame.getContentPane().setBackground(Color.GRAY);
frame.setForeground(Color.WHITE);
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnContinue = new JButton("Continue");
btnContinue.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String msg = nameL.getText();
frame2 fram = new frame2 ();
fram.setVisible(true);
frame.dispose();
new order (msg) .setVisible(true);
}
}
);
btnContinue.setBounds(0, 249, 450, 29);
frame.getContentPane().add(btnContinue);
JTextArea txtrPleaseEnterYour = new JTextArea();
txtrPleaseEnterYour.setEditable(false);
txtrPleaseEnterYour.setBackground(Color.LIGHT_GRAY);
txtrPleaseEnterYour.setBounds(0, 0, 450, 32);
txtrPleaseEnterYour.setText("\tPlease enter your name and email below\n If you do not have or want to provide an email, Leave the space blank");
frame.getContentPane().add(txtrPleaseEnterYour);
JTextArea txtrEnterYourFull = new JTextArea();
txtrEnterYourFull.setEditable(false);
txtrEnterYourFull.setFont(new Font("Lucida Grande", Font.PLAIN, 15));
txtrEnterYourFull.setBackground(Color.GRAY);
txtrEnterYourFull.setText("Enter your full name");
txtrEnterYourFull.setBounds(52, 58, 166, 29);
frame.getContentPane().add(txtrEnterYourFull);
nameL = new JTextField();
nameL.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
}
);
nameL.setBackground(Color.LIGHT_GRAY);
nameL.setBounds(52, 93, 284, 26);
frame.getContentPane().add(nameL);
nameL.setColumns(10);
JTextArea txtroptionalEnterYour = new JTextArea();
txtroptionalEnterYour.setEditable(false);
txtroptionalEnterYour.setFont(new Font("Lucida Grande", Font.PLAIN, 15));
txtroptionalEnterYour.setBackground(Color.GRAY);
txtroptionalEnterYour.setText("(Optional) Enter your email");
txtroptionalEnterYour.setBounds(52, 139, 193, 29);
frame.getContentPane().add(txtroptionalEnterYour);
textField_1 = new JTextField();
textField_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
textField_1.setBackground(Color.LIGHT_GRAY);
textField_1.setBounds(52, 180, 284, 26);
frame.getContentPane().add(textField_1);
textField_1.setColumns(10);
}
}
my second class where the text field has to be set
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.Color;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;
public class order extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
public JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
order frame = new order();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public order() {
setAlwaysOnTop(false);
setTitle("Order Details // Finalization");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 451, 523);
contentPane = new JPanel();
contentPane.setBackground(Color.LIGHT_GRAY);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnNewButton = new JButton("Submit Order");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setAlwaysOnTop(true);
JOptionPane.showMessageDialog(null, "Your Order Has Been Confirmed", "enjoy your meal", JOptionPane.YES_NO_OPTION);
}
});
btnNewButton.setBounds(164, 466, 117, 29);
contentPane.add(btnNewButton);
}
public order(String para){
getComponents();
JLabel lblNewLabel_1 = new JLabel("");
lblNewLabel_1.setBounds(91, 27, 254, 84);
contentPane.add(lblNewLabel_1);
lblNewLabel_1.setText(para);
}
}
Open both JFrames, have them listen to the EventQueue for a custom "string display" event.
Wrap the string to be displayed in a custom event.
Throw that on the event queue, allowing both the JFrames to receive the event, which they will then display accordingly.
---- Edited with an update ----
Ok, so you're a bit new to Swing, but hopefully not too new to Java. You'll need to understand sub-classing and the "Listener" design pattern.
Events are things that Components listen for. They ask the dispatcher (the Swing dispatcher is fed by the EventQueue) to "tell them about events" and the dispatcher then sends the desired events to them.
Before you get too deep in solving your problem, it sounds like you need to get some familiarity with Swing and its event dispatch, so read up on it here.
I'm trying to create a screen to change the options of my game, so I'd a problem that using a JRadioButton works in a case and not in the other, and I didn't understand why... Does anybody know what happened?
package com.damas.screen;
import java.awt.EventQueue;
import java.awt.Font;
import javax.swing.JFrame;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
public class Options {
private JFrame frame;
protected com.damas.entidades.Options opcoes;
private JRadioButton radioPlayersNo;
private JRadioButton radioPlayersYes;
private JRadioButton radioSoundYes;
private JRadioButton radioSoundNo;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Options window = new Options();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Options() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
opcoes = new com.damas.entidades.Options();
frame = new JFrame();
frame.setBounds(100, 100, 280, 180);
frame.setResizable(Boolean.FALSE);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
radioPlayersYes =new JRadioButton("Yes");
radioPlayersNo = new JRadioButton("No");
radioSoundYes = new JRadioButton("Yes");
radioSoundNo = new JRadioButton("No");
JLabel labelSound = new JLabel("Sound");
labelSound.setBounds(50, 99, 86, 23);
radioPlayersYes.setBounds(129, 39, 55, 14);
radioPlayersNo.setBounds(190, 30, 55, 32);
/* Setting default options*/
radioSoundYes.setSelected(opcoes.getSound());
radioPlayersYes.setSelected(opcoes.getTwoPlayers());
/* Setting labels*/
JLabel lblPlayers = new JLabel("Two Players");
lblPlayers.setBounds(50, 43, 73, 14);
JLabel lblColor = new JLabel("Color");
lblColor.setBounds(50, 74, 46, 14);
JLabel lblOptions = new JLabel("Options");
lblOptions.setFont(new Font("Tw Cen MT Condensed Extra Bold", Font.PLAIN, 16));
lblOptions.setBounds(109, 11, 46, 14);
/* Setting radios*/
JRadioButton radioColorBlack = new JRadioButton("Black");
radioColorBlack.setBounds(115, 65, 77, 32);
JRadioButton radioColorWhite = new JRadioButton("White");
radioColorWhite.setBounds(194, 70, 61, 23);
JRadioButton radioSoundYes = new JRadioButton("Yes");
radioSoundYes.setBounds(120, 94, 55, 32);
JRadioButton radioSoundNo = new JRadioButton("No");
radioSoundNo.setBounds(194, 99, 61, 23);
addItemListeners();
frame.getContentPane().add(radioPlayersYes);
frame.getContentPane().add(radioPlayersNo);
frame.getContentPane().add(radioSoundYes);
frame.getContentPane().add(radioSoundNo);
frame.getContentPane().add(labelSound);
frame.getContentPane().add(lblPlayers);
frame.getContentPane().add(lblColor);
frame.getContentPane().add(radioColorBlack);
frame.getContentPane().add(radioColorWhite);
frame.getContentPane().add(lblOptions);
}
private void addItemListeners(){
radioPlayersYes.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == 1){
opcoes.setTwoPlayers(Boolean.TRUE);
radioPlayersNo.setSelected(Boolean.FALSE);
}else{
opcoes.setTwoPlayers(Boolean.FALSE);
radioPlayersNo.setSelected(Boolean.TRUE);
}
}
});
radioPlayersNo.addItemListener(new ItemListener(){
#Override
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == 1){
opcoes.setTwoPlayers(Boolean.FALSE);
System.out.println(opcoes.getTwoPlayers());
radioPlayersNo.setSelected(Boolean.TRUE);
radioPlayersYes.setSelected(Boolean.FALSE);
}else{
opcoes.setTwoPlayers(Boolean.TRUE);
System.out.println(opcoes.getTwoPlayers());
radioPlayersNo.setSelected(Boolean.FALSE);
radioPlayersYes.setSelected(Boolean.TRUE);
}
}
});
radioSoundYes.addItemListener(new ItemListener(){
#Override
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == ItemEvent.SELECTED){
radioSoundYes.setEnabled(Boolean.TRUE);
System.out.println("Radio Sound Yes: Enabled");
radioSoundNo.setEnabled(Boolean.FALSE);
}else{
radioSoundYes.setEnabled(Boolean.FALSE);
System.out.println("Radio Sound Yes: Disabled");
radioSoundNo.setEnabled(Boolean.TRUE);
}
}
});
radioSoundNo.addItemListener(new ItemListener(){
#Override
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == ItemEvent.SELECTED){
radioSoundNo.setEnabled(Boolean.TRUE);
radioSoundYes.setEnabled(Boolean.FALSE);
}else{
radioSoundNo.setEnabled(Boolean.FALSE);
radioSoundYes.setEnabled(Boolean.TRUE);
}
}
});
}
}
Group the radio buttons like
ButtonGroup playOptionsButtonGroup = new ButtonGroup();
playOptionsButtonGroup.add(radioPlayersNo);
playOptionsButtonGroup.add(radioPlayersYes);
playOptionsButtonGroup.add(radioSoundYes);
playOptionsButtonGroup.add(radioSoundNo);