I have an actionlistener on a button that is to change a boolean called flood to true when clicked, this is then used in an if statement to call a method that will change a frame. My problem is nothing is happening when the button is clicked. I am using a debug log to check for the problem but I'm stumped.
public class Stop_The_Flood extends JFrame implements ActionListener{
final Button StopTheFlood = new Button("Stop The Flood!");
boolean flood = false;
public Stop_The_Flood(char[][] array) {
setTitle("Stop The Flood!");
setSize(1024,768);
//Container panel
JPanel container = new JPanel();
container.setLayout(new GridBagLayout());
//map panel
JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(700, 900));
panel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = array[0].length;
gbc.gridheight = array.length;
gbc.fill = GridBagConstraints.BOTH;
//Button Panel
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridBagLayout());
GridBagConstraints g = new GridBagConstraints();
g.gridwidth = 1;
g.gridheight = 1;
g.gridx = 8;
g.gridy = 15;
g.fill = GridBagConstraints.BOTH;
buttonPanel.setSize(350,350);
//Add to everything to frame
getContentPane().add(container);
container.add(panel, gbc);
container.add(buttonPanel, g);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 100, 100);
StopTheFlood.setBackground(Color.cyan);
StopTheFlood.addActionListener(this);
JLabel[][] labelArray = new JLabel[array.length][array[0].length];
//Initialize JLabel array with the array that contains the data
labels(panel, labelArray, array);
buttonPanel.add(StopTheFlood);
setVisible(true);
if(flood == true) {
final Logger logger = Logger.getLogger("Stop_The_Flood");
logger.warning("found water");
}
}
public void actionPerformed(ActionEvent event) {
flood = true;
}
Nothing is being performed in your actionPerformed method, so you could try to create a new ClickListener class:
private class Clicklistener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == StopTheFlood)
{
flood = true;
}
}
}
Then on your "Stop_The_Flood" class create an object of ClickListener and add it to .addActionLister():
Clicklistener click= new Clicklistener();
StopTheFlood.addActionListener(click);
P.S don't forget to pass StopTheFlood to the ClickListener since I did not add that to the code.
Related
I am trying to build a sample application using GridLayout in Java. But I am unable to re-size my buttons. Please help me in doing it.
There are four grid layouts in the code.
I have used the setSize(width, height) function and also the setPreferredSize function. But I am not able to set the size of the buttons.
Here is the code
import java.awt.*;
import javax.swing.*;
public class Details2 {
static JButton btn1,btn2;
public static void main(String[] a) {
JFrame myFrame = new JFrame("Medical History Form");
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setSize(700,700);
Container myPane = myFrame.getContentPane();
myPane.setLayout(new GridLayout(2,1));
myPane.add(getFieldPanel());
myPane.add(getButtonPanel());
myPane.setPreferredSize(new Dimension(100,100));
myFrame.setVisible(true);
}
private static JPanel getFieldPanel() {
JPanel p = new JPanel(new GridLayout(4,2));
p.setBorder(BorderFactory.createTitledBorder("Details"));
p.add(new JLabel("Please check in the here"));
p.add(new JCheckBox("Nothing till now",false));
p.add(getPanel());
return p;
}
private static JPanel getButtonPanel() {
GridLayout g =new GridLayout(1,2);
JPanel p = new JPanel(g);
btn1 = new JButton("Submit");
btn2 = new JButton("Reset");
p.add(btn1).setPreferredSize(new Dimension(100,100));
p.add(btn2).setPreferredSize(new Dimension(100,100));
p.setPreferredSize(new Dimension(100,100));
return p;
}
private static JPanel getPanel() {
JPanel p = new JPanel(new GridLayout(5,2));
p.add(new JCheckBox("A",false));
p.add(new JCheckBox("B",false));
p.add(new JCheckBox("C",false));
p.add(new JCheckBox("D",false));
p.add(new JCheckBox("E",false));
p.add(new JCheckBox("F",false));
p.add(new JCheckBox("G",false));
p.add(new JCheckBox("E",false));
p.add(new JCheckBox("H",false));
p.add(new JCheckBox("I",false));
return p;
}
}
I believe setting GridLayout(2,2) will override size changes made to the panels. To be more precise, use GridBagConStraints; you can refer following code to understand it.
private JTextField field1 = new JTextField();
private JButton addBtn = new JButton("Save: ");
public void addComponents(Container pane) {
pane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
// Components
c.gridwidth = 1;
c.weightx = .01;
c.weighty = .2;
c.gridx = 0;
c.gridy = 1;
pane.add(field1, c);
c.gridwidth = 1;
c.weightx = .01;
c.weighty = .2;
c.gridx = 0;
c.gridy = 1;
pane.add(addBtn, c);
}
public MainView() {
//Create and set up the window.
JFrame frame = new JFrame("NAME");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Set up the content pane.
addComponents(frame.getContentPane());
//Display the window.
frame.pack();
frame.setVisible(true);
frame.setResizable(false);
frame.setSize(400, 125);
frame.setLocation(400, 300);
}
if you want to control the size of your components then don't use a layout. do something like this:
private static JPanel getButtonPanel() {
JPanel p = new JPanel();
p.setLayout(null);
btn1 = new JButton("Submit");
btn2 = new JButton("Reset");
btn1.setBounds(x, y, width, height);
btn2.setBounds(x, y, width, height);
p.add(btn1);
p.add(btn2);
return p;
I'm coding a small project for my high school class but I have run into a bit of an issue now that I'm working with frames. I'm trying to find the easiest and most efficient way to arrange the contents of a panel in java 7 (Note: this means SpringUtilities is not an option)
For the arrangement of each item I wanted it to have the option to type in your name at the top and then have 3 buttons in the same row below the name box
and the code I have so far is
private static void userInterface(){
//Declare and assign variables
final String[] options = {"Lvl 1", "Lvl 2", "Lvl 3"};
int optionsAmt = options.length;
//Create the panel used to make the user interface
JPanel panel = new JPanel(new SpringLayout());
//Create the name box
JTextField tf = new JTextField(10);
JLabel l = new JLabel("Name: ");
l.setLabelFor(tf);
panel.add(l);
panel.add(tf);
//Create 3 buttons with corresponding values of String options
for(int a = 0; a < optionsAmt; a++){
JButton b = new JButton(options[a]);
panel.add(new JLabel());
panel.add(b);
}
//Layout the panel
}
public static void main(String[] args) {
JFrame f = new JFrame();
f.pack();
f.setTitle("Number Game");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}
"Easy" is a relative term, for example, you could do something like...
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridLayout(2, 1));
JPanel fieldPane = new JPanel();
fieldPane.add(new JTextField(10));
add(fieldPane);
JPanel buttonPane = new JPanel();
buttonPane.add(new JButton("1"));
buttonPane.add(new JButton("2"));
buttonPane.add(new JButton("3"));
add(buttonPane);
}
}
or something like...
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = 3;
gbc.gridx = 0;
gbc.gridy = 0;
add(new JTextField(10), gbc);
gbc.gridwidth = 1;
gbc.gridy = 1;
add(new JButton("1"), gbc);
gbc.gridx++;
add(new JButton("2"), gbc);
gbc.gridx++;
add(new JButton("3"), gbc);
}
}
Both are easy, both do the job, but which you would use would depend greatly on what you want to achieve...
Take a look at Laying Out Components Within a Container for more details
There is a JPanel with buttons and textField. TextField filters unnecessary buttons by name. But after delete the size of rest buttons is changing.
The height of buttons must not change after filtering in the textField. How to achieve this?
public class TestViewer {
public static void main(String[] args) {EventQueue.invokeLater(new Runnable() {
public void run() {
JDialog dialog = new TestDialog();
dialog.setLocationRelativeTo(null);
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setTitle("Type text and press Enter");
dialog.setSize(300, 700);
dialog.setVisible(true);
dialog.setLocationRelativeTo(null);
dialog.setModal(true);
}
});
}
}
class TestDialog extends JDialog {
public TestDialog() {
getContentPane().add(new JPan
el(), BorderLayout.CENTER);
getContentPane().add(createBtnPanel(), BorderLayout.CENTER);
}
private JPanel createBtnPanel() {
int n = 100;
Final String ArrButtonNames[] = new String[n];
for (int h = 0; h < ArrButtonNames.length; h++) {
if ((h%2)==0){
ArrButtonNames[h]="Filter"+h;
}
else{
ArrButtonNames[h]="Button"+h;
}
}
final JButton ArrButton[] = new JButton[n];
final JPanel btnPanel = new JPanel(new GridLayout(0, ArrButtonNames.length, 1,1));
btnPanel.setLayout(new GridLayout(0, 1));
final JTextField textField = new JTextField();
textField.setColumns(23);
btnPanel.add(textField);
for (int i = 0; i < ArrButtonNames.length; i++) {
String btnString = ArrButtonNames[i];
JButton button = new JButton(btnString);
Dimension d = button.getPreferredSize();
d.setSize(d.getWidth(), d.getHeight()*1);
button.setPreferredSize(d);
button.setSize(d);
button.setMinimumSize(d);
button.setMaximumSize(d);
btnPanel.add(button);
ArrButton[i] = button;
}
textField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for(int k = 0; k < ArrButtonNames.length; k++) {
if(ArrButtonNames[k].indexOf(textField.getText())==-1) {
btnPanel.remove(ArrButton[k]);
btnPanel.revalidate();
btnPanel.repaint();
}
}
}
});
JPanel MainPanel = new JPanel();
MainPanel.setLayout(new BorderLayout());
MainPanel.add(btnPanel, BorderLayout.NORTH);
final JScrollPane scrollPane = new JScrollPane(btnPanel);
MainPanel.add(scrollPane, BorderLayout.CENTER);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
return MainPanel;
}
}
You have that effect, because you use GridLayout, which resize components to fill whole cell.
For your purposes I recommend you to use GridBagLayout, that can do what you want.
Try to use next code for filling your btnPanel instead of yours:
final JButton ArrButton[] = new JButton[n];
final JPanel btnPanel = new JPanel();
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.WEST;
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 1;
c.gridx=0;
c.gridy=0;
btnPanel.setLayout(new GridBagLayout());
final JTextField textField = new JTextField();
btnPanel.add(textField,c);
for (int i = 0; i < ArrButtonNames.length; i++) {
String btnString = ArrButtonNames[i];
JButton button = new JButton(btnString);
c.gridy ++;
btnPanel.add(button,c);
ArrButton[i] = button;
}
c.fill = GridBagConstraints.BOTH;
c.weighty = 1;
c.gridy ++;
btnPanel.add(new JLabel(""),c);
And it looks like:
ALso use pack() method instead of setSize(...), and don't use setPreferedSize(...) and others size methods read about that here.
I am trying to get familiar with CardLayout so I am making a mock game menu. This menu should have three buttons, but that layout part is easy.
So, what I want to do is start it with a menu with three buttons. The single player button should change what the user sees to a single button, which can change it back to the original menu.
I followed an example online and then applied the same methods to this. However, the menu itself is a card and it's where the command to change cards will come from, not a separate container.
Whenever I run this i get an error:
public class GameMenuCards extends JFrame{
private int currentCard = 1;
private JPanel cardPanel;
private CardLayout cl;
private GridBagConstraints gbc;
public GameMenuCards(){
initUI();
}
public void initUI(){
//set the properties for the window
setTitle("Game Menu With Cards");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setExtendedState(MAXIMIZED_BOTH);
cardPanel = new JPanel();
cl = new CardLayout();
JPanel game = new JPanel();
game.setBackground(Color.BLACK);
//the menu panel
JPanel menu = new JPanel();
menu.setLayout(new GridBagLayout());
menu.setBackground(Color.BLACK);
cardPanel.add(menu, "1");
cardPanel.add(game, "2");
//set up the buttons for the menu
JButton single = new JButton("Single Player");
single.setPreferredSize(new Dimension(300, 30));
single.setBackground(Color.GRAY);
single.setForeground(Color.CYAN);
single.setBorder(BorderFactory.createLineBorder(Color.CYAN, 3));
JButton multi = new JButton("Multi Player");
multi.setPreferredSize(new Dimension(300, 30));
multi.setBackground(Color.GRAY);
multi.setForeground(Color.CYAN);
multi.setBorder(BorderFactory.createLineBorder(Color.CYAN, 3));
JButton score = new JButton("High Scores");
score.setPreferredSize(new Dimension(300, 30));
score.setBackground(Color.GRAY);
score.setForeground(Color.CYAN);
score.setBorder(BorderFactory.createLineBorder(Color.CYAN, 3));
gbc = new GridBagContraints();
//add everything to the menu
gbc.insets = new Insets(35, 50, 0, 50);
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.gridx = 1;
gbc.gridy = 1;
menu.add(single, gbc);
gbc.gridx = 1;
gbc.gridy = 2;
label(menu);
gbc.gridx = 1;
gbc.gridy = 3;
menu.add(multi, gbc);
gbc.gridx = 1;
gbc.gridy = 4;
label(menu);
gbc.gridx = 1;
gbc.gridy = 5;
gbc.insets = new Insets(35, 50, 35, 50);
menu.add(score, gbc);
single.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
currentCard = 2;
cl.show(cardPanel, "" + (currentCard));
}
});
JButton returnBut = new JButton("Back To Menu");
returnBut.setPreferredSize(new Dimension(300, 30));
returnBut.setBackground(Color.GRAY);
returnBut.setForeground(Color.CYAN);
returnBut.setBorder(BorderFactory.createLineBorder(Color.CYAN, 3));
returnBut.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
currentCard = 1;
cl.show(cardPanel, "" + (currentCard));
}
});
game.add(returnBut);
getContentPane().add(cardPanel);
}
public void label(Container c){
JLabel j1 = new JLabel();
j1.setPreferredSize(new Dimension(300, 40));
j1.setBackground(Color.BLACK);
c.add(j1, gbc);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run(){
GameMenuCards gm = new GameMenuCards();
gm.setVisible(true);
}
});
}
}
I know that i could have done a similar thing with the buttons to the labels but i only had the thought two buttons in, so at that stage it would have taken longer.
Am I going about this the right way? Can you correct any mistakes I've made in the code?
Whenever I run this i get an error
Your application is throwing an NPE here
gbc.insets = new Insets(35, 50, 0, 50);
as you haven't initialized your GridBagConstraints gbc.
Also, the reason that you see both panels side-by-side is that, even though you created a CardLayout, you neglect to use it for your cardPanel. Therefore you are still using the default FlowLayout of the JPanel. You could do:
cardPanel = new JPanel(cl);
Why are the JLabel, JTextField and JButton components on the FieldBox panel not displaying?
Please let me know if I can add anything to this question to make it more answerable!
The field box (one of which is created for each of several instance fields):
public class FieldBox extends javax.swing.JPanel {
JLabel label;
JTextField textField;
public FieldBox() {
setBackground(Color.RED);
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
label = new JLabel();
gbc.gridx = 0;
gbc.gridy = 0;
add(label,gbc);
textField = new JTextField();
gbc.gridx = 1;
gbc.gridy = 0;
add(textField, gbc);
JButton editBtn = new JButton("edit");
gbc.gridx = 2;
gbc.gridy = 0;
add(editBtn, gbc);
JButton saveBtn = new JButton ("save");
gbc.gridx = 3;
gbc.gridy = 0;
add(saveBtn, gbc);
label.setVisible(true);
label.setBackground(Color.yellow);
setVisible(true);
initComponents();
}
The panel onto which the boxes are added: (the panel appears. I know this panel loads because I can see its background. I can also see the "tit" JLabel, which I'm using for testing. Also, when I load the boxes onto it using a gridLayout (as shown below), I see the background of one of the boxes, but none of its contents are displayed, and also there should be three boxes shown but I only see one. Using a GridBagLayout
public class ShowBook extends javax.swing.JPanel {
public ShowBook(Book b) {
setLayout(new GridLayout(1,6));
setBackground(Color.GREEN);
String[] fieldTitles = {"title", "catalog", "publisher" };
JLabel tit = new JLabel("tit");
add(tit);
for (String s : fieldTitles){
FieldBox fb = new FieldBox();
fb.label.setText(s + ": ");
fb.textField.setText(getField(b, s));
System.out.println("in text field" + fb.textField.getText());
fb.revalidate();
fb.setVisible(true);
add (fb);
}
revalidate();
setVisible(true);
}
The panel onto which the ShowBook panel (above) is added. This panel also contains a listbox, which lists books in the collection, and a button to launch a ShowBook panel with the selected book as parameter.
public class ShowLib extends javax.swing.JPanel {
/**
* Creates new form ShowLib
*/
public ShowLib(Library l) {
setLayout(new BorderLayout()) ;
setBackground(Color.WHITE);
JPanel listPanel = new JPanel();
listPanel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
final JList bookList = new JList();
bookList.setVisible(true);
bookList.setPreferredSize(new Dimension(150, 600));
bookList.setBackground(Color.yellow);
DefaultListModel dlm = new DefaultListModel();
for (Book b : l.libList){
dlm.addElement(b);
}
bookList.setModel(dlm);
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = gbc.BOTH;
listPanel.add(bookList, gbc);
JButton showBtn = new JButton("show");
gbc.gridy = gbc.RELATIVE;
listPanel.add(showBtn, gbc);
showBtn.addActionListener(new ActionListener () {
#Override
public void actionPerformed(ActionEvent e){
Book b = (Book) bookList.getSelectedValue();
ShowBook db = new ShowBook (b);
System.out.println("Clicked");
add (db, BorderLayout.CENTER);
revalidate();
}
});
revalidate();
setVisible(true);
add(listPanel, BorderLayout.WEST);
}
Where the ShowLib panel is added to the main JFrame. I know this works because that panel displays properly
void showLib() {
ShowLib sl = new ShowLib(l);
sl.setVisible(true);
setContentPane(sl);
revalidate();
// this.revalidate();
// this.pack();
System.out.println("showlibClicked");
}
The problem was the line initComponents(); at the bottom of the FieldBox class.
Lesson learned: If you're not using NetBeans visual GUI editor, GET RID OF THIS LINE!