Swing - positioning some JButtons - java

I'm trying to make a little game with JButton objects. My problem is, when I add buttons to my panel, they don't position where I need them. To be more clear.
This is the Image I have :
Here's my code :
My main class which extends JFrame adds a new Board1 which extends JPanel
public class Main2 extends JFrame {
public Main2() {
setVisible(true);
setSize(500, 500);
add(new Board1());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setTitle("Zombicide");
setResizable(false);
}
public static void main(String[] args) {
new Main2();
}
}
My Board class which extends JPanel and adds some Zone objects which extend JButton.
public class Board1 extends JPanel implements Board {
private List<Zone> zones = new ArrayList<Zone>();
public Board1() {
zones.add(new Zone(1, false, true, null, "/zone1D1C.jpg", 0, 0, this));
zones.add(new Zone(2, false, false, null, "/zone2D1C.jpg", 150, 0, this));
zones.add(new Zone(3, false, false, null, "/zone3D1C.jpg", 300, 0, this));
zones.add(new Zone(4, true, false, null, "/zone4D1C.jpg", 0, 150, this));
zones.add(new Zone(5, false, false, null, "/zone5D1C.jpg", 300, 150, this));
zones.add(new Zone(6, true, false, null, "/zone6D1C.jpg", 0, 300, this));
zones.add(new Zone(7, true, false, null, "/zone7D1C.jpg", 150, 300, this));
zones.add(new Zone(8, false, false, null, "/zone8D1C.jpg", 300, 300, this));
}
}
And finally my zone class which extends JButton
public class Zone extends JButton implements ActionListener {
private final Zone zone;
private final Board board;
private Integer id;
private boolean piece;
private boolean egout;
private Integer x;
private Integer y;
private Integer x_end;
private Integer y_end;
public Zone(Integer id, boolean piece, boolean egout, Dalle[] dalles, List<Connexion> connexions, String image_name, Integer x, Integer y, Board board) {
zone = this;
addMouseListener(new TAdapter());
this.board = board;
this.piece = piece;
this.egout = egout;
this.id = id;
this.setLayout(null);
this.setBorder(null);
this.setText(null);
ImageIcon ii = new ImageIcon(this.getClass().getResource(image_name));
this.setIcon(ii);
this.x = x;
this.y = y;
this.setBounds(x, y, ii.getIconWidth(), ii.getIconHeight());
this.x_end = x + ii.getIconWidth();
this.y_end = y + ii.getIconHeight();
this.setSize(ii.getIconWidth(), ii.getIconHeight());
}
private class TAdapter extends MouseAdapter {
#Override
public void mouseClicked(MouseEvent e) {
if (gotoZone()) {
...
} else {
System.out.println("error");
}
}
}
}

The GridBagLayout is the best suitable layout for what you try to achieve. It could be something like this :
public class Board1 extends JPanel implements Board {
public Board1() {
super();
this.setLayout(new GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridx = 0;
constraints.gridy = 0;
this.add(new Zone(...), constraints);
constraints.gridx = 1;
constraints.gridy = 0;
this.add(new Zone(...), constraints);
// You caught the point I think
}
}
You have a good tutorial made by Oracle here.

import java.awt.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.net.URL;
public class ZombiecideLayout {
private JComponent ui = null;
ZombiecideLayout() {
initUI();
}
public void initUI() {
if (ui != null) {
return;
}
ui = new JPanel(new GridBagLayout());
ui.setBorder(new EmptyBorder(4, 4, 4, 4));
try {
URL dayAddress = new URL("http://i.stack.imgur.com/OVOg3.jpg");
URL nightAddress = new URL("http://i.stack.imgur.com/lxthA.jpg");
BufferedImage biDay = ImageIO.read(
dayAddress).getSubimage(180, 0, 300, 300);
BufferedImage biNight = ImageIO.read(
nightAddress).getSubimage(180, 0, 300, 300);
GridBagConstraints gbc = new GridBagConstraints();
Insets pad = new Insets(0,0,0,0);
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = pad;
gbc.gridwidth = 1;
gbc.gridheight = 1;
JButton b1 = new JButton();
b1.setContentAreaFilled(false);
b1.setBorder(null);
b1.setMargin(pad);
b1.setIcon(new ImageIcon(biDay.getSubimage(0, 0, 100, 100)));
b1.setRolloverIcon(new ImageIcon(biNight.getSubimage(0, 0, 100, 100)));
ui.add(b1, gbc);
gbc.gridx = 1;
JButton b2 = new JButton();
b2.setContentAreaFilled(false);
b2.setBorder(null);
b2.setMargin(pad);
b2.setIcon(new ImageIcon(biDay.getSubimage(100, 0, 100, 100)));
b2.setRolloverIcon(new ImageIcon(biNight.getSubimage(100, 0, 100, 100)));
ui.add(b2, gbc);
gbc.gridx = 2;
JButton b3 = new JButton();
b3.setContentAreaFilled(false);
b3.setBorder(null);
b3.setMargin(pad);
b3.setIcon(new ImageIcon(biDay.getSubimage(200, 0, 100, 100)));
b3.setRolloverIcon(new ImageIcon(biNight.getSubimage(200, 0, 100, 100)));
ui.add(b3, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridwidth = 2;
JButton b4 = new JButton();
b4.setContentAreaFilled(false);
b4.setBorder(null);
b4.setMargin(pad);
b4.setIcon(new ImageIcon(biDay.getSubimage(0, 100, 200, 100)));
b4.setRolloverIcon(new ImageIcon(biNight.getSubimage(0, 100, 200, 100)));
ui.add(b4, gbc);
gbc.gridx = 2;
gbc.gridy = 1;
gbc.gridwidth = 1;
JButton b5 = new JButton();
b5.setContentAreaFilled(false);
b5.setBorder(null);
b5.setMargin(pad);
b5.setIcon(new ImageIcon(biDay.getSubimage(200, 100, 100, 100)));
b5.setRolloverIcon(new ImageIcon(biNight.getSubimage(200, 100, 100, 100)));
ui.add(b5, gbc);
gbc.gridx = 0;
gbc.gridy = 2;
JButton b6 = new JButton();
b6.setContentAreaFilled(false);
b6.setBorder(null);
b6.setMargin(pad);
b6.setIcon(new ImageIcon(biDay.getSubimage(0, 200, 100, 100)));
b6.setRolloverIcon(new ImageIcon(biNight.getSubimage(0, 200, 100, 100)));
ui.add(b6, gbc);
gbc.gridx = 1;
JButton b7 = new JButton();
b7.setContentAreaFilled(false);
b7.setBorder(null);
b7.setMargin(pad);
b7.setIcon(new ImageIcon(biDay.getSubimage(100, 200, 100, 100)));
b7.setRolloverIcon(new ImageIcon(biNight.getSubimage(100, 200, 100, 100)));
ui.add(b7, gbc);
gbc.gridx = 2;
JButton b8 = new JButton();
b8.setContentAreaFilled(false);
b8.setBorder(null);
b8.setMargin(pad);
b8.setIcon(new ImageIcon(biDay.getSubimage(200, 200, 100, 100)));
b8.setRolloverIcon(new ImageIcon(biNight.getSubimage(200, 200, 100, 100)));
ui.add(b8, gbc);
} catch (Exception ex) {
ex.printStackTrace();
}
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
ZombiecideLayout o = new ZombiecideLayout();
JFrame f = new JFrame("Zombiecide Layout");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}

Related

Buttons within buttons in java GUI

I want to create buttons within buttons in java gui, so I have a bunch of buttons and within those buttons there's more buttons but whenever I try to make a for-loop for those buttons nothing happens. Here is my code
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.ImageIcon;
import java.net.URL;
import java.awt.Dimension;
import javax.swing.JOptionPane;
import java.awt.*;
import javax.swing.ImageIcon;
import java.awt.Dimension;
public class Elements extends JPanel implements ActionListener {
JButton c_one[] = new JButton[4];
JButton c_two[] = new JButton[4];
JButton c_three[] = new JButton[4];
JButton c_four[] = new JButton[4];
JButton THINGY [] = new JButton[1];
// buttons for column one row 0
JButton btn1 = new JButton("Nicosia");
JButton btn2 = new JButton("Mumbai");
JButton btn3 = new JButton("Dubait");
JButton btn4 = new JButton("Romania");
// buttons for column one row 1
JButton btna = new JButton("semihemidemisemiquaver ");
JButton btnb = new JButton("semidemiquaver");
JButton btnc = new JButton("qaver");
JButton btnd = new JButton("stop note");
// button column one row 2
JButton btne = new JButton("23 ");
JButton btnf = new JButton("27");
JButton btng = new JButton("72");
JButton btnh = new JButton("4");
// button colooum one row 3
JButton btnE = new JButton("Pinky");
JButton btnF = new JButton("Cotten Candy");
JButton btnG = new JButton("Lady");
JButton btnH = new JButton(" The Other Tide.");
// button column two row 0
JButton btn10 = new JButton("\tEverything about you");
JButton btn20 = new JButton("All about the thing in the janitors closet");
JButton btn30 = new JButton("If Dubait is real or not");
JButton btn40 = new JButton("12");
// button column two row 1
JButton btn00 = new JButton("$63,645, ");
JButton btn01 = new JButton("$120 000");
JButton btn02 = new JButton("$15");
JButton btn03 = new JButton("$64 200");
// button column two row 2
JButton btn04 = new JButton("True ");
JButton btn05 = new JButton("False");
// button column two row 3
JButton btnaa = new JButton("\tMr. Penny");
JButton btnbb = new JButton("Mr. Dime");
JButton btncc = new JButton("Mr. Nickel");
JButton btndd = new JButton("Mr.Dollar");
// button column three row 1
JButton btn06 = new JButton("\tDr. Harold Shipman");
JButton btn07 = new JButton("Jesse James.");
JButton btn08 = new JButton("Pablo Escobar");
JButton btn09 = new JButton("Al Capone");
// button column three row 2
JButton btnaaa = new JButton("\tTrue");
JButton btnbbb = new JButton("False");
JButton btnddd = new JButton("Only in the bladder");
// button column three row 3
JButton btnEE = new JButton("20% ");
JButton btnFF = new JButton("6 to 9%,");
JButton btnGG = new JButton("11-17%");
JButton btnHH = new JButton("34%");
// button column three row 4
JButton question11 = new JButton("Does stretching delay muscle soreness");
JButton btn12 = new JButton("Stretching before or after exercise does NOT reduce muscle soreness ");
JButton btn13 = new JButton("Stretching before or after exercise DOES reduce soreness");
// JPanel.setBackground(Color.YELLOW);
int PE = 0;
GridBagConstraints constraints = new GridBagConstraints(); // this variable will set the coordinates of each button
String icon[] = { "ont.jpg", "oet.jpg", "cm.jpg","riddles.jpg","stw.jpg" };
public Elements() {
setLayout(new GridBagLayout());
constraints.insets = new Insets(5, 5, 5, 5); // borders
for (int k = 0; k < (c_one.length); k++) {
c_one[k] = new JButton();
constraints.gridx = 0;
++constraints.gridy;
c_one[k].setIcon(
new ImageIcon(new ImageIcon(icon[0]).getImage().getScaledInstance(150, 100, java.awt.Image.SCALE_SMOOTH)));
add(c_one[k], constraints);
c_one[k].addActionListener(this);
}
constraints.gridy = -1; // setting the gridy to be negative one so the loop will iterate starting at
// gridy = 0
for (int j = 0; j < (c_two.length); j++) {
c_two[j] = new JButton();
constraints.gridx = 1;
++constraints.gridy;
c_two[j].setIcon(
new ImageIcon(new ImageIcon(icon[1]).getImage().getScaledInstance(150, 100, java.awt.Image.SCALE_SMOOTH)));
add(c_two[j], constraints);
c_two[j].addActionListener(this);
}
// gridy = 0;
constraints.gridy = -1;
for (int m = 0; m < (c_three.length); m++) {
c_three[m] = new JButton();
constraints.gridx = 2;
++constraints.gridy;
c_three[m].setIcon(
new ImageIcon(new ImageIcon(icon[2]).getImage().getScaledInstance(150, 100, java.awt.Image.SCALE_SMOOTH)));
add(c_three[m], constraints);
c_three[m].addActionListener(this);
}
constraints.gridy = -1; // setting the gridy to be negative one so the loop will iterate starting at
// gridy = 0
for (int j = 0; j < (c_four.length); j++) {
c_four[j] = new JButton();
constraints.gridx = 3;
++constraints.gridy;
c_four[j].setIcon(
new ImageIcon(new ImageIcon(icon[3]).getImage().getScaledInstance(150, 100, java.awt.Image.SCALE_SMOOTH)));
add(c_four[j], constraints);
c_four[j].addActionListener(this);
}
constraints.gridy = -1; // setting the gridy to be negative one so the loop will iterate starting at
// gridy = 0
for (int j = 0; j < (THINGY.length); j++) {
THINGY[j] = new JButton();
constraints.gridx = 6;
++constraints.gridy;
THINGY[j].setIcon(
new ImageIcon(new ImageIcon(icon[4]).getImage().getScaledInstance(150, 100, java.awt.Image.SCALE_SMOOTH)));
add(THINGY[j], constraints);
THINGY[j].addActionListener(this);
}
JButton pointsEarned = new JButton("Points Earned");
constraints.fill = GridBagConstraints.VERTICAL;
constraints.ipady = 20;
constraints.gridx = 3;
constraints.gridy = 0;
constraints.anchor = GridBagConstraints.PAGE_START;
add(pointsEarned, constraints);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == c_one[0]) {
System.out.println(" For 200 points. What is the capital of Cyprus?");
JFrame frame = new JFrame("200");
JPanel panel = new JPanel();
panel.setBounds(55, 55, 400, 200);
panel.setBackground(Color.BLUE);
JButton question1 = new JButton("For 200 points. What is the capital of Cyprus?");
question1.setBounds(50, 100, 160, 80);
question1.setBackground(Color.ORANGE);
panel.add(question1);
btn2.setBounds(50, 100, 80, 30);
btn2.setBackground(Color.ORANGE);
btn1.setBounds(50, 100, 80, 30);
btn1.setBackground(Color.ORANGE);
panel.add(btn1);
panel.add(btn2);
btn3.setBounds(50, 100, 80, 30);
btn3.setBackground(Color.ORANGE);
panel.add(btn3);
btn4.setBounds(50, 100, 80, 30);
btn4.setBackground(Color.ORANGE);
panel.add(btn4);
frame.add(panel);
frame.setSize(535, 250);
frame.setLayout(null);
frame.setVisible(true);
} else if (e.getSource() == c_one[1]) {
System.out
.println("For 400 points. What is a note that is played for half the duration of a thirty second note?");
JFrame frame2 = new JFrame("400");
JPanel panel = new JPanel();
panel.setBounds(55, 55, 400, 200);
panel.setBackground(Color.BLUE);
JButton question2 = new JButton("In music, a hundred twenty-eighth note is known as?");
question2.setBounds(50, 100, 160, 80);
question2.setBackground(Color.ORANGE);
panel.add(question2);
btna.setBounds(50, 100, 80, 30);
btna.setBackground(Color.ORANGE);
btnb.setBounds(50, 100, 80, 30);
btnb.setBackground(Color.ORANGE);
panel.add(btna);
panel.add(btnb);
btnc.setBounds(50, 100, 80, 30);
btnc.setBackground(Color.ORANGE);
panel.add(btnc);
btnd.setBounds(50, 100, 80, 30);
btnd.setBackground(Color.ORANGE);
panel.add(btnd);
frame2.add(panel);
frame2.setSize(535, 250);
frame2.setLayout(null);
frame2.setVisible(true);
}
if (e.getSource() == c_one[2]) {
JFrame frame3 = new JFrame("600");
JPanel panel = new JPanel();
panel.setBounds(55, 55, 400, 200);
panel.setBackground(Color.BLUE);
JButton question3 = new JButton("How many times was Caesar stabbed by his senators?");
question3.setBounds(50, 100, 160, 80);
question3.setBackground(Color.ORANGE);
panel.add(question3);
btne.setBounds(50, 100, 80, 30);
btne.setBackground(Color.ORANGE);
btnf.setBounds(50, 100, 80, 30);
btnf.setBackground(Color.ORANGE);
panel.add(btne);
panel.add(btnf);
btng.setBounds(50, 100, 80, 30);
btng.setBackground(Color.ORANGE);
panel.add(btng);
btnh.setBounds(50, 100, 80, 30);
btnh.setBackground(Color.ORANGE);
panel.add(btnh);
frame3.add(panel);
frame3.setSize(535, 250);
frame3.setLayout(null);
frame3.setVisible(true);
} else if (e.getSource() == c_one[3]) {
JFrame frame4 = new JFrame("800");
JPanel panel = new JPanel();
panel.setBounds(55, 55, 400, 200);
panel.setBackground(Color.BLUE);
JButton question4 = new JButton("Louisiana is home to a rare pink dolphin named:");
question4.setBounds(50, 100, 160, 100);
question4.setBackground(Color.ORANGE);
panel.add(question4);
btnE.setBounds(50, 100, 80, 30);
btnE.setBackground(Color.ORANGE);
btnF.setBounds(50, 100, 80, 30);
btnF.setBackground(Color.ORANGE);
panel.add(btnE);
panel.add(btnF);
btnG.setBounds(50, 100, 80, 30);
btnG.setBackground(Color.ORANGE);
panel.add(btnG);
btnH.setBounds(50, 100, 80, 30);
btnH.setBackground(Color.ORANGE);
panel.add(btnH);
frame4.add(panel);
frame4.setSize(535, 250);
frame4.setLayout(null);
frame4.setVisible(true);
}
// array 2
if (e.getSource() == c_two[0]) {
JFrame frame = new JFrame("200");
JPanel panel = new JPanel();
panel.setBounds(55, 55, 400, 200);
panel.setBackground(Color.BLUE);
JButton question1 = new JButton("What do teachers know?");
question1.setBounds(50, 100, 160, 80);
question1.setBackground(Color.ORANGE);
panel.add(question1);
btn10.setBounds(50, 100, 80, 30);
btn10.setBackground(Color.ORANGE);
btn20.setBounds(50, 100, 80, 30);
btn20.setBackground(Color.ORANGE);
panel.add(btn10);
panel.add(btn20);
btn30.setBounds(50, 100, 80, 30);
btn30.setBackground(Color.ORANGE);
panel.add(btn30);
btn40.setBounds(50, 100, 80, 30);
btn40.setBackground(Color.ORANGE);
panel.add(btn40);
frame.add(panel);
frame.setSize(535, 250);
frame.setLayout(null);
frame.setVisible(true);
} else if (e.getSource() == c_two[1]) {
System.out.println("Who is my physics teacher");
JFrame frame2 = new JFrame("400");
JPanel panel = new JPanel();
panel.setBounds(55, 55, 400, 200);
panel.setBackground(Color.BLUE);
JButton question2 = new JButton("Who is my physics teacher?");
question2.setBounds(50, 100, 160, 80);
question2.setBackground(Color.ORANGE);
panel.add(question2);
btnaa.setBounds(50, 100, 80, 30);
btnaa.setBackground(Color.ORANGE);
btnbb.setBounds(50, 100, 80, 30);
btnbb.setBackground(Color.ORANGE);
panel.add(btnaa);
panel.add(btnbb);
btncc.setBounds(50, 100, 80, 30);
btncc.setBackground(Color.ORANGE);
panel.add(btncc);
btndd.setBounds(50, 100, 80, 30);
btndd.setBackground(Color.ORANGE);
panel.add(btndd);
frame2.add(panel);
frame2.setSize(535, 250);
frame2.setLayout(null);
frame2.setVisible(true);
}
if (e.getSource() == c_two[2]) {
JFrame frame4 = new JFrame("600");
JPanel panel = new JPanel();
panel.setBounds(55, 55, 400, 200);
panel.setBackground(Color.BLUE);
JButton question4 = new JButton("How much do teachers get payed on average");
question4.setBounds(50, 100, 160, 100);
question4.setBackground(Color.ORANGE);
panel.add(question4);
btn00.setBounds(50, 100, 80, 30);
btn00.setBackground(Color.ORANGE);
btn01.setBounds(50, 100, 80, 30);
btn01.setBackground(Color.ORANGE);
panel.add(btn00);
panel.add(btn01);
btn02.setBounds(50, 100, 80, 30);
btn02.setBackground(Color.ORANGE);
panel.add(btn02);
btn03.setBounds(50, 100, 80, 30);
btn03.setBackground(Color.ORANGE);
panel.add(btn03);
frame4.add(panel);
frame4.setSize(535, 250);
frame4.setLayout(null);
frame4.setVisible(true);
} else if (e.getSource() == c_two[3]) {
JFrame frame3 = new JFrame("800");
JPanel panel = new JPanel();
panel.setBounds(55, 55, 600, 800);
panel.setBackground(Color.BLUE);
JButton question3 = new JButton("For every 10 Canadian teachers, at least 4 have endured violence from students");
question3.setBounds(50, 100, 160, 180);
question3.setBackground(Color.ORANGE);
panel.add(question3);
btn04.setBounds(50, 100, 80, 30);
btn04.setBackground(Color.ORANGE);
btn05.setBounds(50, 100, 80, 30);
btn05.setBackground(Color.ORANGE);
panel.add(btn04);
panel.add(btn05);
frame3.add(panel);
frame3.setSize(800, 500);
frame3.setLayout(null);
frame3.setVisible(true);
}
// array 3
if (e.getSource() == c_three[0]) {
JFrame frame = new JFrame("200");
JPanel panel = new JPanel();
panel.setBounds(55, 55, 400, 200);
panel.setBackground(Color.BLUE);
JButton question1 = new JButton("The most prolific modern serial killer is:");
question1.setBounds(50, 100, 160, 80);
question1.setBackground(Color.ORANGE);
panel.add(question1);
btn06.setBounds(50, 100, 80, 30);
btn06.setBackground(Color.ORANGE);
btn07.setBounds(50, 100, 80, 30);
btn07.setBackground(Color.ORANGE);
panel.add(btn06);
panel.add(btn07);
btn08.setBounds(50, 100, 80, 30);
btn08.setBackground(Color.ORANGE);
panel.add(btn08);
btn09.setBounds(50, 100, 80, 30);
btn09.setBackground(Color.ORANGE);
panel.add(btn09);
frame.add(panel);
frame.setSize(535, 250);
frame.setLayout(null);
frame.setVisible(true);
} else if (e.getSource() == c_three[1]) {
JFrame frame2 = new JFrame("400");
JPanel panel = new JPanel();
panel.setBounds(55, 55, 400, 200);
panel.setBackground(Color.BLUE);
JButton question2 = new JButton("Urine is sterile\t");
question2.setBounds(50, 100, 160, 80);
question2.setBackground(Color.ORANGE);
panel.add(question2);
btnaaa.setBounds(50, 100, 80, 30);
btnaaa.setBackground(Color.ORANGE);
btnbbb.setBounds(50, 100, 80, 30);
btnbbb.setBackground(Color.ORANGE);
panel.add(btnaaa);
panel.add(btnbbb);
btnddd.setBounds(50, 100, 80, 30);
btnddd.setBackground(Color.ORANGE);
panel.add(btnddd);
frame2.add(panel);
frame2.setSize(535, 250);
frame2.setLayout(null);
frame2.setVisible(true);
}
if (e.getSource() == c_three[2]) {
JFrame frame4 = new JFrame("600");
JPanel panel = new JPanel();
panel.setBounds(55, 55, 400, 200);
panel.setBackground(Color.BLUE);
JButton question4 = new JButton("The Amazon rainforest provides ___% of Earth's oxygen. ");
question4.setBounds(50, 100, 160, 100);
question4.setBackground(Color.ORANGE);
panel.add(question4);
btnEE.setBounds(50, 100, 80, 30);
btnEE.setBackground(Color.ORANGE);
btnFF.setBounds(50, 100, 80, 30);
btnFF.setBackground(Color.ORANGE);
panel.add(btnEE);
panel.add(btnFF);
btnGG.setBounds(50, 100, 80, 30);
btnGG.setBackground(Color.ORANGE);
panel.add(btnGG);
btnHH.setBounds(50, 100, 80, 30);
btnHH.setBackground(Color.ORANGE);
panel.add(btnHH);
frame4.add(panel);
frame4.setSize(535, 250);
frame4.setLayout(null);
frame4.setVisible(true);
} else if (e.getSource() == c_three[3]) {
JFrame frame3 = new JFrame("800");
JPanel panel = new JPanel();
panel.setBounds(55, 55, 600, 800);
panel.setBackground(Color.BLUE);
question11.setBounds(50, 100, 160, 180);
question11.setBackground(Color.ORANGE);
panel.add(question11);
btn12.setBounds(50, 100, 80, 30);
btn12.setBackground(Color.ORANGE);
btn13.setBounds(50, 100, 80, 30);
btn13.setBackground(Color.ORANGE);
panel.add(btn12);
panel.add(btn13);
frame3.add(panel);
frame3.setSize(800, 300);
frame3.setLayout(null);
frame3.setVisible(true);
}
}
}
Here is a screenshot of my code:
And a picture of the buttons
I want it to say your correct or something after a button is clicked so for example in the second screenshot there's a button labelled Nicosia its btn1 so I want btn 1 to do thatthat, I tried an if else but it didn't work; I did if(e.getSource()==btn1){System.out.println("correct")}
So, having spent way more time with your code then I might have liked to, the basic answer to your question is - use a ActionListener, check which button was pressed and validate the answer to the question.
About here you should be screaming at me "YES, BUT HOW!?", which is where your actual question begins.
The problem is, you've coupled the data (question/options/answers) to the UI in such away that it's simply not easy to for you do to. Instead, you need to decouple the data (question/options/answer) from the UI, so that the UI becomes much more dumb (and re-usable) and relies on the model/data to tell it what it needs to know.
The follow answer makes use of:
Dependency injection
Observer pattern
Single responsibility principle
Information hiding (AKA encapsulation)
software engineering principles. It aims to decouple the "model" (actually models) from the UI in such away that you actually only ever need 3 panels to present ALL the data (the question panel gets dynamically re-used)
Let's start with some basic data...
public interface Question {
public int getPoints();
public String getPrompt();
public String[] getOptions();
public boolean isCorrect(String answer);
}
public interface Quiz {
public int getScore();
public String[] getCatagories();
public Question[] getQuestionsForCatagory(String category);
public boolean didAnswerQuestion(Question question, String answer);
}
(nb: It's possible to "hide" the isCorrect method in the Question through a second interface or implementation, but I figured by the time I get to the end of this, you're head would already be spinning)
Ok, so these define the basic, contractual, requirements we need to be able to build a "quiz"
It should be noted that it could be possible to add an observer to the Quiz which could generate notifications when the score changes, but I'm going to leave that to you 😉
The intention of using interface like this is to the hide the implementation detail. This means we could source the quiz information from a file (like a XML and/or JSON) or from a database or even some kind of cloud service.
Speaking of implementations, let's start with something simple
public class DefaultQuiz implements Quiz {
private Map<String, List<Question>> questions = new HashMap<>();
private int score;
public void add(String category, Question[] questions) {
this.questions.put(category, Arrays.asList(questions));
}
#Override
public boolean didAnswerQuestion(Question question, String answer) {
if (question.isCorrect(answer)) {
score += question.getPoints();
return true;
}
return false;
}
#Override
public int getScore() {
return score;
}
#Override
public String[] getCatagories() {
Set<String> keys = questions.keySet();
return keys.toArray(new String[keys.size()]);
}
#Override
public Question[] getQuestionsForCatagory(String category) {
List<Question> values = questions.get(category);
return values.toArray(new Question[values.size()]);
}
public static Quiz build() {
DefaultQuiz quiz = new DefaultQuiz();
quiz.add("Oddly Niche Topics", new Question[]{
new DefaultQuestion(200, "What is the capital of Cyprus?", new String[]{"Nicosia", "Mumbai", "Dubait", "Romania"}, 0),
new DefaultQuestion(400, "What is a note that is played for half the duration of a thirty second note?", new String[]{"demisemiquaver", "semidemiquaver", "qaver", "stop note"}, 0),
new DefaultQuestion(600, "How many times was Caesar stabbed by his senators?", new String[]{"23", "27", "72", "4"}, 0),
new DefaultQuestion(800, "Louisiana is home to a rare pink dolphin named?", new String[]{"Pinky", "Cotten Candy", "Lady", "The Other Tide."}, 0),
});
quiz.add("Ominously Enough Teachers", new Question[]{
new DefaultQuestion(200, "What do teachers know?", new String[]{"Everything about you", "All about the thing in the janitors closet", "If Dubait is real or not", "12"}, 0),
new DefaultQuestion(400, "Who is my physics teacher?", new String[]{"Mr. Penny", "Mr. Dime", "Mr. Nickel", "Mr. Dollar"}, 0),
new DefaultQuestion(600, "How much do teachers get payed on average?", new String[]{"$63,645", "$120,000", "$15", "$64,200"}, 0),
new DefaultQuestion(800, "For every 10 Canadian teachers, at least 4 have endured violence from students?", new String[]{"True", "False"}, 0),
});
quiz.add("Common Miconceptions", new Question[]{
new DefaultQuestion(200, "The most prolific modern serial killer is?", new String[]{"Everything about you", "All about the thing in the janitors closet", "If Dubait is real or not", "12"}, 0),
new DefaultQuestion(400, "Urine is sterile?", new String[]{"Mr. Penny", "Mr. Dime", "Mr. Nickel", "Mr. Dollar"}, 0),
new DefaultQuestion(600, "The Amazon rainforest provides ___% of Earth's oxygen", new String[]{"$63,645", "$120,000", "$15", "$64,200"}, 0),
new DefaultQuestion(800, "Apparently this is where the quiz ends", new String[]{"True", "True"}, 0),
});
quiz.add("Riddles", new Question[]{
new DefaultQuestion(200, "What is the meaning of live?", new String[]{"42", "Eat, Drink, Sleep, Repeat", "Grow, get a meaningness job, work till you die", "Parties"}, 0),
new DefaultQuestion(400, "What's black and white and red all over?", new String[]{"A news paper", "A pengiun with a knife", "A panda with a knife"}, 0),
new DefaultQuestion(600, "Is this question pointless?", new String[]{"Yes", "No", "Depends on your point of view"}, 0),
new DefaultQuestion(800, "Why are you stil here?", new String[]{"Pubs are closed", "I want to learn more"}, 0),
});
return quiz;
}
}
public class DefaultQuestion implements Question {
private int points;
private String prompt;
private List<String> options;
private String answer;
public DefaultQuestion(int points, String prompt, String[] options, int answer) {
this.points = points;
this.prompt = prompt;
this.options = Arrays.asList(options);
this.answer = options[answer];
}
public int getPoints() {
return points;
}
public String getPrompt() {
return prompt;
}
public String[] getOptions() {
Collections.shuffle(options);
return options.toArray(new String[options.size()]);
}
#Override
public boolean isCorrect(String answer) {
return this.answer.equals(answer);
}
}
So, this default implementation has a simple build method which builds a quiz, based on the information I extracted from your question.
One thing to note is, every time DefaultQuestion#getOptions is called, the options are randomised!! So you, you know, actually have to read the answers 😉
Now, the UI is broken down into three parts, the "categories pane", the "question and answer pane" and the "controller"
The first two are pretty easy to understand, the controller needs a little bit more consideration.
Let's start with the first two...
public class QuizCategoriesPane extends JPanel {
public static interface Observer {
public void askQuestion(QuizCategoriesPane source, Quiz quize, Question question);
}
private Quiz quiz;
private Observer observer;
public QuizCategoriesPane(Quiz quiz, Observer observer) {
this.quiz = quiz;
this.observer = observer;
String[] categories = quiz.getCatagories();
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
gbc.gridheight = GridBagConstraints.REMAINDER;
gbc.insets = new Insets(4, 4, 4, 4);
gbc.anchor = GridBagConstraints.NORTH;
for (String category : categories) {
add(makeCategoryPaneFor(category, quiz.getQuestionsForCatagory(category)), gbc);
}
JButton spinButton = buildButton();
spinButton.setText("Spin the wheel");
gbc.fill = GridBagConstraints.HORIZONTAL;
add(spinButton, gbc);
}
public Quiz getQuiz() {
return quiz;
}
protected JPanel makeCategoryPaneFor(String category, Question[] questions) {
JPanel panel = new JPanel(new GridLayout(-1, 1, 4, 4));
for (Question question : questions) {
panel.add(makeButtonForQuestion(category, question));
}
return panel;
}
protected JButton makeButtonForQuestion(String category, Question question) {
JButton btn = buildButton();
btn.setText(category);
// I'd prefer to use a Action, but I'm probably already pushing you
// beyond your limits
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
observer.askQuestion(QuizCategoriesPane.this, getQuiz(), question);
}
});
return btn;
}
protected JButton buildButton() {
JButton btn = new JButton();
btn.setContentAreaFilled(false);
btn.setBorderPainted(false);
btn.setBackground(Color.BLUE);
btn.setForeground(Color.YELLOW);
btn.setOpaque(true);
btn.setBorder(new EmptyBorder(32, 32, 32, 32));
return btn;
}
}
public class QuestionPane extends JPanel {
public static interface Obsever {
public void didAnswerQuestion(QuestionPane source);
}
private Quiz quiz;
private Question question;
private QuestionPane(Quiz quiz, Question question, Obsever obsever) {
this.question = question;
setLayout(new BorderLayout());
add(new JLabel("<html>For " + question.getPoints() + " Points<br><h1>" + question.getPrompt() + "</h1></html>"), BorderLayout.NORTH);
JPanel options = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
ButtonGroup bg = new ButtonGroup();
for (String option : question.getOptions()) {
JRadioButton button = new JRadioButton("<html><h2>" + option + "</h2></html>");
button.setActionCommand(option);
bg.add(button);
options.add(button, gbc);
}
add(options);
JPanel actionPane = new JPanel(new GridBagLayout());
gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
gbc.anchor = GridBagConstraints.LINE_END;
JButton answerButton = new JButton("Answer");
answerButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String answer = bg.getSelection().getActionCommand();
if (quiz.didAnswerQuestion(question, answer)) {
JOptionPane.showMessageDialog(QuestionPane.this, "Correct");
} else {
JOptionPane.showMessageDialog(QuestionPane.this, "Incorrect");
}
obsever.didAnswerQuestion(QuestionPane.this);
}
});
actionPane.add(answerButton, gbc);
add(actionPane, BorderLayout.SOUTH);
}
}
The "controller" is responsible for managing the presentation of the "categories" and the "question/answer" UIs. Because the UIs are relatively complicated, they are separated into individual classes, this allows them to be responsible for just doing one job and not getting over burden with functionality which really isn't their responsibility anyway.
The controller might look something like...
public class QuizPane extends JPanel {
private CardLayout cardLayout;
public QuizPane(Quiz quiz) {
setBorder(new EmptyBorder(16, 16, 16, 16));
cardLayout = new CardLayout();
setLayout(cardLayout);
QuizCategoriesPane.Observer quizObserver = new QuizCategoriesPane.Observer() {
#Override
public void askQuestion(QuizCategoriesPane source, Quiz quize, Question question) {
QuestionPane qp = new QuestionPane(quiz, question, new QuestionPane.Obsever() {
#Override
public void didAnswerQuestion(QuestionPane source) {
remove(source);
cardLayout.show(QuizPane.this, "categories");
}
});
add(qp, "question");
cardLayout.show(QuizPane.this, "question");
}
};
add(new QuizCategoriesPane(quiz, quizObserver), "categories");
}
}
It has a very basic responsibility, show the user the categories, when a user selects a category, notified via an observer, show the question. When the user answers the question, notified via an observer, show the categories again.
As I said earlier, somebody needs to tell the categories pane that the score has changed, I've suggested that this could be done via an observer pattern on the Quiz itself, as this makes it independent of all the other workflows. And, no, I'm not going to do it.
Now, obviously, this needs some more work, for example, there's no way to track which questions have already been presented to the user, something else for you to figure out 😉
Runnable example
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.border.EmptyBorder;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
Quiz quiz = DefaultQuiz.build();
JFrame frame = new JFrame();
frame.add(new QuizPane(quiz));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public static interface Question {
public int getPoints();
public String getPrompt();
public String[] getOptions();
public boolean isCorrect(String answer);
}
public static interface Quiz {
public int getScore();
public String[] getCatagories();
public Question[] getQuestionsForCatagory(String category);
public boolean didAnswerQuestion(Question question, String answer);
}
public static class DefaultQuiz implements Quiz {
private Map<String, List<Question>> questions = new HashMap<>();
private int score;
public void add(String category, Question[] questions) {
this.questions.put(category, Arrays.asList(questions));
}
#Override
public boolean didAnswerQuestion(Question question, String answer) {
if (question.isCorrect(answer)) {
score += question.getPoints();
return true;
}
return false;
}
#Override
public int getScore() {
return score;
}
#Override
public String[] getCatagories() {
Set<String> keys = questions.keySet();
return keys.toArray(new String[keys.size()]);
}
#Override
public Question[] getQuestionsForCatagory(String category) {
List<Question> values = questions.get(category);
return values.toArray(new Question[values.size()]);
}
public static Quiz build() {
DefaultQuiz quiz = new DefaultQuiz();
quiz.add("Oddly Niche Topics", new Question[]{
new DefaultQuestion(200, "What is the capital of Cyprus?", new String[]{"Nicosia", "Mumbai", "Dubait", "Romania"}, 0),
new DefaultQuestion(400, "What is a note that is played for half the duration of a thirty second note?", new String[]{"demisemiquaver", "semidemiquaver", "qaver", "stop note"}, 0),
new DefaultQuestion(600, "How many times was Caesar stabbed by his senators?", new String[]{"23", "27", "72", "4"}, 0),
new DefaultQuestion(800, "Louisiana is home to a rare pink dolphin named?", new String[]{"Pinky", "Cotten Candy", "Lady", "The Other Tide."}, 0),
});
quiz.add("Ominously Enough Teachers", new Question[]{
new DefaultQuestion(200, "What do teachers know?", new String[]{"Everything about you", "All about the thing in the janitors closet", "If Dubait is real or not", "12"}, 0),
new DefaultQuestion(400, "Who is my physics teacher?", new String[]{"Mr. Penny", "Mr. Dime", "Mr. Nickel", "Mr. Dollar"}, 0),
new DefaultQuestion(600, "How much do teachers get payed on average?", new String[]{"$63,645", "$120,000", "$15", "$64,200"}, 0),
new DefaultQuestion(800, "For every 10 Canadian teachers, at least 4 have endured violence from students?", new String[]{"True", "False"}, 0),
});
quiz.add("Common Miconceptions", new Question[]{
new DefaultQuestion(200, "The most prolific modern serial killer is?", new String[]{"Everything about you", "All about the thing in the janitors closet", "If Dubait is real or not", "12"}, 0),
new DefaultQuestion(400, "Urine is sterile?", new String[]{"Mr. Penny", "Mr. Dime", "Mr. Nickel", "Mr. Dollar"}, 0),
new DefaultQuestion(600, "The Amazon rainforest provides ___% of Earth's oxygen", new String[]{"$63,645", "$120,000", "$15", "$64,200"}, 0),
new DefaultQuestion(800, "Apparently this is where the quiz ends", new String[]{"True", "True"}, 0),
});
quiz.add("Riddles", new Question[]{
new DefaultQuestion(200, "What is the meaning of live?", new String[]{"42", "Eat, Drink, Sleep, Repeat", "Grow, get a meaningness job, work till you die", "Parties"}, 0),
new DefaultQuestion(400, "What's black and white and red all over?", new String[]{"A news paper", "A pengiun with a knife", "A panda with a knife"}, 0),
new DefaultQuestion(600, "Is this question pointless?", new String[]{"Yes", "No", "Depends on your point of view"}, 0),
new DefaultQuestion(800, "Why are you stil here?", new String[]{"Pubs are closed", "I want to learn more"}, 0),
});
return quiz;
}
}
public static class DefaultQuestion implements Question {
private int points;
private String prompt;
private List<String> options;
private String answer;
public DefaultQuestion(int points, String prompt, String[] options, int answer) {
this.points = points;
this.prompt = prompt;
this.options = Arrays.asList(options);
this.answer = options[answer];
}
public int getPoints() {
return points;
}
public String getPrompt() {
return prompt;
}
public String[] getOptions() {
Collections.shuffle(options);
return options.toArray(new String[options.size()]);
}
#Override
public boolean isCorrect(String answer) {
return this.answer.equals(answer);
}
}
public static class QuizPane extends JPanel {
private CardLayout cardLayout;
public QuizPane(Quiz quiz) {
setBorder(new EmptyBorder(16, 16, 16, 16));
cardLayout = new CardLayout();
setLayout(cardLayout);
QuizCategoriesPane.Observer quizObserver = new QuizCategoriesPane.Observer() {
#Override
public void askQuestion(QuizCategoriesPane source, Quiz quize, Question question) {
QuestionPane qp = new QuestionPane(quiz, question, new QuestionPane.Obsever() {
#Override
public void didAnswerQuestion(QuestionPane source) {
remove(source);
cardLayout.show(QuizPane.this, "categories");
}
});
add(qp, "question");
cardLayout.show(QuizPane.this, "question");
}
};
add(new QuizCategoriesPane(quiz, quizObserver), "categories");
}
}
public static class QuizCategoriesPane extends JPanel {
public static interface Observer {
public void askQuestion(QuizCategoriesPane source, Quiz quize, Question question);
}
private Quiz quiz;
private Observer observer;
public QuizCategoriesPane(Quiz quiz, Observer observer) {
this.quiz = quiz;
this.observer = observer;
String[] categories = quiz.getCatagories();
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
gbc.gridheight = GridBagConstraints.REMAINDER;
gbc.insets = new Insets(4, 4, 4, 4);
gbc.anchor = GridBagConstraints.NORTH;
for (String category : categories) {
add(makeCategoryPaneFor(category, quiz.getQuestionsForCatagory(category)), gbc);
}
JButton spinButton = buildButton();
spinButton.setText("Spin the wheel");
gbc.fill = GridBagConstraints.HORIZONTAL;
add(spinButton, gbc);
}
public Quiz getQuiz() {
return quiz;
}
protected JPanel makeCategoryPaneFor(String category, Question[] questions) {
JPanel panel = new JPanel(new GridLayout(-1, 1, 4, 4));
for (Question question : questions) {
panel.add(makeButtonForQuestion(category, question));
}
return panel;
}
protected JButton makeButtonForQuestion(String category, Question question) {
JButton btn = buildButton();
btn.setText(category);
// I'd prefer to use a Action, but I'm probably already pushing you
// beyond your limits
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
observer.askQuestion(QuizCategoriesPane.this, getQuiz(), question);
}
});
return btn;
}
protected JButton buildButton() {
JButton btn = new JButton();
btn.setContentAreaFilled(false);
btn.setBorderPainted(false);
btn.setBackground(Color.BLUE);
btn.setForeground(Color.YELLOW);
btn.setOpaque(true);
btn.setBorder(new EmptyBorder(32, 32, 32, 32));
return btn;
}
}
public static class QuestionPane extends JPanel {
public static interface Obsever {
public void didAnswerQuestion(QuestionPane source);
}
private Quiz quiz;
private Question question;
private QuestionPane(Quiz quiz, Question question, Obsever obsever) {
this.question = question;
setLayout(new BorderLayout());
add(new JLabel("<html>For " + question.getPoints() + " Points<br><h1>" + question.getPrompt() + "</h1></html>"), BorderLayout.NORTH);
JPanel options = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
ButtonGroup bg = new ButtonGroup();
for (String option : question.getOptions()) {
JRadioButton button = new JRadioButton("<html><h2>" + option + "</h2></html>");
button.setActionCommand(option);
bg.add(button);
options.add(button, gbc);
}
add(options);
JPanel actionPane = new JPanel(new GridBagLayout());
gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
gbc.anchor = GridBagConstraints.LINE_END;
JButton answerButton = new JButton("Answer");
answerButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String answer = bg.getSelection().getActionCommand();
if (quiz.didAnswerQuestion(question, answer)) {
JOptionPane.showMessageDialog(QuestionPane.this, "Correct");
} else {
JOptionPane.showMessageDialog(QuestionPane.this, "Incorrect");
}
obsever.didAnswerQuestion(QuestionPane.this);
}
});
actionPane.add(answerButton, gbc);
add(actionPane, BorderLayout.SOUTH);
}
}
}

Adding Data to JTable from different Class

SO I have this Test Client which will run the program and i want this class to populate a JTable in a JPanel class named StartScreenPlayerPanel.
I've tried several methods which failed.
TestClient Class
import view.MainFrame;
import view.StartScreenPlayerPanel;
public class TestClientGUI {
private static final Logger logger = Logger.getLogger(SimpleTestClientGUI.class.getName());
private static Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
MainFrame mainframe;
StartScreenPlayerPanel startScreenPlayerPanel;
public static void main(String args[]) {
final GameEngine gameEngine = new GameEngineImpl();
//GUI - new MainFrame
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainFrame frame = new MainFrame();
System.out.println(screenSize);
frame.setMinimumSize(new Dimension(screenSize.width/2, screenSize.height/2));
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
The Class with the JTable - "StartScreenPlayerPanel"
public class StartScreenPlayerPanel extends JPanel {
MainFrame mainframe;
//private JTable table;
private DefaultTableModel model = new DefaultTableModel();
public StartScreenPlayerPanel() {
setLayout(new BorderLayout());
JTable table = new JTable(model);
table.getTableHeader().setFont(new Font("Arial", Font.BOLD, 16));
model.addColumn("Player");
model.addColumn("Initial Points");
//model.addRow(new Object[]{"v1", "v2"});
add(table.getTableHeader(), BorderLayout.NORTH);
add(table, BorderLayout.CENTER);
}
public void setModel(String c1, String c2) {
model.addRow(new Object[]{c1, c2});
model.fireTableDataChanged();
}
public DefaultTableModel getModel() {
return this.model;
}
}
What I tried So far ;
//Add players to GUI
StartScreenPlayerPanel startScreenPlayerPanel = new StartScreenPlayerPanel();
startScreenPlayerPanel.setModel("CoinMaster","TheLoser");
startScreenPlayerPanel.getModel().addRow(new Object[]{"CoinMaster", "TheLoser"});
startScreenPlayerPanel.getModel().setValueAt("TheLoser", 2, 2);
Nothing I tried worked, except doing it in the same class
Thanks For your help.
Edit - Added code for MainFrame:
public class MainFrame extends JFrame {
static Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
private StartScreenPlayerPanel startScreenPlayerPanel;
private JPanel contentPane;
private JTable table;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainFrame frame = new MainFrame();
System.out.println(screenSize);
frame.setMinimumSize(new Dimension(screenSize.width/2, screenSize.height/2));
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public MainFrame() {
startScreenPlayerPanel = new StartScreenPlayerPanel();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, (screenSize.width * 2 / 3), (screenSize.height * 2 / 3));
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
GridBagLayout gbl_contentPane = new GridBagLayout();
gbl_contentPane.columnWidths = new int[]{1200, 0};
gbl_contentPane.rowHeights = new int[]{74, 0, 446, 0, 0};
gbl_contentPane.columnWeights = new double[]{1.0, Double.MIN_VALUE};
gbl_contentPane.rowWeights = new double[]{0.0, 0.0, 1.0, 0.0, Double.MIN_VALUE};
contentPane.setLayout(gbl_contentPane);
JLabel lblTitle = new JLabel("The Coin Game",SwingConstants.CENTER);
lblTitle.setFont(new Font("Arial", Font.PLAIN, (int)screenSize.width/30));
GridBagConstraints gbc_lblTitle = new GridBagConstraints();
gbc_lblTitle.gridwidth = 2;
gbc_lblTitle.insets = new Insets(0, 0, 5, 0);
gbc_lblTitle.anchor = GridBagConstraints.NORTH;
gbc_lblTitle.fill = GridBagConstraints.HORIZONTAL;
gbc_lblTitle.gridx = 0;
gbc_lblTitle.gridy = 0;
contentPane.add(lblTitle, gbc_lblTitle);
JPanel StartScreenBtnPanel = new JPanel();
GridBagConstraints gbc_StartScreenBtnPanel = new GridBagConstraints();
gbc_StartScreenBtnPanel.gridwidth = 0;
gbc_StartScreenBtnPanel.insets = new Insets(0, 0, 5, 0);
gbc_StartScreenBtnPanel.fill = GridBagConstraints.BOTH;
gbc_StartScreenBtnPanel.gridx = 0;
gbc_StartScreenBtnPanel.gridy = 1;
contentPane.add(StartScreenBtnPanel, gbc_StartScreenBtnPanel);
StartScreenBtnPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
JButton btnAddPlayer = new JButton("Add Player");
btnAddPlayer.setFont(new Font("Tahoma", Font.PLAIN, 16));
StartScreenBtnPanel.add(btnAddPlayer);
JButton btnStartGame = new JButton("Start Game");
btnStartGame.setFont(new Font("Tahoma", Font.PLAIN, 16));
StartScreenBtnPanel.add(btnStartGame);
GridBagConstraints gbc_playerPanel = new GridBagConstraints();
gbc_playerPanel.gridwidth = 2;
gbc_playerPanel.insets = new Insets(0, 0, 5, 0);
gbc_playerPanel.fill = GridBagConstraints.BOTH;
gbc_playerPanel.gridx = 0;
gbc_playerPanel.gridy = 2;
contentPane.add(startScreenPlayerPanel, gbc_playerPanel);
}
public StartScreenPlayerPanel getStartScreenPlayerPanel() {
return startScreenPlayerPanel;
}
}

Can't compare button icon to another icon

I am overriding the actionListener. All of the buttons besides "playbutton" have an image attached as an icon (button1, button2, button3). Every time a button is pressed, it should compare its icon to the prepared ImageIcon "livePicture" and if they are the same, it should go with the "Escaped()" method. Otherwise, the program will run the "Died()" method.
However, at least with the current code, it only uses "Died()". This, I guess, means that there is something wrong with the ifs that compare the images, but that is the only way of comparison I found on the internet.
Also, keep in mind that this is my first project, so it may seem a little cluttered.
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.Vector;
public class Frame
{
private final int WIDTH = 1024;
private final int HEIGHT = 768;
private JFrame frame;
private JPanel panel;
private JLabel human;
private JTextArea text;
private JTextArea deathMessage;
private ImageIcon livePicture;
private JButton button1;
private JButton button2;
private JButton button3;
private GridBagConstraints gbc;
private ActionListener actionListener;
private JButton playButton;
private Border border = BorderFactory.createEmptyBorder();
private Font font = new Font(Font.MONOSPACED, Font.PLAIN, 20);
public Frame()
{
Quest survival = new Quest();
actionListener = e -> {
if (e.getSource() == playButton) //playbutton works fine
{
if (!survival.IsEmpty())
{
AppendQuest(survival.GetQuest());
survival.RemoveQuest();
}
else
{
Escaped();
}
}
else if (e.getSource() == button1) //button1 action
{
if (button1.getIcon().toString() != livePicture.toString())
{
Died();
}
else
{
if (!survival.IsEmpty())
{
AppendQuest(survival.GetQuest());
survival.RemoveQuest();
}
else
{
Escaped();
}
}
}
else if (e.getSource() == button2) //button2 action
{
if (button2.getIcon().toString() != livePicture.toString())
{
Died();
}
else
{
if (!survival.IsEmpty())
{
AppendQuest(survival.GetQuest());
survival.RemoveQuest();
}
else
{
Escaped();
}
}
}
else if (e.getSource() == button3) //button3 action
{
if (button3.getIcon().toString() != livePicture.toString())
{
Died();
}
else
{
if (!survival.IsEmpty())
{
AppendQuest(survival.GetQuest());
survival.RemoveQuest();
}
else
{
Escaped();
}
}
}
};
//I left the rest of the constructor for bonus info
frame = new JFrame();
panel = new JPanel();
gbc = new GridBagConstraints();
human = new JLabel(ImageSize(200, 200, "res/human.png"));
text = new JTextArea("You have lost in the forest. Now you have to find " +
"your way back.");
FormatText(text);
deathMessage = new JTextArea();
frame.setTitle("Shady Path");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(WIDTH, HEIGHT);
frame.setLocationRelativeTo(null);
frame.getContentPane().setBackground(Color.BLACK);
frame.setResizable(false);
playButton = new JButton();
playButton.addActionListener(actionListener);
playButton.setFont(font);
playButton.setText("Play");
playButton.setForeground(Color.WHITE);
playButton.setBackground(Color.BLACK);
playButton.setBorder(border);
panel.setLayout(new GridBagLayout());
panel.setOpaque(false);
gbc.anchor = GridBagConstraints.PAGE_START;
gbc.gridwidth = GridBagConstraints.REMAINDER;
panel.add(human, gbc);
gbc.insets = new Insets(30, 0, 0, 0);
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
panel.add(text, gbc);
gbc.fill = GridBagConstraints.VERTICAL;
gbc.insets = new Insets(50, 0, 68, 0);
panel.add(playButton, gbc);
frame.add(panel);
frame.setVisible(true);
}
public void AppendQuest(Vector<String> event)
{
panel.removeAll();
panel.add(human, gbc);
gbc.insets = new Insets(0, 0, 30, 0);
text.setText(event.remove(0));
FormatText(text);
panel.add(text, gbc);
deathMessage.setText(event.remove(0));
FormatText(deathMessage);
livePicture = ImageSize(50, 50, event.remove(0));
Collections.shuffle(event);
ImageIcon picture1 = ImageSize(50, 50, event.get(0)); //setting button1
button1 = new JButton();
button1.addActionListener(actionListener);
button1.setIcon(picture1);
button1.setBorder(border);
ImageIcon picture2 = ImageSize(50, 50, event.get(1)); //setting button2
button2 = new JButton();
button2.addActionListener(actionListener);
button2.setIcon(picture2);
button2.setBorder(border);
ImageIcon picture3 = ImageSize(50, 50, event.get(2)); //setting button3
button3 = new JButton();
button3.addActionListener(actionListener);
button3.setIcon(picture3);
button3.setBorder(border);
gbc.gridwidth = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(50, 360, 100, 0);
panel.add(button1, gbc);
gbc.insets = new Insets(50, 77, 100, 77);
panel.add(button2, gbc);
gbc.insets = new Insets(50, 0, 100, 360);
panel.add(button3, gbc);
panel.revalidate();
panel.repaint();
}
private void Escaped()
{
//Unnecessary info
}
private void Died()
{
//Unnecessary info
}
//This just resizes the images
private ImageIcon ImageSize(int x, int y, String fileName)
{
BufferedImage baseImg = null;
try {
baseImg = ImageIO.read(new File(fileName));
} catch (IOException e) {
e.printStackTrace();
}
Image resizedImg = baseImg.getScaledInstance(x, y, Image.SCALE_SMOOTH);
ImageIcon IconImg = new ImageIcon(resizedImg);
return IconImg;
}
private void FormatText(JTextArea baseText)
{
//Unnecessary info
}
}
EDIT:
Here is also an example of what vector could go as an "event" in "AppendQuest"
Vector<String> items2 = new Vector<>();
items2.add("You are kind of disoriented. What will you use to find the right way?" +
" moss, sun or tree barks");
items2.add("Unfortunately you didn't orient yourself well enough. Now, you " +
"will roam through the forest forever.");
items2.add("res/orientation_sun.png");
items2.add("res/orientation_moss.png");
items2.add("res/orientation_sun.png");
items2.add("res/orientation_tree_bark.png");
You can compare Objects with the .equals(Object) function:
if(!button.getIcon().equals(livePicture))
{
Died();
}
else
{...}
The == operator checks the identity of objects or the value of native types (e.g. int).
That means:
int nr1 = 1;
int nr2 = 1;
if(nr1 == nr2) {...} //true -> int is a native type
String str1 = "test";
String str2 = "test";
if(str1 == str2) {...} //false -> Same content but not same objects
if(str1.equals(str2)) {...} //true -> Same content, different objects
//Edit:
Another problem might be that you remove the image-url from your vector while creating the livePicture:
livePicture = ImageSize(50, 50, event.remove(0));
The url is not in the list anymore when you create your buttons. The result is that the buttons will never have the same image as your livePicture has, unless you're changing it (do you?).

JFrame Background Image does not work [duplicate]

This question already has answers here:
JFrame background image
(4 answers)
Closed 6 years ago.
I searched for a way to add an Image as an Bakground for my JFrame.
I found some Questions for that and tried several solutions but my Image won't show up and I don't know what's wrong (I'm a noob btw xd)
I DID see the other Questions but they DID NOT help me, I tried really hard but can't find my fault! So please (Human who marked my post as duplicate).
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class prognose extends Frame {
// Anfang Attribute
private JTextField spendenbetrag = new JTextField();
private JTextField streamzeit = new JTextField();
private JLabel sBetragL = new JLabel();
private JLabel sZeitL = new JLabel();
private JButton prognosebutton = new JButton();
private ImageIcon prognosebuttonIcon = new ImageIcon("C:\\Users\\user\\Documents\\Programmieren\\Workspace\\images\\Button.png");
private JTextField ergebnis = new JTextField();
// Ende Attribute
public prognose() {
// Frame-Initialisierung
super();
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) { dispose(); }
});
int frameWidth = 455;
int frameHeight = 580;
setSize(frameWidth, frameHeight);
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
int x = (d.width - getSize().width) / 2;
int y = (d.height - getSize().height) / 2;
setLocation(x, y);
setTitle("Loot für die Welt");
setResizable(false);
Panel cp = new Panel(null);
add(cp);
// Anfang Komponenten
spendenbetrag.setText("");
cp.add(spendenbetrag);
streamzeit.setText("");
cp.add(streamzeit);
sBetragL.setText("Aktueller Spendenbetrag");
cp.add(sBetragL);
streamzeit.setBounds(152, 184, 145, 25);
spendenbetrag.setBounds(152, 112, 145, 25);
sBetragL.setBounds(152, 80, 145, 25);
sZeitL.setBounds(152, 152, 155, 25);
sZeitL.setText("Aktuelle Streamzeit");
cp.add(sZeitL);
prognosebutton.setBounds(184, 224, 80, 280);
prognosebutton.setText("");
prognosebutton.setMargin(new Insets(2, 2, 2, 2));
prognosebutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
prognosebutton_ActionPerformed(evt);
}
});
prognosebutton.setIcon(prognosebuttonIcon);
prognosebutton.setBorderPainted(false);
prognosebutton.setBackground(Color.WHITE);
prognosebutton.setBorder(BorderFactory.createEtchedBorder(0, Color.DARK_GRAY, new Color(0xC0C0C0)));
prognosebutton.setIconTextGap(0);
cp.setBackground(Color.WHITE);
setUndecorated(false);
cp.add(prognosebutton);
ergebnis.setBounds(152, 512, 145, 25);
ergebnis.setText("");
ergebnis.setEditable(false);
cp.add(ergebnis);
// Ende Komponenten
setVisible(true);
setLayout(new BorderLayout());
setSize(455,580);
setVisible(true);
JLabel background=new JLabel(new ImageIcon("C:\\Users\\user\\Documents\\Programmieren\\Workspace\\images\\Background.png"));
add(background);
background.setLayout(new FlowLayout());
} // end of public prognose
// Anfang Methoden
public static void main(String[] args) {
new prognose();
} // end of main
public void prognosebutton_ActionPerformed(ActionEvent evt) {
// TODO hier Quelltext einfügen
String a;
String b;
a = spendenbetrag.getText();
b = streamzeit.getText();
double d;
double e = Double.parseDouble(a);
double f = Double.parseDouble(b);
d = e*(60/f)*48;
d = ((double)((int)(d*100)))/100;
String g = String.valueOf(d);
ergebnis.setText(g);
} // end of prognosebutton_ActionPerformed
// Ende Methoden
} // end of class prognose
Extend JFrame instead of Frame, use the setComponentPane to set the backround, Move the declaration of the background label to the top of the code. Add all the components to that label.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class prognose extends JFrame {
// Anfang Attribute
private JTextField spendenbetrag = new JTextField();
private JTextField streamzeit = new JTextField();
private JLabel sBetragL = new JLabel();
private JLabel sZeitL = new JLabel();
private JButton prognosebutton = new JButton();
private ImageIcon prognosebuttonIcon = new ImageIcon("C:\\test\\rak.png");
private JTextField ergebnis = new JTextField();
// Ende Attribute
public prognose() {
// Frame-Initialisierung
super();
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) { dispose(); }
});
int frameWidth = 455;
int frameHeight = 580;
setSize(frameWidth, frameHeight);
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
int x = (d.width - getSize().width) / 2;
int y = (d.height - getSize().height) / 2;
setLocation(x, y);
setTitle("Loot für die Welt");
setResizable(false);
JLabel background=new JLabel(new ImageIcon("C:\\test\\rak.png"));
setContentPane(background);
background.setLayout(new FlowLayout());
Panel cp = new Panel(null);
background.add(cp);
// Anfang Komponenten
spendenbetrag.setText("");
background.add(spendenbetrag);
streamzeit.setText("");
background.add(streamzeit);
sBetragL.setText("Aktueller Spendenbetrag");
background.add(sBetragL);
streamzeit.setBounds(152, 184, 145, 25);
spendenbetrag.setBounds(152, 112, 145, 25);
sBetragL.setBounds(152, 80, 145, 25);
sZeitL.setBounds(152, 152, 155, 25);
sZeitL.setText("Aktuelle Streamzeit");
background.add(sZeitL);
prognosebutton.setBounds(184, 224, 80, 280);
prognosebutton.setText("");
prognosebutton.setMargin(new Insets(2, 2, 2, 2));
prognosebutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
prognosebutton_ActionPerformed(evt);
}
});
prognosebutton.setIcon(prognosebuttonIcon);
prognosebutton.setBorderPainted(false);
prognosebutton.setBackground(Color.WHITE);
prognosebutton.setBorder(BorderFactory.createEtchedBorder(0, Color.DARK_GRAY, new Color(0xC0C0C0)));
prognosebutton.setIconTextGap(0);
background.setBackground(Color.WHITE);
setUndecorated(false);
background.add(prognosebutton);
ergebnis.setBounds(152, 512, 145, 25);
ergebnis.setText("");
ergebnis.setEditable(false);
background.add(ergebnis);
// Ende Komponenten
setVisible(true);
setLayout(new BorderLayout());
setSize(455,580);
setVisible(true);
} // end of public prognose
// Anfang Methoden
public static void main(String[] args) {
new prognose();
} // end of main
public void prognosebutton_ActionPerformed(ActionEvent evt) {
// TODO hier Quelltext einfügen
String a;
String b;
a = spendenbetrag.getText();
b = streamzeit.getText();
double d;
double e = Double.parseDouble(a);
double f = Double.parseDouble(b);
d = e*(60/f)*48;
d = ((double)((int)(d*100)))/100;
String g = String.valueOf(d);
ergebnis.setText(g);
} // end of prognosebutton_ActionPerformed
// Ende Methoden
} // end of class prognose

Icon is not set right on GlassPane

I have a class that sets warning icons behind a textField when the input is different from what i expect form the user. For textfield this class works perfect, but when i'm trying to use it with a textArea the warning icons aren't set on the right location .
here is the class that sets and removes the warning icons:
public class GlassValidationPane extends JComponent {
private HashMap<Component, JLabel> warningLabels = new HashMap<>();
private ImageIcon warningIcon;
private final ImageUtilities iU = new ImageUtilities();
public GlassValidationPane() {
setLayout(null);
setOpaque(false);
Icon icon = UIManager.getIcon("OptionPane.warningIcon");
int imgW = icon.getIconWidth();
int imgH = icon.getIconHeight();
BufferedImage img = iU.getBufferedImageOfIcon(icon, imgW, imgH);
warningIcon = new ImageIcon(iU.resize(img, 18, 18));
}
void showWarningIcon(Component c) {
if (warningLabels.containsKey(c)) {
return;
}
JLabel label = new JLabel();
label.setIcon(warningIcon);
//int x=c.getX();//this will make it insode the component
int x = c.getWidth() + c.getX() + label.getIcon().getIconWidth();//this makes it appear outside/next to component);
int y = c.getY();
System.out.println("ïn show warning: " + y);
label.setBounds(x, y, label.getIcon().getIconWidth(), label.getIcon().getIconHeight());
add(label);
label.setVisible(true);
revalidate();
repaint();
warningLabels.put(c, label);
}
public void removeWarningIcon(Component c) {
for (Map.Entry<Component, JLabel> entry : warningLabels.entrySet()) {
Component component = entry.getKey();
JLabel jLabel = entry.getValue();
if (component == c) {
remove(jLabel);
revalidate();
repaint();
break;
}
}
warningLabels.remove(c);
}
public void refreshLocations() {
for (Map.Entry<Component, JLabel> entry : warningLabels.entrySet()) {
Component c = entry.getKey();
JLabel label = entry.getValue();
int x = c.getWidth() + c.getX() + label.getIcon().getIconWidth();//this makes it appear outside/next to component
int y = c.getY();
label.setBounds(x, y, label.getIcon().getIconWidth(), label.getIcon().getIconHeight());
revalidate();
repaint();
}
}
public boolean allSet(){
if(!warningLabels.isEmpty()){
JOptionPane.showMessageDialog(null, "Please fill every text field in, or adjust te wrong input", "Empty input/Wrong input", JOptionPane.ERROR_MESSAGE);
return false;
}
return true;
}
private class ImageUtilities {
public BufferedImage resize(BufferedImage image, int width, int height) {
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TRANSLUCENT);
Graphics2D g2d = (Graphics2D) bi.createGraphics();
g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
g2d.drawImage(image, 0, 0, width, height, null);
g2d.dispose();
return bi;
}
public BufferedImage getBufferedImageOfIcon(Icon icon, int imgW, int imgH) {
BufferedImage img = new BufferedImage(imgW, imgH, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = (Graphics2D) img.getGraphics();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
icon.paintIcon(null, g2d, 0, 0);
g2d.dispose();
return img;
}
}
}
I have found that the getY() function for the textArea always gives 0 back, but i can't find why it always return 0. here is the code who calls the class ClaxxValidationPane:
public class JobInput extends JFrame {
private JPanel contentPane;
private JTextField txtJobId;
private GlassValidationPane gvp;
private JTextArea textAreaDesription;
private boolean INSERT;
/**
* Create the frame.
*/
public JobInput(String titel, boolean INSERT) {
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
setVisible(false);
dispose();
}
});
setBounds(100, 100, 296, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
GridBagLayout gbl_contentPane = new GridBagLayout();
gbl_contentPane.columnWidths = new int[]{0, 0, 0};
gbl_contentPane.rowHeights = new int[]{0, 0, 0, 0, 0, 0};
gbl_contentPane.columnWeights = new double[]{0.0, 0.0, Double.MIN_VALUE};
gbl_contentPane.rowWeights = new double[]{0.0, 0.0, 0.0, 1.0, 0.0, Double.MIN_VALUE};
contentPane.setLayout(gbl_contentPane);
JLabel lblTitel = new JLabel(titel);
lblTitel.setFont(new Font("Arial", Font.BOLD, 15));
GridBagConstraints gbc_lblTitel = new GridBagConstraints();
gbc_lblTitel.gridwidth = 2;
gbc_lblTitel.insets = new Insets(0, 0, 5, 0);
gbc_lblTitel.gridx = 0;
gbc_lblTitel.gridy = 0;
contentPane.add(lblTitel, gbc_lblTitel);
JSeparator separator = new JSeparator();
GridBagConstraints gbc_separator = new GridBagConstraints();
gbc_separator.fill = GridBagConstraints.BOTH;
gbc_separator.gridwidth = 2;
gbc_separator.insets = new Insets(0, 0, 5, 0);
gbc_separator.gridx = 0;
gbc_separator.gridy = 1;
contentPane.add(separator, gbc_separator);
JLabel lblJobid = new JLabel("JobID");
GridBagConstraints gbc_lblJobid = new GridBagConstraints();
gbc_lblJobid.anchor = GridBagConstraints.EAST;
gbc_lblJobid.insets = new Insets(0, 0, 5, 5);
gbc_lblJobid.gridx = 0;
gbc_lblJobid.gridy = 2;
contentPane.add(lblJobid, gbc_lblJobid);
txtJobId = new JTextField();
GridBagConstraints gbc_txtJobId = new GridBagConstraints();
gbc_txtJobId.insets = new Insets(0, 0, 5, 0);
gbc_txtJobId.fill = GridBagConstraints.HORIZONTAL;
gbc_txtJobId.gridx = 1;
gbc_txtJobId.gridy = 2;
contentPane.add(txtJobId, gbc_txtJobId);
txtJobId.setColumns(10);
JLabel lblDescription = new JLabel("Description");
GridBagConstraints gbc_lblDescription = new GridBagConstraints();
gbc_lblDescription.anchor = GridBagConstraints.NORTH;
gbc_lblDescription.insets = new Insets(0, 0, 5, 5);
gbc_lblDescription.gridx = 0;
gbc_lblDescription.gridy = 3;
contentPane.add(lblDescription, gbc_lblDescription);
textAreaDesription = new JTextArea();
textAreaDesription.setLineWrap(true);
textAreaDesription.setWrapStyleWord(true);
GridBagConstraints gbc_textArea = new GridBagConstraints();
gbc_textArea.insets = new Insets(0, 0, 5, 0);
gbc_textArea.fill = GridBagConstraints.BOTH;
gbc_textArea.gridx = 1;
gbc_textArea.gridy = 3;
JScrollPane scroll = new JScrollPane (textAreaDesription,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
contentPane.add(scroll, gbc_textArea);
JButton btnOk = new JButton("Ok");
GridBagConstraints gbc_btnOk = new GridBagConstraints();
gbc_btnOk.gridwidth = 2;
gbc_btnOk.gridx = 0;
gbc_btnOk.gridy = 4;
contentPane.add(btnOk, gbc_btnOk);
gvp = new GlassValidationPane();
FocusAdapter fl = new FocusAdapter() {
#Override
public void focusGained(FocusEvent fe) {
super.focusGained(fe);
((JTextComponent) fe.getSource()).setBorder(BorderFactory.createLineBorder(Color.gray));
}
public void focusLost(FocusEvent fe) {
super.focusLost(fe);
if(fe.getSource().equals(txtJobId)){
validationForInteger(txtJobId);
} else if(fe.getSource().equals(textAreaDesription)){
validationForText(textAreaDesription);
} else{
gvp.removeWarningIcon(((Component) fe.getSource()));
((JTextComponent) fe.getSource()).setBorder(BorderFactory.createLineBorder(Color.gray));
}
}
};
txtJobId.addFocusListener(fl);
textAreaDesription.addFocusListener(fl);
setGlassPane(gvp);
gvp.setVisible(true);
}
private void validationForInteger(JTextComponent comp){
String temp = comp.getText();
if(temp.matches("^[1-9]\\d*$")){
setGreen(comp);
} else {
setRed(comp);
}
}
private void validationForText(JTextComponent comp) {
System.out.println("In validation for text " + textAreaDesription.getY());
String temp = comp.getText();
if (temp.matches("^[a-zA-Z0-9][a-zA-Z0-9\\s_/-]+$")) {
setGreen(comp);
} else {
setRed(comp);
}
}
private void setRed(JTextComponent comp) {
comp.setBorder(BorderFactory.createLineBorder(Color.red));
gvp.showWarningIcon(comp);
}
private void setGreen(JTextComponent comp) {
comp.setBorder(BorderFactory.createLineBorder(Color.green));
gvp.removeWarningIcon(comp);
}
}
thus the focus listners shall call for validation and there the classValidaionPane shall be called. If it is called then it goes wrong (but only for textArea's and not for textField) can somebody help me with this?
The parent component of the JTextArea is not the same as the parent component of the JTextField, since the JTextArea is inside a JScrollPane. I have not taken the time to read and understand all the code you posted, but you should probably placed the label relative to the position of the JScrollPane, and not relative to the position of the JTextArea.

Categories

Resources