I am trying to make a sign in program with a time clock display. I am having a hard time trying to get the clock into the already made JPanel. It currently pops up 2 seperate JPanels when I run the program. Please help with any suggestions.
CODE:
private static JLabel lblUserName;
private static JTextField txtUserName;
private static JButton btnSignIn;
private static JLabel lblPassword;
private static JPasswordField txtPassword;
private static JButton btnCancel;
private static JTabbedPane tabbedPane;
public static void main(String[] args)
{
UserSignIn frame = new UserSignIn();
JFrame frm = new JFrame();
SimpleDigitalClock clock1 = new SimpleDigitalClock();
frm.add(clock1);
//Pack
frm.pack();
frame.pack();
// Set origional focus on User Name text field
txtUserName.requestFocusInWindow();
// Make Visible
frame.setVisible(true);
frm.setVisible(true);
}
static class SimpleDigitalClock extends JPanel
{
String stringTime;
int hour, minute, second;
String aHour = "";
String bMinute = "";
String cSecond = "";
public void setStringTime(String abc)
{
this.stringTime = abc;
}
public int Number(int a, int b)
{
return (a <= b) ? a : b;
}
SimpleDigitalClock()
{
Timer t = new Timer(1000, new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
repaint();
}
});
t.start();
}
#Override
public void paintComponent(Graphics v)
{
super.paintComponent(v);
Calendar rite = Calendar.getInstance();
hour = rite.get(Calendar.HOUR_OF_DAY);
minute = rite.get(Calendar.MINUTE);
second = rite.get(Calendar.SECOND);
if (hour < 10)
{
this.aHour = "0";
}
if (hour >= 10)
{
this.aHour = "";
}
if (minute < 10)
{
this.bMinute = "0";
}
if (minute >= 10)
{
this.bMinute = "";
}
if (second < 10)
{
this.cSecond = "0";
}
if (second >= 10)
{
this.cSecond = "";
}
setStringTime(aHour + hour + ":" + bMinute+ minute + ":" + cSecond + second);
v.setColor(Color.RED);
int length = Number(this.getWidth(),this.getHeight());
Font Font1 = new Font("Digital", Font.BOLD, length / 5);
v.setFont(Font1);
v.drawString(stringTime, (int) length/6, length/2);
}
#Override
public Dimension getPreferredSize()
{
return new Dimension(200, 200);
}
}
public UserSignIn()
{
initGUI();
}
public void initGUI()
{
setTitle("Login");
JPanel pnlUserSignIn = new JPanel(new GridBagLayout());
this.getContentPane().add(pnlUserSignIn);
//build table for employees signed in
JTable t = new JTable(null);
JLabel label = new JLabel("Employees Currently Signed In");
// ROW 1 BUTTONS
// Username and Sign In buttons
lblUserName = new JLabel("Username: ");
txtUserName = new JTextField("Username");
// Actions
//txtUserName.addMouseListener(this);
// Adding objects to Panel
JPanel pnlLogin = new JPanel();
pnlLogin.add(lblUserName);
pnlLogin.add(txtUserName);
//ROW 2 BUTTONS
//Password and Cancel
btnSignIn = new JButton("Sign In");
btnCancel=new JButton("Cancel");
//Actions
btnSignIn.addActionListener(this);
btnCancel.addActionListener(this);
// Adding objects to Panel
JPanel pnlPassword = new JPanel();
pnlPassword.add(btnSignIn);
pnlPassword.add(btnCancel);
JPanel detailsPanel = new JPanel();
detailsPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
GridBagConstraints gbc = new GridBagConstraints();
// Putting Objects into the grid
gbc.gridx = 0;
gbc.gridy = 0;
pnlUserSignIn.add(label, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
pnlUserSignIn.add(new JScrollPane(t), gbc);
gbc.gridx = 0;
gbc.gridy = 2;
pnlUserSignIn.add(pnlLogin, gbc);
gbc.gridx = 0;
gbc.gridy = 3;
gbc.gridwidth = 2;
pnlUserSignIn.add(pnlPassword, gbc);
//gbc.gridx = 1;
//gbc.gridy = 1;
//gbc.gridwidth = 1;
//gbc.gridheight = 2;
//panel.add(detailsPanel, gbc);
this.pack();
this.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent actionEvent)
{
if(actionEvent.getSource()==btnCancel)
{
System.exit(0);
}
//if(actionEvent.getSource()==txtUserName)
//{
// txtUserName.setText("");
// txtUserName.requestFocus();
//}
}
PLEASE IGNORE THE COMMENTED CODE, I am working on many things at once.
You don't need another frame. Just add clock to existing one. For example to the SOUTH:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Calendar;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.Timer;
public class UserSignIn extends JFrame implements ActionListener{
private static JLabel lblUserName;
private static JTextField txtUserName;
private static JButton btnSignIn;
private static JLabel lblPassword;
private static JPasswordField txtPassword;
private static JButton btnCancel;
private static JTabbedPane tabbedPane;
public static void main(String[] args) {
UserSignIn frame = new UserSignIn();
SimpleDigitalClock clock1 = new SimpleDigitalClock();
frame.add(clock1, BorderLayout.SOUTH);
// Pack
frame.pack();
// Set origional focus on User Name text field
txtUserName.requestFocusInWindow();
// Make Visible
frame.setVisible(true);
}
static class SimpleDigitalClock extends JPanel {
String stringTime;
int hour, minute, second;
String aHour = "";
String bMinute = "";
String cSecond = "";
public void setStringTime(String abc) {
this.stringTime = abc;
}
public int Number(int a, int b) {
return (a <= b) ? a : b;
}
SimpleDigitalClock() {
Timer t = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
repaint();
}
});
t.start();
}
#Override
public void paintComponent(Graphics v) {
super.paintComponent(v);
Calendar rite = Calendar.getInstance();
hour = rite.get(Calendar.HOUR_OF_DAY);
minute = rite.get(Calendar.MINUTE);
second = rite.get(Calendar.SECOND);
if (hour < 10) {
this.aHour = "0";
}
if (hour >= 10) {
this.aHour = "";
}
if (minute < 10) {
this.bMinute = "0";
}
if (minute >= 10) {
this.bMinute = "";
}
if (second < 10) {
this.cSecond = "0";
}
if (second >= 10) {
this.cSecond = "";
}
setStringTime(aHour + hour + ":" + bMinute + minute + ":" + cSecond
+ second);
v.setColor(Color.RED);
int length = Number(this.getWidth(), this.getHeight());
Font Font1 = new Font("Digital", Font.BOLD, length / 5);
v.setFont(Font1);
v.drawString(stringTime, (int) length / 6, length / 2);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
public UserSignIn() {
initGUI();
}
public void initGUI() {
setTitle("Login");
JPanel pnlUserSignIn = new JPanel(new GridBagLayout());
this.getContentPane().add(pnlUserSignIn);
// build table for employees signed in
JTable t = new JTable(null);
JLabel label = new JLabel("Employees Currently Signed In");
// ROW 1 BUTTONS
// Username and Sign In buttons
lblUserName = new JLabel("Username: ");
txtUserName = new JTextField("Username");
// Actions
// txtUserName.addMouseListener(this);
// Adding objects to Panel
JPanel pnlLogin = new JPanel();
pnlLogin.add(lblUserName);
pnlLogin.add(txtUserName);
// ROW 2 BUTTONS
// Password and Cancel
btnSignIn = new JButton("Sign In");
btnCancel = new JButton("Cancel");
// Actions
btnSignIn.addActionListener(this);
btnCancel.addActionListener(this);
// Adding objects to Panel
JPanel pnlPassword = new JPanel();
pnlPassword.add(btnSignIn);
pnlPassword.add(btnCancel);
JPanel detailsPanel = new JPanel();
detailsPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
GridBagConstraints gbc = new GridBagConstraints();
// Putting Objects into the grid
gbc.gridx = 0;
gbc.gridy = 0;
pnlUserSignIn.add(label, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
pnlUserSignIn.add(new JScrollPane(t), gbc);
gbc.gridx = 0;
gbc.gridy = 2;
pnlUserSignIn.add(pnlLogin, gbc);
gbc.gridx = 0;
gbc.gridy = 3;
gbc.gridwidth = 2;
pnlUserSignIn.add(pnlPassword, gbc);
// gbc.gridx = 1;
// gbc.gridy = 1;
// gbc.gridwidth = 1;
// gbc.gridheight = 2;
// panel.add(detailsPanel, gbc);
this.pack();
this.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent actionEvent) {
if (actionEvent.getSource() == btnCancel) {
System.exit(0);
}
// if(actionEvent.getSource()==txtUserName)
// {
// txtUserName.setText("");
// txtUserName.requestFocus();
// }
}
}
Related
im trying to make a Sudoku game and I want to change the background color of the same box, same column and same row when I click on a JTextField. I'm trying to add multiple Mouse Listener, one for each JTextField but It doesnt work. I'm now testing changing the background color of just the JTextField that I click on.
The main problem is in here.
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class Panel extends JPanel {
public static final int ROWS = 3;
public static final int COLUMNS = 3;
public static JTextField[][] fields = new JTextField[ROWS * COLUMNS][ROWS * COLUMNS];
for (int i = 0; i < ROWS*COLUMNS; i++) {
for (int j = 0; j < ROWS*COLUMNS; j++) {
fields[i][j] = new JTextField();
int finalI = i;
int finalJ = j;
fields[i][j].addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
fields[finalI][finalJ].setBackground(Color.BLUE);
}
});
}
}
}
I have also try with this but it doesn't work.
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class Panel extends JPanel {
public static final int ROWS = 3;
public static final int COLUMNS = 3;
public static JTextField[][] fields = new JTextField[ROWS * COLUMNS][ROWS * COLUMNS];
for (int i = 0; i < ROWS*COLUMNS; i++) {
for (int j = 0; j < ROWS*COLUMNS; j++) {
fields[i][j] = new JTextField();
addMouseActions(i, j);
}
}
private void addMouseActions(int row, int col){
fields[row][col].addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
fields[row][col].setBackground(Color.BLUE);
}
});
}
}
Here it's the full code that I have for the Panel class.
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class Panel extends JPanel {
static String[] levels = {"Easy", "Medium", "Hard"};
public static final JComboBox<String> levelsBox = new JComboBox<>(levels);
private final JButton playButton = new JButton("Play");
private final JButton checkButton = new JButton("Check");
private final JButton hintButton = new JButton("Hint");
private final JButton solveButton = new JButton("Solve");
private final JButton exitButton = new JButton("Exit");
public static final int ROWS = 3;
public static final int COLUMNS = 3;
public static JTextField[][] fields = new JTextField[ROWS * COLUMNS][ROWS * COLUMNS];
public Panel(JFrame frame) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(600, 200);
frame.setLayout(new BorderLayout());
frame.add(new SudokuBoard());
frame.add(new MenuPane(), BorderLayout.AFTER_LINE_ENDS);
frame.pack();
frame.setVisible(true);
}
});
}
public class MenuPane extends JPanel {
public MenuPane() {
setBorder(new EmptyBorder(4, 4, 4, 4));
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 1;
gbc.weightx = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
JLabel diff = new JLabel("Select the difficulty: ");
diff.setFont(new Font("SansSerif",Font.BOLD,18));
add(diff, gbc);
gbc.gridx++;
levelsBox.setFont(new Font("SansSerif",Font.BOLD,16));
add(levelsBox,gbc);
gbc.gridy++;
playButton.setActionCommand("Play");
add(playButton, gbc);
gbc.gridy++;
checkButton.setActionCommand("Check");
checkButton.setEnabled(false);
add(checkButton, gbc);
gbc.gridy++;
hintButton.setActionCommand("Hint");
hintButton.setEnabled(false);
add(hintButton, gbc);
gbc.gridy++;
solveButton.setActionCommand("Solve");
solveButton.setEnabled(false);
add(solveButton, gbc);
gbc.gridy++;
exitButton.setActionCommand("Exit");
add(exitButton, gbc);
}
}
public static class SudokuBoard extends JPanel {
private SubBoard[] subBoards;
public SudokuBoard() {
setBorder(new EmptyBorder(30, 30, 30, 10));
subBoards = new SubBoard[ROWS * COLUMNS];
setLayout(new GridLayout(ROWS, COLUMNS));
for (int row = 0; row < ROWS; row++) {
for (int col = 0; col < COLUMNS; col++) {
int bigIndex = (row * COLUMNS) + col;
int index = (row * ROWS) + col;
SubBoard board = new SubBoard(bigIndex);
board.setBorder(new LineBorder(Color.GRAY, 3));
subBoards[index] = board;
add(board);
}
}
}
}
public static class SubBoard extends JPanel {
public SubBoard(int bigIndex) {
setLayout(new GridLayout(ROWS, COLUMNS));
for (int row = 0; row < ROWS; row++) {
for (int col = 0; col < COLUMNS; col++) {
int index = (row * COLUMNS) + col;
JTextField field = new JTextField();
field.setPreferredSize(new Dimension(60, 60));
field.setHorizontalAlignment(JTextField.CENTER);
field.setFont(new Font("SansSerif", Font.BOLD, 25));
field.setDocument(new JTextFieldLimit(1));
//field.setEditable(false);
fields[bigIndex][index] = field;
add(field);
}
}
}
}
public void addListeners(Controller controller) {
playButton.addActionListener(controller);
checkButton.addActionListener(controller);
hintButton.addActionListener(controller);
solveButton.addActionListener(controller);
exitButton.addActionListener(controller);
for (int i = 0; i < ROWS*COLUMNS; i++) {
for (int j = 0; j < ROWS*COLUMNS; j++) {
fields[i][j] = new JTextField();
int finalI = i;
int finalJ = j;
fields[i][j].addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
fields[finalI][finalJ].setBackground(Color.BLUE);
}
});
}
}
}
public void enableButtons(boolean enabled){
checkButton.setEnabled(enabled);
hintButton.setEnabled(enabled);
solveButton.setEnabled(enabled);
}
}
And this is the Controller Class that I'm using for Actions Events.
import pkgClient.MyClient;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Objects;
public class Controller implements ActionListener {
Panel panel;
JFrame frame;
public Controller(Panel panel, JFrame frame) {
this.frame = frame;
this.panel = panel;
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equalsIgnoreCase("Play")){
String level = Panel.levelsBox.getItemAt(Panel.levelsBox.getSelectedIndex());
if(Objects.equals(level, "Easy")){
MyClient.out.println("easyMode");
}else if(Objects.equals(level, "Medium")){
MyClient.out.println("mediumMode");
}else if (Objects.equals(level, "Hard")){
MyClient.out.println("hardMode");
}
panel.enableButtons(true);
Panel.fields[0][0].setBackground(Color.WHITE);
} else if(e.getActionCommand().equalsIgnoreCase("Check")){
System.out.println("Comprobar");
MyClient.out.println("check");
panel.enableButtons(false);
}else if(e.getActionCommand().equalsIgnoreCase("Hint")){
System.out.println("Pista");
MyClient.out.println("hint");
} else if(e.getActionCommand().equalsIgnoreCase("Solve")){
System.out.println("Resolver");
MyClient.out.println("solve");
panel.enableButtons(false);
} else if(e.getActionCommand().equalsIgnoreCase("Exit")) {
frame.dispose();
MyClient.out.println("exit");
}else if(e.getActionCommand().equalsIgnoreCase("Text")) {
System.out.println("hola");
Panel.fields[0][0].setBackground(Color.BLACK);
}else{
System.err.println("Error: unexpected event");
}
}
}
Is there any way to set an unique Mouse Event to every single JTextField like I do with buttons and Actions in the Controller Class? Or how do I have to do it?
Thank you.
I finally could solve the problem, I just needed to use a FocusListener instead of a MouseListener. I can change the background color of a field int the FocusGained(FocusEvent event) method and each JTextField has an independent event. I can know which JTextField is being clicked with event.getComponent() inside of the FocusGained method.
I'm very new to JFrame, I was trying to enable and disable the JCheckbox (or) JCheckbox panel depends on radio button selection.
Here :
If "Yes" Radio button is selected JCheckboxs panel needs to be disabled and Textbox should be enabled.
If "No" Radio button is selected JCheckboxs needs to be enabled and Textbox should be disabled.
I can enable and disable the textbox but I don't know to control JCheckboxs
Here's my code
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashSet;
import java.util.Set;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private Set<String> selectedValues = new HashSet<>(8);
// JPanel panelCheckBox = new JPanel(new WrapLayout(WrapLayout.LEADING));
public TestPane() {
setBorder(new EmptyBorder(16, 16, 16, 16));
setLayout(new GridBagLayout());
JTextField textField = new JTextField(40);
JPanel panelCheckBox = new JPanel(new WrapLayout(WrapLayout.LEADING));
//testing start here
// DisabledPanel disabledPanel = new DisabledPanel(panelCheckBox);
// DisabledPanel disable = new DisabledPanel(panelCheckBox);
//disabledPanel.setEnabled(false);
JRadioButton yes = new JRadioButton("yes");
yes.setSelected(true);
yes.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (yes.isSelected()) {
textField.setEnabled(true);
panelCheckBox.setEnabled(false);
}
}
});
JRadioButton no = new JRadioButton("No");
no.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (no.isSelected()) {
textField.setText("");
textField.setEnabled(false);
}
}
});
ButtonGroup bg = new ButtonGroup();
bg.add(yes);
bg.add(no);
JPanel enterClassPane = new JPanel(new GridBagLayout());
enterClassPane.setBorder(new TitledBorder(null, "Enetr Your MetaClass", TitledBorder.LEADING, TitledBorder.TOP, null, null));
enterClassPane.add(yes);
enterClassPane.add(no);
// JPanel panelCheckBox = new JPanel(new WrapLayout(WrapLayout.LEADING));
//testing start here
// DisabledPanel disabledPanel = new DisabledPanel(panelCheckBox);
//disabledPanel.setEnabled(false);
int numberCheckBox = 10;
JCheckBox[] checkBoxList = new JCheckBox[numberCheckBox];
for (int i = 0; i < numberCheckBox; i++) {
checkBoxList[i] = new JCheckBox("Diagram " + i);
panelCheckBox.add(checkBoxList[i]);
checkBoxList[i].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Selected Diagram " + e.getActionCommand());
if (e.getSource() instanceof JCheckBox) {
JCheckBox cb = (JCheckBox) e.getSource();
if (cb.isSelected()) {
selectedValues.add(cb.getActionCommand());
} else {
selectedValues.remove(cb.getActionCommand());
}
}
}
});
}
JPanel classPane = new JPanel(new GridBagLayout());
classPane.setBorder(new TitledBorder(null, "Enter Meta Class", TitledBorder.LEADING, TitledBorder.TOP, null, null));
classPane.add(textField);
JPanel actionsPane = new JPanel(new GridBagLayout());
JButton btnCancel = new JButton("Cancel");
btnCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(1);
}
});
JButton btnOkay = new JButton("Okay");
btnOkay.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Text field
System.out.println(textField.getText());
for (String command : selectedValues) {
System.out.println(command);
}
}
});
actionsPane.add(btnOkay);
actionsPane.add(btnCancel);
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(4, 4, 4, 4);
gbc.gridwidth = gbc.REMAINDER;
gbc.fill = gbc.HORIZONTAL;
add(enterClassPane, gbc);
add(new JScrollPane(panelCheckBox), gbc);
add(classPane, gbc);
add(actionsPane, gbc);
}
}
public class WrapLayout extends FlowLayout {
private Dimension preferredLayoutSize;
public WrapLayout() {
super();
}
public WrapLayout(int align) {
super(align);
}
public WrapLayout(int align, int hgap, int vgap) {
super(align, hgap, vgap);
}
#Override
public Dimension preferredLayoutSize(Container target) {
return layoutSize(target, true);
}
#Override
public Dimension minimumLayoutSize(Container target) {
Dimension minimum = layoutSize(target, false);
minimum.width -= (getHgap() + 1);
return minimum;
}
private Dimension layoutSize(Container target, boolean preferred) {
synchronized (target.getTreeLock()) {
int targetWidth = target.getSize().width;
Container container = target;
while (container.getSize().width == 0 && container.getParent() != null) {
container = container.getParent();
}
targetWidth = container.getSize().width;
if (targetWidth == 0) {
targetWidth = Integer.MAX_VALUE;
}
int hgap = getHgap();
int vgap = getVgap();
Insets insets = target.getInsets();
int horizontalInsetsAndGap = insets.left + insets.right + (hgap * 2);
int maxWidth = targetWidth - horizontalInsetsAndGap;
// Fit components into the allowed width
Dimension dim = new Dimension(0, 0);
int rowWidth = 0;
int rowHeight = 0;
int nmembers = target.getComponentCount();
for (int i = 0; i < nmembers; i++) {
Component m = target.getComponent(i);
if (m.isVisible()) {
Dimension d = preferred ? m.getPreferredSize() : m.getMinimumSize();
// Can't add the component to current row. Start a new row.
if (rowWidth + d.width > maxWidth) {
addRow(dim, rowWidth, rowHeight);
rowWidth = 0;
rowHeight = 0;
}
// Add a horizontal gap for all components after the first
if (rowWidth != 0) {
rowWidth += hgap;
}
rowWidth += d.width;
rowHeight = Math.max(rowHeight, d.height);
}
}
addRow(dim, rowWidth, rowHeight);
dim.width += horizontalInsetsAndGap;
dim.height += insets.top + insets.bottom + vgap * 2;
Container scrollPane = SwingUtilities.getAncestorOfClass(JScrollPane.class, target);
if (scrollPane != null && target.isValid()) {
dim.width -= (hgap + 1);
}
return dim;
}
}
private void addRow(Dimension dim, int rowWidth, int rowHeight) {
dim.width = Math.max(dim.width, rowWidth);
if (dim.height > 0) {
dim.height += getVgap();
}
dim.height += rowHeight;
}
}
}
You will need to change some parts of your code:
Move numberCheckBox and checkBoxList as global variables inside TestPane, and rename numberCheckBox to NUMBER_CHECK_BOX as it will become a constant now, so your code should be looking like this
public class TestPane extends JPanel {
private static final int NUMBER_CHECK_BOX = 10;
JCheckBox[] checkBoxList = new JCheckBox[NUMBER_CHECK_BOX];
...
}
Now, create a method to toggle setEnabled(...) for each checkbox in the panel
private void toggleCheckBoxesEnabled(boolean enabled) {
for (JCheckBox box : checkBoxList) {
box.setEnabled(enabled);
}
}
And now just call it inside each of the buttons' actionListeners
yes.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (yes.isSelected()) {
textField.setEnabled(true);
toggleCheckBoxesEnabled(true);
}
}
});
no.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (no.isSelected()) {
textField.setText("");
textField.setEnabled(false);
toggleCheckBoxesEnabled(false);
}
}
});
And by the way, don't forget to call frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
How to disable the checkbox at initial itself
To disable them, you'll need to disable the checkboxes where you create them:
for (int i = 0; i < numberCheckBox; i++) {
checkBoxList[i] = new JCheckBox("Diagram " + i);
checkBoxList[i].setEnabled(false); // Add this line
panelCheckBox.add(checkBoxList[i]);
...
}
basically i am working on a tetris game and i want to implement a 2 player versus mode.
for now i have a working single player and now i want to make a gui for a 2 player multiplayer. (i will make a second keylistener and a endGame condition later)
however, when i add both gamepanels (what displays the state of the game after retreiving the state of the game from the boardhandler (1 or 2 depending on which player)) i dont get a correct display/gui.
this is what it looks like:
https://gyazo.com/58f37beab249c975cd4acdb8ae0e0154
this is what it should look like (but i want 2 boards displayed since this screenshot is from singleplayerwindow):
https://gyazo.com/4aecf061109844504a05387fb3d39e8f
anyone know what i am doing wrong and/or how i could fix it ?
thank you <3
package gui;
import tetris.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
public class MultiPlayerWindow extends JPanel
{
private GameLoop gameLoop1 ;
private GameLoop gameLoop2 ;
private boolean gameLoopHasStarted1 ;
private boolean gameLoopHasStarted2 ;
private BoardHandler bh1 ;
private BoardHandler bh2 ;
private HighScoreList highScoreList;
private HumanInput inputController ;
private HumanInput inputController2 ;
private JPanel scorePanel;
private JPanel rightPanel;
public MultiPlayerWindow( MainMenu mainMenu ){
//create the variables
Board board1 = new Board(10 , 20 ) ;
Board board2 = new Board(10 , 20 ) ;
final HumanInput inputController1 = new HumanInput() ;
final HumanInput inputController2 = new HumanInput() ;
this.bh1 = new BoardHandler(board1 , true) ;
this.bh2 = new BoardHandler(board2 , true) ;
this.highScoreList = new HighScoreList() ;
//behaviour
this.addKeyListener(inputController1);
this.addKeyListener(inputController2);
this.setFocusable(true);
this.requestFocusInWindow() ;
this.setLayout(new GridBagLayout());
//create panels
scorePanel = new JPanel() ;
scorePanel.setLayout(new GridBagLayout());
scorePanel.setSize(Config.LEFTPANEL_SIZE);
rightPanel = new JPanel() ;
rightPanel.setLayout(new GridBagLayout());
rightPanel.setSize(Config.RIGHTPANEL_SIZE);
//create the ScoreBoard
final ScoreBoard scoreBoard = new ScoreBoard() ;
GridBagConstraints d = new GridBagConstraints() ;
d.gridx = 0 ;
d.gridy = 0 ;
scorePanel.add(scoreBoard , d) ;
d.insets = new Insets(30,10,10,0);
//add a timer to update ScoreBoard
new Timer(1000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//System.out.println("Trying to update score");
scoreBoard.setScore(gameLoop1.getScore());
scoreBoard.setScore(gameLoop2.getScore());
}
}).start();
//create the Highscore Board
HighScoreBoard highScoreBoard = new HighScoreBoard(highScoreList);
d = new GridBagConstraints();
d.gridx = 0;
d.gridy = 1;
d.insets = new Insets(30,10,10,0);
scorePanel.add(highScoreBoard, d);
//create the combobox to choose between tetris and pentris
String[] optionStrings = {"Tetris", "Pentris"};
final JComboBox optionList = new JComboBox(optionStrings);
optionList.setSelectedIndex(0);
optionList.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(optionList.getSelectedIndex() == 0)
{
bh1.switchToTetris();
bh2.switchToTetris();
}
else if(optionList.getSelectedIndex() == 1)
{
bh1.switchToPentris();
bh2.switchToPentris();
}
}
});
optionList.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e) {
optionList.requestFocus();
}
#Override
public void focusLost(FocusEvent e) {
}
});
d = new GridBagConstraints();
d.gridx = 0;
d.gridy = 2;
d.weightx = 0.5;
d.insets = new Insets(30,10,10,0);
scorePanel.add(optionList, d);
//add the scorePanel
d = new GridBagConstraints();
d.gridx = 1;
d.gridy = 0;
this.add(scorePanel, d);
final GamePanel gamePanel1 = new GamePanel(board1);
final GamePanel gamePanel2 = new GamePanel(board2);
gamePanel1.setSize(Config.GAMEPANEL_SIZE);
gamePanel2.setSize(Config.GAMEPANEL_SIZE);
d = new GridBagConstraints();
d.gridx = 0;
d.gridy = 0;
this.add(gamePanel1, d);
d = new GridBagConstraints();
d.gridx = 2;
d.gridy = 0;
this.add(gamePanel2, d);
//set the Thread
gameLoop1 = new GameLoop(bh1, inputController1, gamePanel1, highScoreList);
gameLoop2 = new GameLoop(bh2, inputController2, gamePanel2, highScoreList);
gameLoop1.start();
gameLoop2.start();
gameLoopHasStarted1 = false;
gameLoopHasStarted2 = false;
//add the buttons
JPanel buttonPanel = new JPanel();
buttonPanel.setAlignmentX(30);
buttonPanel.setLayout(new GridLayout(3,1,10,10));
d = new GridBagConstraints();
d.gridx = 0;
d.weightx = 0.2;
d.gridy = 0;
d.insets = new Insets(200,20,0,20);
rightPanel.add(buttonPanel, d);
//backbutton
d = new GridBagConstraints();
d.gridx = 0;
d.gridy = 1;
d.anchor = GridBagConstraints.SOUTH;
d.insets = new Insets(20, 20, 0, 20);
rightPanel.add(new BackButton(mainMenu), d);
//add the right panel
d = new GridBagConstraints();
d.gridx = 3;
d.gridy = 0;
this.add(rightPanel, d);
final JButton startButton = new JButton("Start");
startButton.requestFocus(false);
startButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(!gameLoopHasStarted1 && !gameLoopHasStarted2)
{
try{
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run(){
gameLoopHasStarted1 = true;
gameLoopHasStarted2 = true;
gameLoop1.startNewGame();
gameLoop2.startNewGame();
optionList.setEnabled(false);
requestFocusInWindow();
startButton.setEnabled(false);
}
});
}
catch(Exception expenction)
{
expenction.printStackTrace();
}
}
}
});
buttonPanel.add(startButton);
//pause button
final JButton pauseButton = new JButton("Pause ");
buttonPanel.add(pauseButton);
pauseButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(!gameLoop1.isPaused() && !gameLoop2.isPaused()) {
gameLoop1.setPaused(true);
gameLoop2.setPaused(true);
pauseButton.setText("Unpause");
}
else if(gameLoop1.isPaused()&& gameLoop2.isPaused())
{
gameLoop1.setPaused(false);
gameLoop2.setPaused(false);
pauseButton.setText("Pause ");
}
}
});
//reset button
JButton resetButton = new JButton("Reset");
buttonPanel.add(resetButton);
resetButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
bh1.resetBoard();
bh2.resetBoard();
optionList.setEnabled(true);
if(gameLoop1.isRunning() && gameLoop2.isRunning())
{
gameLoop1.apruptGameEnd();
gameLoop2.apruptGameEnd();
}
gameLoopHasStarted1 = false;
gameLoopHasStarted2 = false;
gamePanel1.repaint();
gamePanel2.repaint();
startButton.setEnabled(true);
gameLoop1.setPaused(false);
gameLoop2.setPaused(false);
pauseButton.setText("Pause");
scoreBoard.setScore(0);
}
});
//focuslistener for inputController
this.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e) {
}
#Override
public void focusLost(FocusEvent e) {
requestFocusInWindow();
}
});
}
public Dimension getPreferredSize()
{
return Config.SINGLE_PLAYER_SIZE;
}
}
fixed it.
public Dimension getPreferredSize()
{
return Config.SINGLE_PLAYER_SIZE;
}
this last part was what was messing it up, the rest of the code works fine but was previously then (for some tbh unknown reason) messed up by this. not 100% sure why...
I am using SwingWorker class to make a process run in another thread. What I want is, once this thread has finished processing, it should return a String and also it should enable a JMenuItem. I am using the done() method in the SwingWorker class to enable the JMenuItem but I receive a NullPinterException. The doInBackground() method returns a String which I want to access in the main GUI class - GUIMain.java, present in the same package. How should I do that? I saw many examples which implement done() or onPostExecute() methods, but I think I am going wrong somewhere. Here is the code which I have implemented:
public class GUIMain extends JFrame implements ActionListener, FocusListener, ItemListener, MouseListener, MouseMotionListener {
private JMenuBar menuBar; // Defined a menuBar item
private JMenu recalibrationMenu; // Define the recalibration menu item
private JMenuItem CGMenuItem;
private JMenuItem TGMenuItem;
private JMenu viewResultsMenu; // Define the View Results menu item
public JMenuItem cgResults;
public JMenuItem tgResults;
private JPanel TGImage;
private JPanel TGPanel;
private JPanel CGImage;
private JPanel CGPanel;
private JPanel CGRecalibrationParameters;
private JDialog resultsParameters;
private JLabel massPeakLabel = new JLabel("Select mass peak (m/z)");
private JTextField massPeakField = new JTextField(5);
private JLabel massWindowLabel = new JLabel("Mass window (Da)");
private JTextField massWindowField = new JTextField(5);
private float mzPeakValue;
private float massWindowValue;
private JButton massPeakSelectionButton = new JButton("OK");
private JButton CloseDialogButton = new JButton("Cancel");
private String CGRecalibratedFilesPath;
private String TGRecalibratedFilesPath;
/** Constructor to setup the GUI */
public GUIMain(String title) {
super(title);
setLayout(new BorderLayout());
menuBar = new JMenuBar();
menuBar.setBorder(new BevelBorder(BevelBorder.RAISED));
// build the Recalibration menu
recalibrationMenu = new JMenu("Recalibration");
CGMenuItem = new JMenuItem("Crystal Growth");
CGMenuItem.setEnabled(false); //initially disabled when app is launched
CGMenuItem.addActionListener(this);
TGMenuItem = new JMenuItem("Topological Greedy");
TGMenuItem.setEnabled(false); //initially disabled when app is launched
TGMenuItem.addActionListener(this);
recalibrationMenu.add(CGMenuItem);
recalibrationMenu.add(TGMenuItem);
// build the View Results menu
viewResultsMenu = new JMenu("View Results");
cgResults = new JMenuItem("CG Recalibration");
cgResults.setEnabled(false); //initially disabled when app is launched
cgResults.addActionListener(this);
tgResults = new JMenuItem("TG Recalibration");
tgResults.setEnabled(false); //initially disabled when app is launched
tgResults.addActionListener(this);
viewResultsMenu.add(cgResults);
viewResultsMenu.add(tgResults);
// add menus to menubar
menuBar.add(fileMenu);
menuBar.add(recalibrationMenu);
menuBar.add(viewResultsMenu);
// put the menubar on the frame
setJMenuBar(menuBar);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Exit program if close-window button clicked
setPreferredSize(new Dimension(1300, 800)); // Set the preferred window size
pack();
setLocationRelativeTo(null);
setVisible(true);
}
public GUIMain()
{
}
}
public void actionPerformed(ActionEvent e) {
//Handle CG menu item action
**if ((e.getSource() == CGMenuItem)) {
RecalibrationWorker rw = new RecalibrationWorker(file,"CG");
rw.processCompleted();
rw.setVisible(true);
cgResults.setEnabled(true);
}**
if ((e.getSource() == cgResults)) {
viewRecalibrationResults("CG Recalibration - View Results", "CG");
}
if ((e.getSource() == tgResults)) {
viewRecalibrationResults("TG Recalibration - View Results", "TG");
}
}
private void viewRecalibrationResults(String dialogTitle, final String recalibrationType) {
resultsParameters = new JDialog();
resultsParameters.setLayout(new GridBagLayout());
resultsParameters.setTitle(dialogTitle);
GridBagConstraints gc = new GridBagConstraints();
gc.gridx = 0;
gc.gridy = 0;
gc.anchor = GridBagConstraints.WEST;
gc.ipady = 20;
// gc.anchor = GridBagConstraints.WEST;
resultsParameters.add(massPeakLabel, gc);
commonMassThresholdLabel.setLabelFor(massPeakField);
gc.gridx = 1;
gc.gridy = 0;
gc.ipady = 0;
gc.anchor = GridBagConstraints.CENTER;
resultsParameters.add(massPeakField,gc);
massPeakField.setText("");
massPeakField.addActionListener(this);
massPeakField.addFocusListener(this);
gc.gridx = 0;
gc.gridy = 1;
gc.ipady = 20;
gc.anchor = GridBagConstraints.WEST;
resultsParameters.add(massWindowLabel, gc);
massWindowLabel.setLabelFor(massWindowField);
gc.gridx = 1;
gc.gridy = 1;
gc.ipady = 0;
gc.anchor = GridBagConstraints.CENTER;
resultsParameters.add(massWindowField,gc);
massWindowField.setText("");
massWindowField.addActionListener(this);
massWindowField.addFocusListener(this);
gc.gridx = 0;
gc.gridy = 2;
gc.anchor = GridBagConstraints.CENTER;
resultsParameters.add(massPeakSelectionButton, gc);
massPeakSelectionButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if ("CG".equals(recalibrationType))
recalibrationResults("CG");
else if ("TG".equals(recalibrationType))
recalibrationResults("TG");
}
});
massPeakSelectionButton.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
if ("CG".equals(recalibrationType))
recalibrationResults("CG");
else if ("TG".equals(recalibrationType))
recalibrationResults("TG");
}
}
#Override
public void keyReleased(KeyEvent e) {
}
});
gc.gridx = 1;
gc.gridy = 2;
gc.anchor = GridBagConstraints.EAST;
resultsParameters.add(CloseDialogButton,gc);
CloseDialogButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
resultsParameters.dispose();
}
});
resultsParameters.setVisible(true);
resultsParameters.setLocationRelativeTo(this);
resultsParameters.setSize(270, 150);
resultsParameters.setResizable(false);
}
}
public class RecalibrationWorker extends JDialog {
private boolean isStarted = false;
private JLabel counterLabel = new JLabel("Recalibration not yet started");
private Worker worker = new Worker();
private JPanel recalibrationParameters;
private ButtonGroup radioButtonGroup = new ButtonGroup();
private JRadioButton rawSpectra = new JRadioButton("Use raw spectra");
private JRadioButton preprocessedSpectra = new JRadioButton("Use preprocessed spectra");
private static float commonMassThresholdValue;
private static float recalibrationThresholdValue;
private static double mergeSpectraThresholdValue;
private JLabel commonMassThresholdLabel = new JLabel("<html>Common Mass Window<br>(value between 0.01-0.9 Da)</html>");
private JTextField commonMassThresholdField = new JTextField(String.valueOf(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
commonMassThresholdValue = Float.parseFloat(commonMassThresholdField.getText());
recalibrationThresholdField.requestFocusInWindow();
}
}));
private JLabel recalibrationThresholdLabel = new JLabel("<html>Mass threshold to recalibrate two spectra<br>(value between 0.01-0.9 Da)</html>");
private JTextField recalibrationThresholdField = new JTextField(String.valueOf(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
recalibrationThresholdValue = Float.parseFloat(recalibrationThresholdField.getText());
mergeSpectraThresholdField.requestFocusInWindow();
}
}));
private JLabel mergeSpectraThresholdLabel = new JLabel("<html>Mass threshold to merge spectra<br>(value between 0.01-0.9 Da)</html>");
private JTextField mergeSpectraThresholdField= new JTextField(String.valueOf(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
mergeSpectraThresholdValue = Float.parseFloat(mergeSpectraThresholdField.getText());
startButton.requestFocusInWindow();
}
}));
private JTextArea recalibrationStatus = new JTextArea(7,32);
private JScrollPane textAreaScrolling = new JScrollPane(recalibrationStatus);
private JButton startButton = new JButton(new AbstractAction("Recalibrate") {
#Override
public void actionPerformed(ActionEvent arg0) {
if(!isStarted) {
Worker w = new Worker();
w.addPropertyChangeListener(new RecalibrationWorkerPropertyHandler(RecalibrationWorker.this));
w.execute();
isStarted = false;
}
}
});
private JButton stopButton = new JButton(new AbstractAction("Stop") {
#Override
public void actionPerformed(ActionEvent arg0) {
worker.cancel(true);
}
});
public File file;
public String type;
public String resultFilePath;
public RecalibrationWorker(File dataFile, String recalibrationType) {
file = dataFile;
type = recalibrationType;
setLayout(new GridBagLayout());
if("CG".equals(recalibrationType))
setTitle("Crystal Growth Recalibration");
else if("TG".equals(recalibrationType))
setTitle("Topological Greedy Recalibration");
recalibrationParameters = new JPanel(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
radioButtonGroup.add(rawSpectra);
radioButtonGroup.add(preprocessedSpectra);
gc.gridx = 0;
gc.gridy = 0;
gc.anchor = GridBagConstraints.WEST;
recalibrationParameters.add(preprocessedSpectra,gc);
gc.gridx = 1;
gc.gridy = 0;
recalibrationParameters.add(rawSpectra,gc);
gc.gridx = 0;
gc.gridy = 1;
gc.ipady = 20;
gc.anchor = GridBagConstraints.WEST;
recalibrationParameters.add(commonMassThresholdLabel, gc);
commonMassThresholdLabel.setLabelFor(commonMassThresholdField);
commonMassThresholdField.setColumns(3);
commonMassThresholdField.setText("");
gc.gridx = 1;
gc.gridy = 1;
gc.ipady = 0;
gc.anchor = GridBagConstraints.CENTER;
recalibrationParameters.add(commonMassThresholdField, gc);
commonMassThresholdField.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e) {
}
#Override
public void focusLost(FocusEvent e) {
commonMassThresholdValue = Float.parseFloat(commonMassThresholdField.getText());
recalibrationThresholdField.requestFocusInWindow();
}
});
gc.gridx = 0;
gc.gridy = 2;
gc.ipady = 20;
gc.anchor = GridBagConstraints.WEST;
recalibrationParameters.add(recalibrationThresholdLabel, gc);
recalibrationThresholdLabel.setLabelFor(recalibrationThresholdField);
recalibrationThresholdField.setColumns(3);
recalibrationThresholdField.setText("");
gc.gridx = 1;
gc.gridy = 2;
gc.ipady = 0;
gc.anchor = GridBagConstraints.CENTER;
recalibrationParameters.add(recalibrationThresholdField, gc);
recalibrationThresholdField.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e) {
}
#Override
public void focusLost(FocusEvent e) {
recalibrationThresholdValue = Float.parseFloat(recalibrationThresholdField.getText());
mergeSpectraThresholdField.requestFocusInWindow();
}
});
gc.gridx = 0;
gc.gridy = 3;
gc.ipady = 20;
gc.anchor = GridBagConstraints.WEST;
recalibrationParameters.add(mergeSpectraThresholdLabel, gc);
mergeSpectraThresholdLabel.setLabelFor(mergeSpectraThresholdField);
mergeSpectraThresholdField.setText("");
gc.gridx = 1;
gc.gridy = 3;
gc.ipady = 0;
gc.anchor = GridBagConstraints.CENTER;
recalibrationParameters.add(mergeSpectraThresholdField, gc);
mergeSpectraThresholdField.setColumns(3);
mergeSpectraThresholdField.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e) {
}
#Override
public void focusLost(FocusEvent e) {
mergeSpectraThresholdValue = Double.parseDouble(mergeSpectraThresholdField.getText());
startButton.requestFocusInWindow();
}
});
recalibrationParameters.setBorder(
BorderFactory.createCompoundBorder(
BorderFactory.createTitledBorder("Parameters"),
BorderFactory.createEmptyBorder(5, 5, 5, 5)));
gc.gridx = 0;
gc.gridy = 4;
gc.anchor = GridBagConstraints.EAST;
recalibrationParameters.add(startButton, gc);
gc.gridx = 1;
gc.gridy = 4;
gc.anchor = GridBagConstraints.WEST;
recalibrationParameters.add(stopButton, gc);
gc.gridx = 0;
gc.gridy = 0;
gc.anchor = GridBagConstraints.CENTER;
add(recalibrationParameters, gc);
textAreaScrolling.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createTitledBorder("Recalibration status"),
BorderFactory.createEmptyBorder(5, 5, 5, 5)));
gc.gridx = 0;
gc.gridy = 1;
gc.anchor = GridBagConstraints.CENTER;
add(textAreaScrolling, gc);
recalibrationStatus.setWrapStyleWord(true);
recalibrationStatus.setLineWrap(true);
recalibrationStatus.setEditable(false);
setVisible(true);
setLocationRelativeTo(this);
setSize(415, 425);
setResizable(false);
pack();
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
// constructor
public RecalibrationWorker()
{
}
public float commonMassThreshold() {
return commonMassThresholdValue;
}
public float recalibrationThreshold() {
return recalibrationThresholdValue;
}
public double mergeSpectraThreshold() {
return mergeSpectraThresholdValue;
}
protected String processCompleted() {
return resultFilePath;
}
protected void processFailed() {
System.out.println("Recalibration failed");
}
class Worker extends SwingWorker<String,String> {
// String resultfilePath;
#Override
public String doInBackground() throws Exception {
InputData inputDataObject1 = new InputData();
if(type == "CG")
{
resultFilePath = inputDataObject1.startRecalibration(file, type);
publish("Recalibration Successful!\nFiles can be found at: " + resultFilePath);
}
else if (type == "TG")
{
resultFilePath = inputDataObject1.startRecalibration(file, type);
publish("Recalibration Successful!\nFiles can be found at: " + resultFilePath);
}
return resultFilePath;
}
public void done() {
try {
get();
} catch (Exception e) {
}
}
#Override
protected void process(java.util.List<String> chunks) {
String value = chunks.get(chunks.size() - 1);
recalibrationStatus.append("\n"+value);
// recalibrationStatus.append(chunks.toString());
}
}
import javax.swing.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.concurrent.ExecutionException;
/**
* Created by localadm on 27/09/15.
*/
public class RecalibrationWorkerPropertyHandler implements PropertyChangeListener {
private RecalibrationWorker rwObject;
public RecalibrationWorkerPropertyHandler(RecalibrationWorker rwObject) {
this.rwObject = rwObject;
}
#Override
public void propertyChange(PropertyChangeEvent evt) {
// System.out.println(evt.getPropertyName());
if ("progress".equalsIgnoreCase(evt.getPropertyName())) {
// int value = (int) evt.getNewValue();
// rwObject.showProgress(value);
} else if ("state".equalsIgnoreCase(evt.getPropertyName())) {
SwingWorker worker = (SwingWorker) evt.getSource();
if (worker.isDone()) {
try {
worker.get();
System.out.println("I am here");
rwObject.processCompleted();
} catch (InterruptedException exp) {
rwObject.processFailed();
} catch (ExecutionException e) {
rwObject.processFailed();
}
}
}
}
}
Since you're using a JDialog to manage the SwingWorker, you can actual use the modal state of the dialog to you advantage.
Essentially, when a dialog is modal, it will block the code execution where the dialog is made visible. It will block until the dialog is hidden, at which time, the code will continue to execute.
So, you can disable the button before the dialog is made visible and re-enable it when it's closed.
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
JButton btn = new JButton("Go");
add(btn);
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
btn.setEnabled(false);
SomeWorkerDialog worker = new SomeWorkerDialog(TestPane.this);
// This is just so we can see the button ;)
Point point = btn.getLocationOnScreen();
worker.setLocation(worker.getX(), point.y + btn.getHeight());
worker.setVisible(true);
btn.setEnabled(true);
}
});
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
public class SomeWorkerDialog extends JDialog {
private JProgressBar progressBar;
private SomeWorkerSomeWhere worker;
public SomeWorkerDialog(JComponent parent) {
super(SwingUtilities.getWindowAncestor(parent), "Working Hard", DEFAULT_MODALITY_TYPE);
progressBar = new JProgressBar();
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1;
gbc.insets = new Insets(10, 10, 10, 10);
add(progressBar, gbc);
worker = new SomeWorkerSomeWhere();
worker.addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent evt) {
String name = evt.getPropertyName();
switch (name) {
case "state":
switch (worker.getState()) {
case DONE:
setVisible(false);
break;
}
break;
case "progress":
progressBar.setValue(worker.getProgress());
break;
}
}
});
addWindowListener(new WindowAdapter() {
#Override
public void windowOpened(WindowEvent e) {
worker.execute();
}
#Override
public void windowClosed(WindowEvent e) {
worker.cancel(true);
}
});
pack();
setLocationRelativeTo(parent);
}
}
public class SomeWorkerSomeWhere extends SwingWorker {
#Override
protected Object doInBackground() throws Exception {
for (int index = 0; index < 100 && !isCancelled(); index++) {
setProgress(index);
Thread.sleep(10);
}
return "AllDone";
}
}
}
Update
To get the value returned by the worked, you can add a method to the dialog which returns the calculated value...
public String getValue() throws Exception {
return worker.get()
}
So, once the dialog is closed and the execution of your code continues, you can enable the components you want and call the getValue method
You can also store the result when the state changes and the PropertyChangeListener is notified
The purpose of this program is to allow the tutor to keep a log of his/her students. I'm a newbie to GUI so my code probably isnt the best but I need help with the code for the JButton "SAVE" to take all the information in the log and store it in a .txt file. Line 374 is where my button command is.
import java.awt.BorderLayout;
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.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
public class MainGUI extends JFrame {
// Declare variables:
// array lists
String[] columnNames = {"ID", "NAME", "COURSE", "Professor", "Reason for Tutor"};
Object[][] data = new Object[25][5];
// table
JTable table = new JTable(data, columnNames) {
// sets the ability of the cells to be edited by the user
#Override
public boolean isCellEditable(int row, int column) {
return false; // returns false, cannot be edited
}
};
// frames
JFrame frame, frame1;
// panels
JPanel buttonPanel, buttonPanel2, tablePanel, addPanel, editPanel;
// labels
JLabel labelID, labelName, labelCourse, labelProfessor, labelHelp;
// text fields
JTextField txtID, txtName, txtCourse, txtProfessor, txtHelp;
// buttons
JButton btnAdd, btnEdit, btnDelete, btnSort, btnSave, btnAddInput, btnCancel;
// additionals
int keyCode, rowIndex, rowNumber, noOfStudents;
// button handler
MainGUI.ButtonHandler bh = new MainGUI.ButtonHandler();
public MainGUI() {
// setting/modifying table components
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.getSelectionModel().addListSelectionListener(new MainGUI.RowListener());
table.getColumnModel().getColumn(1).setPreferredWidth(200);
table.getColumnModel().getColumn(3).setPreferredWidth(100);
table.getColumnModel().getColumn(4).setPreferredWidth(200);
table.getTableHeader().setResizingAllowed(false);
table.getTableHeader().setReorderingAllowed(false);
JScrollPane scrollPane = new JScrollPane(table);
// main buttons
btnAdd = new JButton("ADD");
btnAdd.addActionListener(bh);
btnEdit = new JButton("EDIT");
btnEdit.addActionListener(bh);
btnEdit.setEnabled(false); // disables the component
btnDelete = new JButton("DELETE");
btnDelete.addActionListener(bh);
btnDelete.setEnabled(false); // disables the component
btnSort = new JButton("SORT");
btnSort.addActionListener(bh);
btnSave = new JButton("SAVE");
btnSave.addActionListener(bh);
btnSave.setActionCommand("Save");
// with button Listeners
// sub buttons
btnAddInput = new JButton("Add");
btnAddInput.addActionListener(bh);
btnAddInput.setActionCommand("AddInput");
btnCancel = new JButton("Cancel");
btnCancel.addActionListener(bh);
// set label names
labelID = new JLabel("ID");
labelName = new JLabel("NAME");
labelCourse = new JLabel("COURSE");
labelProfessor = new JLabel("Professor");
labelHelp = new JLabel("Reason for Tutoring");
// set text fields width
txtID = new JTextField(20);
txtName = new JTextField(20);
txtCourse = new JTextField(20);
txtProfessor = new JTextField(20);
txtHelp = new JTextField(20);
txtID.setDocument(new MainGUI.JTextFieldLimit(15)); // limits the length of input:
// max of 15
txtID.addKeyListener(keyListener); // accepts only numerals
// main frame
// panel for the table
tablePanel = new JPanel();
tablePanel.setLayout(new BoxLayout(tablePanel, BoxLayout.PAGE_AXIS));
tablePanel.setBorder(BorderFactory.createEmptyBorder(10, 2, 0, 10));
tablePanel.add(table.getTableHeader());
tablePanel.add(table);
// panel for the main buttons
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
// positions the main buttons
c.gridx = 0;
c.gridy = 0;
c.ipady = 20;
c.insets = new Insets(10, 10, 10, 10);
c.fill = GridBagConstraints.HORIZONTAL;
buttonPanel.add(btnAdd, c);
c.gridx = 0;
c.gridy = 1;
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 20;
c.insets = new Insets(10, 10, 10, 10);
buttonPanel.add(btnEdit, c);
c.gridx = 0;
c.gridy = 2;
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 20;
c.insets = new Insets(10, 10, 10, 10);
buttonPanel.add(btnDelete, c);
c.gridx = 0;
c.gridy = 3;
c.ipady = 20;
c.insets = new Insets(10, 10, 10, 10);
c.fill = GridBagConstraints.HORIZONTAL;
buttonPanel.add(btnSort, c);
c.gridx = 0;
c.gridy = 4;
c.ipady = 20;
c.insets = new Insets(10, 10, 10, 10);
c.fill = GridBagConstraints.HORIZONTAL;
buttonPanel.add(btnSave, c);
frame = new JFrame("Student Database");
frame.setVisible(true);
frame.setResizable(false);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.add(tablePanel, BorderLayout.CENTER);
frame.add(buttonPanel, BorderLayout.EAST);
frame.pack();
// ADD frame
// panel for adding
addPanel = new JPanel();
addPanel.setLayout(new GridBagLayout());
// positions the components for adding
// labels
c.insets = new Insets(1, 0, 1, 1);
c.gridx = 0;
c.gridy = 0;
addPanel.add(labelID, c);
c.gridy = 1;
addPanel.add(labelName, c);
c.gridy = 2;
addPanel.add(labelCourse, c);
c.gridy = 3;
addPanel.add(labelProfessor, c);
c.gridy = 4;
addPanel.add(labelHelp, c);
// text fields
c.gridx = 1;
c.gridy = 0;
c.ipady = 1;
addPanel.add(txtID, c);
c.gridy = 1;
c.ipady = 1;
addPanel.add(txtName, c);
c.gridy = 2;
c.ipady = 1;
addPanel.add(txtCourse, c);
c.gridy = 3;
c.ipady = 1;
addPanel.add(txtProfessor, c);
c.gridy = 4;
c.ipady = 1;
addPanel.add(txtHelp, c);
// panel for other necessary buttons
buttonPanel2 = new JPanel();
buttonPanel2.setLayout(new GridLayout(1, 1));
buttonPanel2.add(btnAddInput);
buttonPanel2.add(btnCancel);
frame1 = new JFrame("Student Database");
frame1.setVisible(false);
frame1.setResizable(false);
frame1.setDefaultCloseOperation(HIDE_ON_CLOSE);
frame1.add(addPanel, BorderLayout.CENTER);
frame1.add(buttonPanel2, BorderLayout.PAGE_END);
frame1.pack();
}// end
KeyListener keyListener = new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
keyCode = e.getKeyCode();
if (!(keyCode >= 48 && keyCode <= 57) && !(keyCode >= 96 && keyCode <= 105)
&& !(keyCode >= 37 && keyCode <= 40) && !(keyCode == 127 || keyCode == 8)) {
txtID.setEditable(false);
}
}
#Override
public void keyReleased(KeyEvent e) {
txtID.setEditable(true);
}
};
class RowListener implements ListSelectionListener {
#Override
public void valueChanged(ListSelectionEvent event) {
if (event.getValueIsAdjusting()) {
rowIndex = table.getSelectedRow();
if (data[rowIndex][0] == null || data[rowIndex][0] == "") {
btnEdit.setEnabled(false);
btnDelete.setEnabled(false);
} else {
btnEdit.setEnabled(true);
btnDelete.setEnabled(true);
}
}
}
}// end
class ButtonHandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("ADD")) {
// text fields for Student input data
txtID.setText("");
txtName.setText("");
txtCourse.setText("");
txtProfessor.setText("");
txtHelp.setText("");
frame1.setTitle("Add Student data"); // title bar name for add
frame1.setVisible(true);
} else if (e.getActionCommand().equals("EDIT")) {
txtID.setText(data[rowIndex][0] + ""); // will preview the ID
// input during Add
txtName.setText(data[rowIndex][1] + ""); // will preview the Name
// input during Add
txtCourse.setText(data[rowIndex][2] + ""); // will preview the
// Course input during
// Add
txtProfessor.setText(data[rowIndex][3] + ""); // will preview the Year
// input during Add
txtHelp.setText(data[rowIndex][4] + ""); // will preview the
// Gender input during
// Add
txtID.setEditable(false); // forbids the user to edit the entered
// ID number
frame1.setTitle("Edit Student data"); // title bar name for edit
btnAddInput.setActionCommand("Edit2");
btnAddInput.setText("ACCEPT");
frame1.setVisible(true); // sets the visibility of frame1
} else if (e.getActionCommand().equals("DELETE")) {
int confirm = JOptionPane.showConfirmDialog(frame, "ARE YOU SURE?", "CONFIRM",
JOptionPane.YES_NO_OPTION);
if (confirm == 0) {
rowIndex = table.getSelectedRow();
rowNumber = 0;
noOfStudents--;
for (int i = 0; i <= 10; i++) {
if (rowIndex != i && i <= noOfStudents) {
data[rowNumber][0] = data[i][0];
data[rowNumber][1] = data[i][1];
data[rowNumber][2] = data[i][2];
data[rowNumber][3] = data[i][3];
data[rowNumber][4] = data[i][4];
rowNumber++;
} else if (rowIndex != i && i > noOfStudents) {
data[rowNumber][0] = "";
data[rowNumber][1] = "";
data[rowNumber][2] = "";
data[rowNumber][3] = "";
data[rowNumber][4] = "";
rowNumber++;
}
}
if (noOfStudents == 1000) {
btnAdd.setEnabled(false);
}
else {
btnAdd.setEnabled(true);
}
if (noOfStudents == 0) {
btnDelete.setEnabled(false);
btnEdit.setEnabled(false);
} else {
btnDelete.setEnabled(true);
btnEdit.setEnabled(true);
}
rowIndex = table.getSelectedRow();
if (data[rowIndex][0] == null || data[rowIndex][0] == "") {
btnEdit.setEnabled(false);
btnDelete.setEnabled(false);
} else {
btnEdit.setEnabled(true);
btnDelete.setEnabled(true);
}
table.updateUI();
}
} else if (e.getActionCommand().equals("AddInput")) {
if (txtID.getText().isEmpty() || txtName.getText().isEmpty()
|| txtCourse.getText().isEmpty()// /
|| txtProfessor.getText().isEmpty() || txtHelp.getText().isEmpty()) {
JOptionPane.showMessageDialog(null, "PLEASE FILL IN THE BLANKS.", "ERROR!",
JOptionPane.ERROR_MESSAGE);
}
else {
int dup = 0;
for (int i = 0; i < 10; i++) {
if (txtID.getText().equals(data[i][0])) {
JOptionPane.showMessageDialog(null, "ID NUMBER ALREADY EXISTS.", "ERROR!",
JOptionPane.ERROR_MESSAGE);
dup++;
}
}
if (dup == 0) {
rowIndex = table.getSelectedRow();
data[noOfStudents][0] = txtID.getText();
data[noOfStudents][1] = txtName.getText();
data[noOfStudents][2] = txtCourse.getText();
data[noOfStudents][3] = txtProfessor.getText();
data[noOfStudents][4] = txtHelp.getText();
table.updateUI();
frame1.dispose();
noOfStudents++;
if (noOfStudents == 50){
btnAdd.setEnabled(false);
}
else {
btnAdd.setEnabled(true);
}
if (data[rowIndex][0] == null) {
btnEdit.setEnabled(false);
btnDelete.setEnabled(false);
} else {
btnEdit.setEnabled(true);
btnDelete.setEnabled(true);
}
}
}
table.updateUI();
}else if(e.getActionCommand().equals("Save")){
try {
PrintWriter out = new PrintWriter("filename.txt");
out.println(txtID.getText());
out.println(txtName.getText());
out.println(txtCourse.getText());
out.println(txtProfessor.getText());
out.println(txtHelp.getText());
} catch (FileNotFoundException ex) {
}
}else if (e.getActionCommand().equals("Edit2")) {
if (txtID.getText().isEmpty() || txtName.getText().isEmpty()
|| txtCourse.getText().isEmpty() || txtProfessor.getText().isEmpty()
|| txtHelp.getText().isEmpty()) {
JOptionPane.showMessageDialog(null, "INCOMPLETE INPUT.", "ERROR!",
JOptionPane.ERROR_MESSAGE);
} else {
data[rowIndex][0] = txtID.getText();
data[rowIndex][1] = txtName.getText();
data[rowIndex][2] = txtCourse.getText();
data[rowIndex][3] = txtProfessor.getText();
data[rowIndex][4] = txtHelp.getText();
frame1.dispose();
}
table.updateUI();
} else if (e.getActionCommand().equals("Cancel")) {
frame1.dispose();
}
}
}// end
class JTextFieldLimit extends PlainDocument {
private int limit;
JTextFieldLimit(int limit) {
super();
this.limit = limit;
}
JTextFieldLimit(int limit, boolean upper) {
super();
this.limit = limit;
}
#Override
public void insertString(int offset, String str, AttributeSet attr)
throws BadLocationException {
if (str == null) {
return;
}
if ((getLength() + str.length()) <= limit) {
super.insertString(offset, str, attr);
}
}
}
public static void main(String[] args) {
new MainGUI();
}
}
You need to call flush() method once at the end of printing content to file.
Like,
else if(e.getActionCommand().equals("Save")){
try {
PrintWriter out = new PrintWriter("filename.txt");
out.println(txtID.getText());
out.println(txtName.getText());
out.println(txtCourse.getText());
out.println(txtProfessor.getText());
out.println(txtHelp.getText());
out.flush();
} catch (FileNotFoundException ex) {
}
}
The java.io.Writer.flush() method flushes the stream. If the stream has saved any characters from the various write() methods in a buffer, write them immediately to their intended destination. Then, if that destination is another character or byte stream, flush it. Thus one flush() invocation will flush all the buffers in a chain of Writers and OutputStreams.
The print method will call write method in class PrintWriter, piece of source code is as follows:
/**
* Prints a String and then terminates the line. This method behaves as
* though it invokes <code>{#link #print(String)}</code> and then
* <code>{#link #println()}</code>.
*
* #param x the <code>String</code> value to be printed
*/
public void println(String x) {
synchronized (lock) {
print(x);
println();
}
}
We can see in print() method, it will call write() method.
/**
* Prints a string. If the argument is <code>null</code> then the string
* <code>"null"</code> is printed. Otherwise, the string's characters are
* converted into bytes according to the platform's default character
* encoding, and these bytes are written in exactly the manner of the
* <code>{#link #write(int)}</code> method.
*
* #param s The <code>String</code> to be printed
*/
public void print(String s) {
if (s == null) {
s = "null";
}
write(s);
}