JLabel alignment issues - java

So, I have a problem. I have a JPanel(BoxLayout, Y_AXIS). In it, I have JLabel, and JTextArea. JTextArea expands freely as I fill it with text, expanding the JPanel with it.
JLabel expands to. That is okay as long the text is vertically aligned to the top. But that command doesn't work for some reason (setVerticalTextPosition, setVerticalAlignment, setAlignmentX). I think the first one is acctually a bug within Java.
Since that didn't work, I tried glueing JLabel to the top border.
I have also set all three setXXSize to sam value to keep the size of JLabel constant.
But it just wont stick, depending on the layout it either snaps to the center or just fills the whole JPanel.
Now, I don't care how, but all I need is a couple of letters that are top-aligned in the space occupied with JLabel (I can even use another JTextComponent, if it will make any difference). Is there a way to do that?
I'd provide you with code, but it's pretty much what I have written above, and since the JPanel is a part of more complex GUI, I'd really have to give you the whole code...
(Which I will, if it will be needed.)
package core;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Properties;
import java.util.ResourceBundle;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.border.Border;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
#SuppressWarnings("serial")
class DefaultFont extends Font
{
public DefaultFont()
{
super("Arial", PLAIN, 20);
}
}
#SuppressWarnings("serial")
class Page extends JPanel
{
public JPanel largePage;
public int content;
public Page(JPanel panel, int index)
{
largePage = new JPanel();
largePage.setLayout(new BoxLayout(largePage, BoxLayout.Y_AXIS));
largePage.setMaximumSize(new Dimension(794, 1123));
largePage.setPreferredSize(new Dimension(794, 1123));
largePage.setAlignmentX(Component.CENTER_ALIGNMENT);
largePage.setBackground(Color.WHITE);
largePage.add(new Box.Filler(new Dimension(0, 96), new Dimension(0, 96), new Dimension(0, 96)));
setMaximumSize(new Dimension(556, 931));
setBackground(Color.LIGHT_GRAY);
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
add(new Box.Filler(new Dimension(556, 0), new Dimension(556, 931), new Dimension(556, 931)));
largePage.add(this);
largePage.add(new Box.Filler(new Dimension(0, 96), new Dimension(0, 96), new Dimension(0, 96)));
panel.add(largePage, index);
panel.add(new Box.Filler(new Dimension(0, 40), new Dimension(0, 40), new Dimension(0, 40)));
content = 0;
Main.pages.add(this);
}
}
#SuppressWarnings("serial")
class Heading extends JTextArea
{
public boolean type;
public AbstractDocument doc;
public ArrayList<JPanel/*Question*/> questions;
public ArrayList<JPanel/*List*/> list;
public Heading(boolean segment, Page page)
{
type = segment;
setBackground(Color.RED);
setFont(new Font("Arial", Font.BOLD, 20));
Border in = BorderFactory.createDashedBorder(Color.BLACK);
Border out = BorderFactory.createMatteBorder(0, 0, 10, 0, Color.WHITE);
setBorder(BorderFactory.createCompoundBorder(out, in));
setLineWrap(true);
setWrapStyleWord(true);
setText("Heading 1 Heading 1 Heading 1 Heading 1");
doc = (AbstractDocument)this.getDocument();
doc.setDocumentFilter(new DocumentFilter()
{
public void insertString(FilterBypass fb, int offs,String str, AttributeSet a) throws BadLocationException
{
if ((fb.getDocument().getLength() + str.length()) <= 150)
{
;
fb.insertString(offs, str.replaceAll("\n", " "), a);
}
else
{
int spaceLeft = 150 - fb.getDocument().getLength();
if (spaceLeft <= 0)
return;
fb.insertString(offs, str.substring(0,spaceLeft).replaceAll("\n", " "), a);
}
}
public void replace(FilterBypass fb, int offs, int length, String str, AttributeSet a) throws BadLocationException
{
if (str.equals("\n"))
{
str = "";
}
if ((fb.getDocument().getLength() + str.length() - length) <= 150)
{
fb.replace(offs, length, str.replaceAll("\n", " "), a);
}
else
{
int spaceLeft = 150 - fb.getDocument().getLength() + length;
if (spaceLeft <= 0)
return;
fb.replace(offs, length, str.substring(0,spaceLeft).replaceAll("\n", " "), a);
}
}
});
page.add(this, 0);
page.content++;
if (type)
{
questions = new ArrayList<JPanel>();
}
else
{
list = new ArrayList<JPanel>();
}
}
}
#SuppressWarnings("serial")
class Question extends JPanel
{
public JPanel questionArea, numberArea, answerArea;
public JLabel number;
public JTextArea question;
public Question(Page page, int pageNum, int index)
{
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
questionArea = new JPanel();
questionArea.setLayout(new BoxLayout(questionArea, BoxLayout.X_AXIS));
numberArea = new JPanel();
numberArea.setLayout(new BoxLayout(numberArea, BoxLayout.Y_AXIS));
numberArea.setBackground(Color.YELLOW);
number = new JLabel(pageNum+".", JLabel.RIGHT);
number.setMinimumSize(new Dimension(100, 20));
number.setPreferredSize(new Dimension(100, 20));
number.setMaximumSize(new Dimension(100, 20));
//number.setAlignmentX(TOP_ALIGNMENT);
number.setFont(new Font("Arial", Font.PLAIN, 18));
number.setBackground(Color.BLUE);
numberArea.add(number);
//numberArea.add(new Box.Filler(new Dimension(40, 0), new Dimension(40, 30), new Dimension(40, 300)), BorderLayout.CENTER);
questionArea.add(numberArea);
question = new JTextArea();
question.setFont(new Font("Arial", Font.PLAIN, 18));
question.setLineWrap(true);
question.setWrapStyleWord(true);
question.setBackground(Color.GREEN);
question.setText("dafd afdfd fasdfsdaah fg dfgd");
questionArea.add(question);
add(questionArea);
page.add(this, index);
}
}
public class Main
{
public static Properties config;
public static Locale currentLocale;
public static ResourceBundle lang;
public static JFrame mWindow;
public static JMenuBar menu;
public static JMenu menuFile, menuEdit;
public static JMenuItem itmNew, itmClose, itmLoad, itmSave, itmSaveAs, itmExit, itmCut, itmCopy, itmPaste, itmProperties;
public static JDialog newDoc;
public static JLabel newDocText1, newDocText2;
public static JRadioButton questions, list;
public static ButtonGroup newDocButtons;
public static JButton newDocOk;
public static Boolean firstSegment;
public static JPanel workspace;
public static JScrollPane scroll;
public static ArrayList<Page> pages;
public static void newDocumentForm()
{
//new document dialog
mWindow.setEnabled(false);
newDoc = new JDialog(mWindow, "newDoc");
newDoc.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
newDoc.addWindowListener(new WindowListener ()
{
public void windowActivated(WindowEvent arg0) {}
public void windowClosing(WindowEvent arg0)
{
mWindow.toFront();
newDocText1 = null;
newDocText2 = null;
questions = null;
list = null;
newDocButtons = null;
newDocOk = null;
newDoc.dispose();
mWindow.setEnabled(true);
}
public void windowClosed(WindowEvent arg0) {}
public void windowDeactivated(WindowEvent arg0) {}
public void windowDeiconified(WindowEvent arg0) {}
public void windowIconified(WindowEvent arg0) {}
public void windowOpened(WindowEvent arg0) {}
});
newDoc.setSize(400, 200);
newDoc.setLocationRelativeTo(null);
newDoc.setResizable(false);
newDoc.setLayout(null);
newDoc.setVisible(true);
newDocText1 = new JLabel("newDocText1");
newDocText1.setBounds(5, 0, 400, 20);
newDocText2 = new JLabel("newDocText2");
newDocText2.setBounds(5, 20, 400, 20);
newDoc.add(newDocText1);
newDoc.add(newDocText2);
firstSegment = true;
questions = new JRadioButton("questions");
questions.setSelected(true);
questions.setFocusPainted(false);
questions.setBounds(10, 60, 400, 20);
questions.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
firstSegment = true;
}
});
list = new JRadioButton("list");
list.setFocusPainted(false);
list.setBounds(10, 80, 400, 20);
list.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
firstSegment = false;
}
});
newDoc.add(questions);
newDoc.add(list);
newDocButtons = new ButtonGroup();
newDocButtons.add(questions);
newDocButtons.add(list);
newDocOk = new JButton("ok");
newDocOk.addKeyListener(new KeyListener()
{
public void keyPressed(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_ENTER)
{
newDocOk.doClick();
}
}
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
});
newDocOk.setFocusPainted(false);
newDocOk.setBounds(160, 120, 80, 40);
newDocOk.setMnemonic(KeyEvent.VK_ACCEPT);
newDocOk.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
createNewDocument();
}
});
newDoc.add(newDocOk);
newDocOk.requestFocus();
}
public static void createNewDocument()
{
//dispose of new document dialog
mWindow.toFront();
newDocText1 = null;
newDocText2 = null;
questions = null;
list = null;
newDocButtons = null;
newDocOk = null;
newDoc.dispose();
mWindow.setEnabled(true);
//create document display
workspace = new JPanel();
workspace.setLayout(new BoxLayout(workspace, BoxLayout.PAGE_AXIS));
workspace.add(new Box.Filler(new Dimension(0, 40), new Dimension(0, 40), new Dimension(0, 40)));
workspace.setBackground(Color.BLACK);
scroll = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scroll.getVerticalScrollBar().setUnitIncrement(20);
scroll.setViewportView(workspace);
pages = new ArrayList<Page>();
#SuppressWarnings("unused")
Page p = new Page(workspace, 1);
Heading g = new Heading(true, p);
Question q = new Question(p, 1, 1);
mWindow.add(scroll, BorderLayout.CENTER);
mWindow.repaint();
mWindow.validate();
}
public static void main(String[] args) throws FileNotFoundException, IOException
{
//create main window
mWindow = new JFrame("title");
mWindow.setSize(1000, 800);
mWindow.setMinimumSize(new Dimension(1000, 800));
mWindow.setLocationRelativeTo(null);
mWindow.setLayout(new BorderLayout());
mWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mWindow.setVisible(true);
//create menu bar
menu = new JMenuBar();
menuFile = new JMenu("file");
menuEdit = new JMenu("edit");
itmNew = new JMenuItem("new");
itmNew.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));
itmNew.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
newDocumentForm();
}
});
itmClose = new JMenuItem("close");
itmClose.setActionCommand("Close");
itmClose.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ActionEvent.CTRL_MASK));
itmLoad = new JMenuItem("load");
itmLoad.setActionCommand("Load");
itmLoad.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, ActionEvent.CTRL_MASK));
itmSave = new JMenuItem("save");
itmSave.setActionCommand("Save");
itmSave.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
itmSaveAs = new JMenuItem("saveAs");
itmSaveAs.setActionCommand("SaveAs");
itmExit = new JMenuItem("exit");
itmExit.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//Add confirmation window!
System.exit(0);
}
});
itmCut = new JMenuItem("cut");
itmCut.setActionCommand("Cut");
itmCut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.CTRL_MASK));
itmCopy = new JMenuItem("copy");
itmCopy.setActionCommand("Copy");
itmCopy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK));
itmPaste = new JMenuItem("paste");
itmPaste.setActionCommand("Paste");
itmPaste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK));
itmProperties = new JMenuItem("properties");
itmProperties.setActionCommand("properties");
itmProperties.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, ActionEvent.CTRL_MASK));
menuFile.add(itmNew);
menuFile.add(itmClose);
menuFile.addSeparator();
menuFile.add(itmLoad);
menuFile.addSeparator();
menuFile.add(itmSave);
menuFile.add(itmSaveAs);
menuFile.addSeparator();
menuFile.add(itmExit);
menuEdit.add(itmCut);
menuEdit.add(itmCopy);
menuEdit.add(itmPaste);
menuEdit.addSeparator();
menuEdit.add(itmProperties);
menu.add(menuFile);
menu.add(menuEdit);
//create actionListener for menus
mWindow.add(menu, BorderLayout.NORTH);
mWindow.repaint();
mWindow.validate();
}
}
This is the best I can do, refer to Question class for issue.
To get GUI drawn, run it, pres ctrl+n, and then enter.

As I understood you want to achieve this:
If that is true, all you have to do is this:
numberArea.setLayout(new BorderLayout());
and
numberArea.add(number,BorderLayout.NORTH);

As brano88 suggests, change layout manager...
public Question(Page page, int pageNum, int index) {
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
questionArea = new JPanel();
questionArea.setLayout(new GridBagLayout());
numberArea = new JPanel();
numberArea.setLayout(new BoxLayout(numberArea, BoxLayout.Y_AXIS));
numberArea.setBackground(Color.YELLOW);
number = new JLabel(pageNum + ".", JLabel.RIGHT);
number.setMinimumSize(new Dimension(100, 20));
number.setPreferredSize(new Dimension(100, 20));
number.setMaximumSize(new Dimension(100, 20));
//number.setAlignmentX(TOP_ALIGNMENT);
number.setFont(new Font("Arial", Font.PLAIN, 18));
number.setBackground(Color.BLUE);
numberArea.add(number);
//numberArea.add(new Box.Filler(new Dimension(40, 0), new Dimension(40, 30), new Dimension(40, 300)), BorderLayout.CENTER);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.VERTICAL;
gbc.anchor = GridBagConstraints.NORTH;
questionArea.add(numberArea, gbc);
question = new JTextArea();
question.setFont(new Font("Arial", Font.PLAIN, 18));
question.setLineWrap(true);
question.setWrapStyleWord(true);
question.setBackground(Color.GREEN);
question.setText("dafd afdfd fasdfsdaah fg dfgd");
gbc.gridx = 1;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 1;
gbc.weighty = 1;
gbc.anchor = GridBagConstraints.NORTH;
questionArea.add(question, gbc);
add(questionArea);
page.add(this, index);
}

Related

How to set frame visibility conditionally in JSwing?

I'm trying to create a login panel in Java Swing where the user will first get a screen that requires them to enter the credentials and if they match the correct credentials, they will be directed to another java GUI class called UserManager. I'm not sure how I can set the current frame (of the login panel) to be false and the set the frame visible of the new panel that I want to switch to (the UserManger panel) to be true.
Here is what I have so far but it's not working:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JButton;
public class Main implements ActionListener {
private static JLabel label;
private static JTextField userText;
private static JLabel passwordLabel;
private static JPasswordField passwordText;
private static JButton button;
private static JLabel success;
private static boolean loggedIn = false;
public static void main(String[] args) {
// JOptionPane.showMessageDialog(null, "Login");
JFrame f = new JFrame();
JPanel panel = new JPanel();
f.setSize(100, 100);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(panel);
panel.setLayout(null);
// username text label
label = new JLabel("User");
label.setBounds(10, 20, 80, 25);
panel.add(label);
userText = new JTextField(20);
userText.setBounds(100, 20, 165, 25);
panel.add(userText);
// pasword label
passwordLabel = new JLabel("Password");
passwordLabel.setBounds(10, 50, 80, 25);
panel.add(passwordLabel);
passwordText = new JPasswordField(20);
passwordText.setBounds(100, 50, 165, 25);
panel.add(passwordText);
button = new JButton("Login");
button.setBounds(10, 80, 80, 25);
button.addActionListener(new Main());
panel.add(button);
success = new JLabel("");
success.setBounds(10, 110, 300, 25);
panel.add(success);
f.setVisible(true);
if (loggedIn) {
UserManager frame = new UserManager();
f.setVisible(false);
frame.setVisible(true);
}
}
#Override
public void actionPerformed(ActionEvent e) {
String user = userText.getText();
String password = passwordText.getText();
System.out.println(user + ", " + password);
if(user.equals("John") && password.equals("hello")) {
success.setText("Login successful");
loggedIn = true;
}
else {
success.setText("Incorrect credentials.");
}
}
}
Use a CardLayout
See for How to Use CardLayout more details.
This will encourage you to isolate you functionality into individual components, there by isolating the workflows and supporting the "single responsibility" concept.
import java.awt.CardLayout;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new MainPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class MainPane extends JPanel {
private UserPane userPane;
private LoginPane loginPane;
public MainPane() {
setLayout(new CardLayout());
userPane = new UserPane();
loginPane = new LoginPane(new AuthenticationListener() {
#Override
public void authenticationWasSuccessful(User user) {
userPane.setUser(user);
// The user pane's content size will have changed
SwingUtilities.windowForComponent(userPane).pack();
((CardLayout) getLayout()).show(MainPane.this, "USER");
}
#Override
public void authenticationDidFail() {
JOptionPane.showMessageDialog(MainPane.this, "Authentication failed", "Error", JOptionPane.ERROR_MESSAGE);
}
});
add(userPane, "USER");
add(loginPane, "LOGIN");
((CardLayout) getLayout()).show(this, "LOGIN");
}
}
public interface User {
public String getName();
}
public class DefaultUser implements User {
private String name;
public DefaultUser(String name) {
this.name = name;
}
#Override
public String getName() {
return name;
}
}
public interface AuthenticationListener {
public void authenticationWasSuccessful(User user);
public void authenticationDidFail();
}
public class LoginPane extends JPanel {
private JTextField user;
private JPasswordField password;
private JButton login;
private AuthenticationListener loginListener;
public LoginPane(AuthenticationListener listener) {
setBorder(new EmptyBorder(32, 32, 32, 32));
this.loginListener = listener;
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(4, 4, 4, 4);
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.EAST;
add(new JLabel("User name:"), gbc);
gbc.gridy++;
add(new JLabel("Password:"), gbc);
gbc.gridx++;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.WEST;
user = new JTextField(12);
password = new JPasswordField(12);
add(user, gbc);
gbc.gridy++;
add(password, gbc);
login = new JButton("Login");
gbc.gridx = 0;
gbc.gridy++;
gbc.anchor = GridBagConstraints.CENTER;
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(login, gbc);
login.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
boolean accept = (boolean) (((int) Math.round(Math.random() * 1)) == 0 ? true : false);
if (accept) {
loginListener.authenticationWasSuccessful(new DefaultUser(user.getText()));
} else {
loginListener.authenticationDidFail();
}
}
});
}
}
public class UserPane extends JPanel {
private JLabel userLabel;
public UserPane() {
JLabel label = new JLabel("Welcome!");
Font font = label.getFont();
label.setFont(font.deriveFont(Font.BOLD, 32));
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = gbc.REMAINDER;
add(label, gbc);
userLabel = new JLabel();
add(userLabel, gbc);
}
public void setUser(User user) {
userLabel.setText(user.getName());
}
}
}
Use a modal JDialog
See How to Make Dialogs for more details.
More windows isn't always a good choice, but in the context of gathering user credentials, I think you can make an argument.
This makes use of a modal dialog to stop the code execution at the point that the window is made visible and it won't continue until the window is closed. This allows you an opportunity to get and validate the user credentials before the code continues (it's black magic in how it works, but it's a very common workflow)
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
User user = LoginPane.showLoginDialog();
if (user != null) {
JFrame frame = new JFrame();
frame.add(new UserPane(user));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} else {
// Well, you really don't know do you? Did they cancel
// the dialog or did authentication fail?
}
}
});
}
public interface User {
public String getName();
}
public static class DefaultUser implements User {
private String name;
public DefaultUser(String name) {
this.name = name;
}
#Override
public String getName() {
return name;
}
}
public static class LoginPane extends JPanel {
public interface AuthenticationListener {
public void authenticationWasSuccessful(User user);
public void authenticationDidFail();
}
private JTextField userTextField;
private JPasswordField passwordField;
private JButton loginButton;
private User user;
public LoginPane(AuthenticationListener listener) {
setBorder(new EmptyBorder(32, 32, 32, 32));
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(4, 4, 4, 4);
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.EAST;
add(new JLabel("User name:"), gbc);
gbc.gridy++;
add(new JLabel("Password:"), gbc);
gbc.gridx++;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.WEST;
userTextField = new JTextField(12);
passwordField = new JPasswordField(12);
add(userTextField, gbc);
gbc.gridy++;
add(passwordField, gbc);
loginButton = new JButton("Login");
gbc.gridx = 0;
gbc.gridy++;
gbc.anchor = GridBagConstraints.CENTER;
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(loginButton, gbc);
loginButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
boolean accept = (boolean) (((int) Math.round(Math.random() * 1)) == 0 ? true : false);
if (accept) {
user = new DefaultUser(userTextField.getText());
listener.authenticationWasSuccessful(user);
} else {
user = null;
listener.authenticationDidFail();
}
}
});
}
public User getUser() {
return user;
}
public static User showLoginDialog() {
JDialog dialog = new JDialog();
dialog.setTitle("Login");
dialog.setModal(true);
LoginPane loginPane = new LoginPane(new LoginPane.AuthenticationListener() {
#Override
public void authenticationWasSuccessful(User user) {
dialog.dispose();
}
#Override
public void authenticationDidFail() {
JOptionPane.showMessageDialog(dialog, "Authentication failed", "Error", JOptionPane.ERROR_MESSAGE);
}
});
dialog.add(loginPane);
dialog.pack();
dialog.setLocationRelativeTo(null);
dialog.setVisible(true);
return loginPane.getUser();
}
}
public class UserPane extends JPanel {
public UserPane(User user) {
setBorder(new EmptyBorder(32, 32, 32, 32));
JLabel label = new JLabel("Welcome!");
Font font = label.getFont();
label.setFont(font.deriveFont(Font.BOLD, 32));
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = gbc.REMAINDER;
add(label, gbc);
JLabel userLabel = new JLabel();
userLabel.setText(user.getName());
add(userLabel, gbc);
}
}
}
You need to unset visibility of this frame and set visible User manager at the action performed level:
private navigateToNextFrame(){
f.dispose(false);
UserManager frame = new UserManager();
frame.setVisible(true);
}
Now you need to call this method in the action performed method instead of loggedin=true and delete block in main main method (if (loggedIn))
A little suggestion : User Manager could be a singleton so you can create it at least 1 time.

when my W key is pressed it doesn't register

I am trying to create a game but my key bindings are not working and I am not sure why. the code included will run if given pictures and graphics data for image icons. When running the game the key bind gets input into the key map but it cannot be used for some odd reason. If anyone has any clue as to why it might be doing this that would be much appreciated.
graphics/ui:
package Ballerz;
import java.util.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.*;
import java.io.*;
public class GraphicsPn extends Game{
public GraphicsPn() throws IOException{
frame.setUndecorated(true);
frame.setName("Ballerz");
frame.setIconImage(window.getImage());
frame.setContentPane(startMenu);
frame.validate();
startMenu.setLayout(bord);
startMenu.setPreferredSize(new Dimension(1366, 768));
//top menu design
startMenu.add(topMenu);
topMenu.setPreferredSize(new Dimension(1366, 40));
topMenu.setBackground(Color.BLACK);
topMenu.setForeground(Color.WHITE);
topMenu.setAlignmentX(topMenu.RIGHT_ALIGNMENT);
topMenu.setLayout(bord);
setScene.add(topMenu);
topMenu.setPreferredSize(new Dimension(1366, 40));
topMenu.setBackground(Color.BLACK);
topMenu.setForeground(Color.WHITE);
topMenu.setAlignmentX(topMenu.RIGHT_ALIGNMENT);
topMenu.setLayout(bord);
topMenu.add(X, bord.EAST);
X.setLabel("X");
X.setFont(new Font(title.getName(), Font.ITALIC, 20));
X.setBackground(Color.BLACK);
X.setForeground(Color.WHITE);
X.setSize(new Dimension(50,40));
X.setFocusPainted(false);
X.setBorderPainted(false);
X.doLayout();
startMenu.add(menu, bord.EAST);
ballerz.setIcon(gif);
ballerz.setPreferredSize(new Dimension(768,768));
startMenu.add(ballerz, bord.WEST);
//menu Design
menu.setPreferredSize(new Dimension(598, 700));
menu.setBackground((Color.BLACK));
menu.setLayout(grid);
menu.setAlignmentY(menu.BOTTOM_ALIGNMENT);
grid.setVgap(30);
menu.add(title);
title.setForeground(Color.WHITE);
title.setPreferredSize(new Dimension(598, 150));
title.setFont(new Font(title.getName(), Font.ITALIC, 70));
menu.add(start);
start.setBackground(Color.BLACK);
start.setForeground(Color.WHITE);
start.setLabel("New Game");
start.setFocusPainted(false);
start.setFont(new Font(title.getName(), Font.ITALIC, 25));
start.setBorderPainted(false);
start.setSize(598,50);
start.doLayout();
menu.add(settings);
settings.setBackground(Color.BLACK);
settings.setForeground(Color.WHITE);
settings.setLabel("Settings");
settings.setFocusPainted(false);
settings.setFont(new Font(title.getName(), Font.ITALIC, 25));
settings.setBorderPainted(false);
settings.setSize(598,50);
settings.doLayout();
menu.add(help);
help.setBackground(Color.BLACK);
help.setForeground(Color.WHITE);
help.setLabel("How to Play");
help.setFocusPainted(false);
help.setFont(new Font(title.getName(), Font.ITALIC, 25));
help.setBorderPainted(false);
help.setSize(598,50);
help.doLayout();
menu.add(exit);
exit.setBackground(Color.BLACK);
exit.setForeground(Color.WHITE);
exit.setLabel("Exit");
exit.setFocusPainted(false);
exit.setFont(new Font(title.getName(), Font.ITALIC, 25));
exit.setBorderPainted(false);
exit.setSize(598,50);
exit.doLayout();
menu.add(source);
source.setFont(new Font(title.getName(), Font.ITALIC, 12));
//help design
helpScene.setPreferredSize(new Dimension(1366, 768));
helpScene.setBackground(Color.BLACK);
helpScene.add(topMenu);
ActionListener clic = new ActionListener(){ public void actionPerformed(ActionEvent e) {
if(e.getSource().equals(help)){
frame.setContentPane(helpScene);
frame.revalidate();
frame.repaint();
helpScene.requestFocus();
helpScene.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
helpScene.requestFocus();
System.out.println("pressed " + e.getKeyCode());
if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
frame.setContentPane(startMenu);
frame.repaint();
}
}});
frame.repaint();
}
if(e.getSource().equals(start)){
frame.setContentPane(game);
frame.invalidate();
frame.revalidate();
game.requestFocus();
frame.repaint();
}
if(e.getSource().equals(settings)){
frame.setContentPane(setScene);
setScene.setBackground(Color.BLACK);
setScene.requestFocus();
setScene.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
setScene.requestFocus();
System.out.println("pressed " + e.getKeyCode());
if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
frame.setContentPane(startMenu);
frame.repaint();
}
}});
frame.repaint();
}
if(e.getSource().equals(X)) {
frame.setContentPane(startMenu);
frame.revalidate();
frame.repaint();
}
if(e.getSource().equals(exit)){
System.exit(0);
}
}};
exit.addActionListener(clic);
X.addActionListener(clic);
start.addActionListener(clic);
help.addActionListener(clic);
settings.addActionListener(clic);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setVisible(true);
frame.setBackground(Color.black);
startMenu.setVisible(true);
}
}
game section:
package Ballerz;
import java.util.*;
import java.awt.*;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.io.*;
import java.lang.*;
public class Game extends JPanel {
public int x;
public int y;
public int x2;
public int y2;
public double dis1;
public double dis2;
public JLayeredPane game = new JLayeredPane();
public JPanel players = new JPanel();
JFrame frame = new JFrame();
JLabel ballerz = new JLabel();
public JPanel startMenu = new JPanel();
JPanel helpScene = new JPanel();
JPanel setScene = new JPanel();
JLabel title = new JLabel("Ballerz", JLabel.CENTER);
JLabel source = new JLabel("Gif by ShotoPop: https://media.giphy.com/media/3DrHrnC0JMotPiopno/giphy.gif", JLabel.CENTER);
JPanel menu = new JPanel();
JButton help = new JButton();
JButton start = new JButton();
JButton settings = new JButton();
JButton exit = new JButton("Exit");
JTextArea space1 = new JTextArea();
JPanel topMenu = new JPanel();
JButton X = new JButton();
JLabel space = new JLabel();
JLabel p2 = new JLabel();
public Image player1 = ImageIO.read(new File("C:\\Users\\Adam\\Downloads\\JavaCode\\Ballerz\\src\\tempdude.png"));
ImageIcon window = new ImageIcon("C:\\Users\\Adam\\Downloads\\JavaCode\\Ballerz\\src\\basketball dude.PNG");
ImageIcon gif = new ImageIcon("C:\\Users\\Adam\\Downloads\\JavaCode\\Ballerz\\src\\Ballerz.gif");
ImageIcon court = new ImageIcon("C:\\Users\\Adam\\Downloads\\JavaCode\\Ballerz\\src\\court.png");
ImageIcon player1s = new ImageIcon("C:\\Users\\Adam\\Downloads\\JavaCode\\Ballerz\\src\\tempdude.png");
public FlowLayout flow = new FlowLayout();
public BorderLayout bord = new BorderLayout();
public GridLayout grid = new GridLayout(6, 1);
JLabel ply1 = new JLabel();
JLabel ply2 = new JLabel();
public Game() throws IOException {
game.setLayout(bord);
game.setPreferredSize(new Dimension(1366, 768));
JLabel cort = new JLabel();
cort.setSize(new Dimension(1366, 768));
cort.setIcon(court);
players.setOpaque(false);
players.setLayout(bord);
players.setBackground(Color.pink);
ply1.setIcon(player1s);
ply1.setSize(new Dimension(200, 200));
ply1.setVisible(true);
ply1.setBackground(Color.black);
ply2.setIcon(player1s);
ply2.setSize(new Dimension(200, 200));
ply2.setVisible(true);
ply2.setBackground(Color.black);
players.add(ply1);
players.add(ply2);
players.setSize(new Dimension(1340, 820));
players.repaint();
players.setLayout(null);
ply2.setLocation(15, 410);
ply1.setLocation(1230, 410);
players.repaint();
players.setVisible(true);
players.setAlignmentX(CENTER_ALIGNMENT);
game.add(cort, bord.CENTER,5);
game.add(players,0);
players.setLocation(0, -50);
game.repaint();
}
public static void main(String[] arg) throws Exception {
GraphicsPn g = new GraphicsPn();
Game game = new Game();
keys li = new keys();
}
}
key binds:
package Ballerz;
import java.awt.event.ActionEvent;
import java.io.IOException;
import javax.swing.*;
public class keys extends Game{
public keys() throws IOException {
AbstractAction wAction = new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("BOI");
if (ply2.getLocation().getY() <= 650 && ply2.getLocation().getY() >= 10) {
ply2.setLocation((int) ply2.getLocation().getX(), (int) ply2.getLocation().getY() + 10);
System.out.println(ply2.getLocation());
}
if (ply2.getLocation().getY() > 650)
ply2.setLocation((int) ply2.getLocation().getX(), 650);
players.repaint();
if (ply2.getLocation().getY() < 10) {
ply2.setLocation((int) ply2.getLocation().getX(), 10);
players.repaint();
}
players.repaint();
}
};
players.getInputMap().put(KeyStroke.getKeyStroke('w'), "wAction");
players.getActionMap().put("wAction", wAction );
}
}
You claim that your key bindings aren't working which implies that the only relevant part of the huge amount of code that you posted in your question, are the last two lines, namely
players.getInputMap().put(KeyStroke.getKeyStroke('w'), "wAction");
players.getActionMap().put("wAction", wAction );
where players is a JPanel.
So basically your question boils down to:
Key bindings for JPanel not working
This question has been asked and answered many times on stackoverflow
Try searching the Internet with Google for the terms
jpanel key bindings site:stackoverflow.com
The first result (of more than 2000) was JPanel doesn't react to KeyBindings
Basically you need to
Make sure that players is focusable because, by default, a JPanel is not.
Make sure to use the correct input map

JPanel of main does not get updated from another class

I have class Home that extends JFrame, it holds a static variable panel_event. I have another class called EventLabel, which created a label and it's functions and adds it to the panel using refresh() method, code runs with no error, but my panel_event content does not get updated "show"
I have already added revalidate(), and repaint() methods
public EventLabel(String name2, String date2, int priority2, String note2) {
super();
this.name = name2;
this.date = date2;
this.priority = priority2;
this.note = note2;
}
public void buildLabel() {
label = new JLabel(this.getName());
label.setBounds(10, 11, 403, 34);
label.setForeground(Color.WHITE);
label.setFont(new Font("Yu Gothic UI Light", Font.PLAIN, 20));
String n = this.getNote();
String d = this.getDate();
int p = this.getPriority();
String na = this.getName();
setFont(new Font("Yu Gothic UI Light", Font.PLAIN, 20));
label.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
EventDetailFrame detailFrame = new EventDetailFrame();
detailFrame.NewWindow();
detailFrame.textAreaNoteD.setText(n);
detailFrame.textFieldNameD.setText(na);
detailFrame.textFieldDateD.setText(d);
detailFrame.textFieldPriorityD.setText("Priority");
}
});
}
public void refresh(){
panel_event.add(label);
panel_event.revalidate();
panel_event.repaint();
}
This is the frame with button that is suppose to change content of panel_event
btnSaveAndClose.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String name = txtEventName.getText();
String date = txtEventDate.getText();
String note = txtEventNote.getText();
int priority = getPriorityNumber(txtEventPriority.getText());
Event event = new Event(name, date, note, priority);
EventLabel event_label = new EventLabel(event.getName(),event.getDate(),event.getPriority(),event.getNote());
event_label.buildLabel();
event_label.refresh();
dispose();
}
});
After clicking btnSaveAndClose, I expected the panel_event to show my new JLabel
I created a working example on how to show new label. You can call validate() and repaint().
import java.awt.Color;
import java.awt.Font;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.StringJoiner;
import javax.swing.BorderFactory;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
public class EventLabel extends JLabel
{
private static final long serialVersionUID = -3122247523298894551L;
public EventLabel(String name, String date, String priority, String note)
{
super(name);
setBorder(BorderFactory.createLineBorder(Color.WHITE, 3, false));
setFont(new Font("Yu Gothic UI Light", Font.PLAIN, 20));
this.setOpaque(true);
setBackground(Color.WHITE);
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e)
{
StringJoiner text = new StringJoiner("\n");
text.add("name: " + name);
text.add("date: " + date);
text.add("priority: " + priority);
text.add("note: " + note);
JOptionPane.showMessageDialog(null, text, "Event", JOptionPane.INFORMATION_MESSAGE);
}
});
}
}
AND
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class Main
{
private static JButton button;
private static JPanel labelPanel;
private static JTextField nameField;
private static JTextField dateField;
private static JTextField priorityField;
private static JTextField noteField;
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run()
{
JFrame window = new JFrame();
window.setResizable(false);
window.setTitle("Label Test");
window.getContentPane().add(getContent());
initController();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(680, 700);
window.setLocationRelativeTo(null);
window.setVisible(true);
}
});
}
protected static void initController()
{
button.addActionListener(event -> {
labelPanel.add(new EventLabel(nameField.getText(), dateField.getText(), priorityField.getText(),
noteField.getText()));
nameField.setText("");
dateField.setText("");
priorityField.setText("");
noteField.setText("");
labelPanel.validate();
labelPanel.repaint();
});
}
private static Component getContent()
{
JPanel panel = new JPanel(new BorderLayout());
panel.add(getNorthPanel(), BorderLayout.NORTH);
labelPanel = new JPanel(new FlowLayout());
labelPanel.setBorder(BorderFactory.createTitledBorder("Events"));
panel.add(labelPanel, BorderLayout.CENTER);
return panel;
}
private static Component getNorthPanel()
{
JPanel panel = new JPanel(new FlowLayout());
JPanel inputPanel = new JPanel(new GridLayout(0, 2));
inputPanel.setPreferredSize(new Dimension(400, 100));
nameField = new JTextField();
dateField = new JTextField();
priorityField = new JTextField();
noteField = new JTextField();
inputPanel.add(new JLabel("name"));
inputPanel.add(nameField);
inputPanel.add(new JLabel("date"));
inputPanel.add(dateField);
inputPanel.add(new JLabel("priority"));
inputPanel.add(priorityField);
inputPanel.add(new JLabel("note"));
inputPanel.add(noteField);
panel.add(inputPanel);
button = new JButton("add event");
panel.add(button);
return panel;
}
}

Picture slideshow with fade in/fade out on a JPanel

So, my problem here is that I want a JPanel on my JFrame to function as a slideshow where 4 different pictures fade in and fade out.
I'm using the Scalr library to resize, everything works except with I use run();
As soon as I use that my window won't open and it get stuck with just the text running through. Is there anyway to make this panel have it's own way? Just sitting in the corner and doing his own thing?
A basic explanation would be lovely because I'm very new with Threads and everything around that.
Thank you!
import javax.imageio.ImageIO;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JSplitPane;
import java.awt.BorderLayout;
import java.awt.GridBagLayout;
import javax.swing.JPanel;
import java.awt.GridBagConstraints;
import javax.swing.JButton;
import javax.swing.JTextField;
import java.awt.Insets;
import javax.swing.JTextArea;
import javax.swing.JList;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.awt.Dimension;
import java.awt.Font;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.ButtonGroup;
import javax.swing.AbstractAction;
import se.lundell.team.Team;
import javax.swing.ListSelectionModel;
import javax.swing.Action;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JMenu;
import org.imgscalr.Scalr;
public class MainWindow {
private JFrame frame;
private JTextField textField;
private final ButtonGroup buttonGroup = new ButtonGroup();
protected DefaultListModel<Team> teamList;
private JList list;
private JTextArea textArea;
private final Action addTeamAction = new AddTeamAction();
private final Action removeTeamAction = new RemoveTeamAction();
private final Action clearListAction = new ClearListAction();
private final Action generateAction = new GenerateAction();
public ArrayList<Team> teamA;
public ArrayList<Team> teamB;
/**
* Create the application.
*/
public MainWindow() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 957, 642);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new BorderLayout(0, 0));
JSplitPane splitPane = new JSplitPane();
frame.getContentPane().add(splitPane, BorderLayout.CENTER);
JPanel leftPanel = new JPanel();
splitPane.setLeftComponent(leftPanel);
GridBagLayout gbl_leftPanel = new GridBagLayout();
gbl_leftPanel.columnWidths = new int[]{0, 0};
gbl_leftPanel.rowHeights = new int[]{0, 0, 41, 66, 0, 0};
gbl_leftPanel.columnWeights = new double[]{1.0, Double.MIN_VALUE};
gbl_leftPanel.rowWeights = new double[]{1.0, 0.0, 0.0, 0.0, 1.0, Double.MIN_VALUE};
leftPanel.setLayout(gbl_leftPanel);
teamList = new DefaultListModel<Team>();
teamList.addElement(new Team("team1"));
teamList.addElement(new Team("team2"));
teamList.addElement(new Team("team3"));
teamList.addElement(new Team("team4"));
list = new JList();
list.setModel(teamList);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
GridBagConstraints gbc_list = new GridBagConstraints();
gbc_list.insets = new Insets(0, 0, 5, 0);
gbc_list.fill = GridBagConstraints.BOTH;
gbc_list.gridx = 0;
gbc_list.gridy = 0;
leftPanel.add(list, gbc_list);
textField = new JTextField();
GridBagConstraints gbc_textField = new GridBagConstraints();
gbc_textField.insets = new Insets(0, 0, 5, 0);
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 0;
gbc_textField.gridy = 1;
leftPanel.add(textField, gbc_textField);
textField.setColumns(10);
JPanel btnPanel = new JPanel();
GridBagConstraints gbc_btnPanel = new GridBagConstraints();
gbc_btnPanel.insets = new Insets(0, 0, 5, 0);
gbc_btnPanel.fill = GridBagConstraints.VERTICAL;
gbc_btnPanel.gridx = 0;
gbc_btnPanel.gridy = 2;
leftPanel.add(btnPanel, gbc_btnPanel);
btnPanel.setLayout(new GridLayout(0, 3, 0, 0));
JButton btnAdd = new JButton("Add");
btnAdd.setAction(addTeamAction);
buttonGroup.add(btnAdd);
btnPanel.add(btnAdd);
JButton btnRemove = new JButton("Remove");
btnRemove.setAction(removeTeamAction);
buttonGroup.add(btnRemove);
btnPanel.add(btnRemove);
JButton btnClear = new JButton("Clear");
btnClear.setAction(clearListAction);
buttonGroup.add(btnClear);
btnPanel.add(btnClear);
JPanel generatePanel = new JPanel();
generatePanel.setPreferredSize(new Dimension(10, 20));
GridBagConstraints gbc_generatePanel = new GridBagConstraints();
gbc_generatePanel.fill = GridBagConstraints.BOTH;
gbc_generatePanel.insets = new Insets(0, 0, 5, 0);
gbc_generatePanel.gridx = 0;
gbc_generatePanel.gridy = 3;
leftPanel.add(generatePanel, gbc_generatePanel);
generatePanel.setLayout(new GridLayout(1, 0, 0, 0));
JButton btnGenerate = new JButton("Generate");
btnGenerate.setAction(generateAction);
btnGenerate.setFont(new Font("Tahoma", Font.PLAIN, 26));
generatePanel.add(btnGenerate);
PictureFrame canvasPanel = new PictureFrame();
GridBagConstraints gbc_canvasPanel = new GridBagConstraints();
gbc_canvasPanel.fill = GridBagConstraints.BOTH;
gbc_canvasPanel.gridx = 0;
gbc_canvasPanel.gridy = 4;
leftPanel.add(canvasPanel, gbc_canvasPanel);
JPanel rightPanel = new JPanel();
splitPane.setRightComponent(rightPanel);
rightPanel.setLayout(new BorderLayout(0, 0));
textArea = new JTextArea();
textArea.setEditable(false);
textArea.setAlignmentY(Component.BOTTOM_ALIGNMENT);
textArea.setAlignmentX(Component.LEFT_ALIGNMENT);
rightPanel.add(textArea, BorderLayout.CENTER);
JMenuBar menuBar = new JMenuBar();
frame.getContentPane().add(menuBar, BorderLayout.NORTH);
JMenu mnMenu = new JMenu("Menu");
menuBar.add(mnMenu);
JMenuItem mntmLoad = new JMenuItem("Load");
mnMenu.add(mntmLoad);
JMenuItem mntmSave = new JMenuItem("Save");
mnMenu.add(mntmSave);
JMenuItem mntmExit = new JMenuItem("Exit");
mnMenu.add(mntmExit);
frame.setVisible(true);
}
protected JList getList() {
return list;
}
private class AddTeamAction extends AbstractAction {
public AddTeamAction() {
putValue(NAME, "Add");
putValue(SHORT_DESCRIPTION, "Add team to list.");
}
public void actionPerformed(ActionEvent e) {
if(!textField.getText().isEmpty()) {
teamList.addElement(new Team(textField.getText()));
textField.setText("");
} else {
JOptionPane.showMessageDialog(null, "You need to enter a name.", "Error!", JOptionPane.ERROR_MESSAGE);
}
}
}
private class RemoveTeamAction extends AbstractAction {
public RemoveTeamAction() {
putValue(NAME, "Remove");
putValue(SHORT_DESCRIPTION, "Remove the selected team.");
}
public void actionPerformed(ActionEvent e) {
int choice = getList().getSelectedIndex();
teamList.removeElementAt(choice);
}
}
private class ClearListAction extends AbstractAction {
public ClearListAction() {
putValue(NAME, "Clear");
putValue(SHORT_DESCRIPTION, "Clear the list and the tournament window");
}
public void actionPerformed(ActionEvent e) {
teamList.clear();
textArea.setText("");
teamA.clear();
teamB.clear();
}
}
private class GenerateAction extends AbstractAction {
public GenerateAction() {
putValue(NAME, "Generate");
putValue(SHORT_DESCRIPTION, "Generate a new Round Robin tournament.");
teamA = new ArrayList<Team>();
teamB = new ArrayList<Team>();
}
public void actionPerformed(ActionEvent e) {
rotateSchedual();
}
private void rotateSchedual(){
if(teamList.getSize() % 2 == 0) {
start();
} else {
teamList.addElement(new Team("Dummy"));
start();
}
}
protected void start() {
for(int i = 0; i < teamList.getSize(); i++) {
teamA.add(teamList.getElementAt(i));
}
// Split the arrayList to two and invert.
splitSchedual();
int length = teamA.size();
System.out.println(teamB.size());
System.out.println(length);
printSchedual(length);
//remove index 0 from teamA and add index 0 from teamB first in the list. then add the first team back in again.
for(int i = 0;i <= (length - 1); i++){
//copy index 0 and add it to the other array.
//remove index 0 in both arrays.
teamA.add(1, teamB.get(0));
teamB.remove(0);
teamB.add(teamA.get(length));
teamA.remove(length);
printSchedual(length);
}
}
//Splits the array in to two arrays.
protected void splitSchedual(){
int length = teamA.size();
for(int i = (length/2);i < (length);i++){
teamB.add(teamA.get(i));
}
for(int i = (length - 1);i >= (length/2); i--) {
teamA.remove(i);
}
}
protected void printSchedual(int length){
int rounds = length;
for(int i = 0; i < (rounds - 1); i++){
textArea.append((i+1) + ". " + teamA.get(i).getTeamname() + " - " + teamB.get(i).getTeamname() + "\n");
}
textArea.append("-----------------------------\n");
}
}
public class PictureFrame extends JPanel implements Runnable {
Runnable run;
Image[] imageArray = new Image[4];
Image resized;
public PictureFrame() {
setVisible(true);
try {
imageArray[0] = ImageIO.read(new File(getClass().getResource("/se/lundell/assets/TrophyTheChampion.gif").getFile()));
imageArray[1] = ImageIO.read(new File(getClass().getResource("/se/lundell/assets/trophy.gif").getFile()));
imageArray[2] = ImageIO.read(new File(getClass().getResource("/se/lundell/assets/trophy1.gif").getFile()));
imageArray[3] = ImageIO.read(new File(getClass().getResource("/se/lundell/assets/nicolas_cage.jpg").getFile()));
} catch (IOException e) {
e.printStackTrace();
}
resized = Scalr.resize((BufferedImage)imageArray[0], 190, 190);
}
#Override
public void run() {
System.out.println("körs bara en gång.");
while(true) {
System.out.println("This will print, over and over again.");
for(int i = 0; i < imageArray.length; i++) {
resized = Scalr.resize((BufferedImage)imageArray[i], 190, 190);
repaint();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
#Override
public void paint(Graphics g) {
g.drawImage(resized, 30, 0, null);
}
}
}

Sorting Table is wrong when the sort button be pressed more than once?

I have a problem here. I create program to add data to the table and sort it when i press the button. when i press the sort button once, it isn't wrong. but when i press again it is wrong. so why? please help me.
this is the code.
Nama Class
public class Nama {
private String nama;
private int index;
public Nama(String n,int i){
nama=n;index=i;
}
void setData(String n,int i){
nama=n;index=i;
}
String nama(){
return nama;
}
int ind(){
return index;
}
public String toString(){
return(String.format("%s %d", nama,index));
}
}
MergeSort Class
import java.util.*;
public class MergeSortS{
public void merge_sort(int low,int high,Nama [] a){
int mid;
if(low<high) {
mid=(low+high)/2;
merge_sort(low,mid,a);
merge_sort(mid+1,high, a);
merge(low,mid,high,a);
}
}
public void merge(int low,int mid,int high,Nama [] a){
int h,i,j,k;
Nama b[]=new Nama[50];
h=low;
i=low;
j=mid+1;
while((h<=mid)&&(j<=high)){
if(a[h].nama().compareToIgnoreCase(a[j].nama())<0){
b[i]=a[h];
h++;
}
else{
b[i]=a[j];
j++;
}
i++;
}
if(h>mid){
for(k=j;k<=high;k++){
b[i]=a[k];
i++;
}
}
else{
for(k=h;k<=mid;k++){
b[i]=a[k];
i++;
}
}
for(k=low;k<=high;k++) a[k]=b[k];
}
public MergeSortS() {
}
}
Panel Class
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
/**
*
* #author Kareem
*/
public class Panel extends JPanel implements ActionListener{
JTable table;
JTextField tf1,tf2,tf3,tf4;
JButton b1,b2,b3,b4,b5,b6,b7;
Vector rows,columns,temp;
DefaultTableModel tabModel;
String[]data = new String[3];
String [] column = {"Nama", "Nim", "IP"};
Nama[] n,nim,ip;
MergeSortS mS;
int c=0,index=0;
public Panel(){
this.setBounds(0,0,1280, 800);
this.setLayout(null);
inaTf();
inaTab();
inaBut();
n= new Nama[50];
nim= new Nama[50];
ip= new Nama[50];
mS= new MergeSortS();
this.setVisible(true);
}
public void inaTab(){
rows=new Vector();
columns= new Vector();
temp= new Vector();
addColumns(column);
tabModel=new DefaultTableModel();
tabModel.setDataVector(rows,columns);
table = new JTable(tabModel);
table.setPreferredScrollableViewportSize(new
Dimension(500, 70));
table.setFillsViewportHeight(true);
table.setBounds(100,100,200,200);
JScrollPane scroll = new JScrollPane(table);
scroll.setBounds(50,50,400,400);
add(scroll);
}
public void inaBut(){
b1=new JButton("add Row");
b1.setBounds(50,600,90,25);
add(b1);
b1.addActionListener(this);
b2=new JButton("Delete Row");
b2.setBounds(170,600,90,25);
add(b2);
b2.addActionListener(this);
b3=new JButton("SortName");
b3.setBounds(290,600,120,25);
add(b3);
b3.addActionListener(this);
b5=new JButton("SortNim");
b5.setBounds(290,650,120,25);
add(b5);
b5.addActionListener(this);
b6=new JButton("SortIP");
b6.setBounds(290,700,120,25);
add(b6);
b6.addActionListener(this);
b4=new JButton("RESET");
b4.setBounds(170,650,90,25);
add(b4);
b4.addActionListener(this);
}
public void inaTf(){
tf1=new JTextField();
tf1.setBounds(640,50,90,25);
add(tf1);
JLabel l1= new JLabel("Nama \t: ");
l1.setBounds(530,50,90,25);
add(l1);
tf2=new JTextField();
tf2.setBounds(640,80,90,25);
add(tf2);
JLabel l2= new JLabel("Nim : ");
l2.setBounds(530,80,90,25);
add(l2);
tf3=new JTextField();
tf3.setBounds(640,110,90,25);
add(tf3);
JLabel l3= new JLabel("IPK : ");
l3.setBounds(530,110,90,25);
add(l3);
tf4=new JTextField();
tf4.setBounds(640,140,90,25);
add(tf4);
JLabel l4= new JLabel("Hapus Baris ke ");
l4.setBounds(530,140,120,25);
add(l4);
}
public void addRow()
{
Vector r;
r = createBlankElement();
rows.addElement(r);
table.addNotify();
}
public void addRow(String [] data)
{
Vector r=new Vector();
r = isi(data);
rows.addElement(r);
table.addNotify();
}
public Vector createBlankElement()
{
Vector t = new Vector();
t.addElement((String) " ");
t.addElement((String) " ");
t.addElement((String) " ");
return t;
}
public Vector isi(String[] data) {
Vector t = new Vector();
for(int j=0;j<3;j++){
t.addElement((String) data[j]);
}
return t;
}
public void addColumns(String[] colName) {
for(int i=0;i<colName.length;i++)
columns.addElement((String) colName[i]);
}
void deleteRow(int index) {
if(index!=-1) {
rows.removeElementAt(index);
table.addNotify();
}
}
#Override
public void actionPerformed(ActionEvent e) {
try{
if(e.getSource()==b1){
data[0]=tf1.getText()+" "+index;
n[index]=new Nama(data[0],index);
data[1]=tf2.getText();
nim[index]=new Nama(data[1],index);
data[2]=tf3.getText()+rows.size();
ip[index]=new Nama (data[2],index);
c=c+1;
index=index+1;
addRow(data);
}
if(e.getSource()==b2){
int i;
i=Integer.parseInt(tf4.getText());
deleteRow(i);
// for(;i<rows.size();i++){
// n[i]=n[i+1];
// }
}
if(e.getSource()==b3){
mS.merge_sort(0, rows.size()-1, n);
temp.setSize(rows.size());
for(int i=0;i<index;i++){
temp.set(i, rows.get(n[i].ind()));
}
for(int i=0;i<index;i++){
rows.set(i, temp.get(i));
}
}
if(e.getSource()==b4){
rows.setSize(0);
temp.setSize(0);
for(int i=0;i<index;i++)n[i]=null;
index=0;
}
if(e.getSource()==b5){
mS.merge_sort(0, rows.size()-1, nim);
temp.setSize(rows.size());
for(int i=0;i<rows.size();i++){
temp.set(i, rows.get(nim[i].ind()));
}
for(int i=0;i<rows.size();i++){
rows.set(i, temp.get(i));
}
}
if(e.getSource()==b6){
mS.merge_sort(0, rows.size()-1, ip);
temp.setSize(rows.size());
for(int i=0;i<rows.size();i++){
temp.add(i, rows.get(ip[i].ind()));
}
for(int i=0;i<rows.size();i++){
rows.set(i, temp.get(i));
}
}
repaint();
}
catch (Throwable t){
JOptionPane.showMessageDialog(null, "AAAAAA");
}
}
}
Frame Class
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
/**
*
* #author Kareem
*/
public class Frame extends JFrame {
public Frame(){
super("Penghitung Gaji");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(null);
this.setSize(1280, 800);
this.getContentPane().add(new Panel());
this.setVisible(true);
}
public static void main(String[] args) {
Frame frame = new Frame();
}
}
Thanks. And Sorry for my bad english.
No where do you actually tell the TableModel that it's contents have changed...
Now, the thing that weirds me out, is you are keeping a Vector of the rows outside of the model...
mS.merge_sort(0, rows.size()-1, n);
temp.setSize(rows.size());
for(int i=0;i<index;i++){
temp.set(i, rows.get(n[i].ind()));
}
for(int i=0;i<index;i++){
rows.set(i, temp.get(i)); // This is doing nothing...
}
Once the data has been handed to the table model, you should not be interacting with it, unless you are willing to notify the table model of the changes.
Personally, I would simply use the inbuilt sorting capabilities of the JTable
ps- I would also, strongly, encourage you to learn how to use layout managers, they will save your sanity in the long run
Dashing through the snow
In a one-horse open sleigh
O'er the fields we go
Laughing all the way
Bells on bobtail ring'
Making spirits bright
What fun it is to ride and sing
A sleighing song tonight!
Jingle bells, jingle bells,
Jingle all the way.
Oh! what fun it is to ride
In a one-horse open sleigh.
Jingle bells, jingle bells, ....
song singing from code, please to apologize me if isn't this one your favorite song
can't comment or suggesting, excluding used LayoutManager in my code, I walked the path of least resistance, my endless lazyness
.
.
.
from code
.
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.RowSorter.SortKey;
import javax.swing.ScrollPaneConstants;
import javax.swing.SortOrder;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;
public class MyFrame {
private JFrame frame = new JFrame();
private JTable table;
private JPanel buttonPanel = new JPanel();
private JPanel buttonPanelSouth = new JPanel();
private JPanel textFieldPanel = new JPanel();
private JPanel northPanel = new JPanel();
private JPanel centerPanel = new JPanel();
private JLabel l1, l2, l3, l4;
private JTextField tf1, tf2, tf3, tf4;
private JButton b1, b2, b3, b4, b5, b6, b7;
private String[] columnNames = {"Nama", "Nim", "IP", "Hapus Baris ke"};
private Object[][] data = {
{"igor", "B01_125-358", "1.124.01.125", true},
{"lenka", "B21_002-242", "21.124.01.002", true},
{"peter", "B99_001-358", "99.124.01.001", false},
{"zuza", "B12_100-242", "12.124.01.100", true},
{"jozo", "BUS_011-358", "99.124.01.011", false},
{"nora", "B09_154-358", "9.124.01.154", false},
{"xantipa", "B01_001-358", "1.124.01.001", false},};
private DefaultTableModel model = new DefaultTableModel(data, columnNames) {
private static final long serialVersionUID = 1L;
#Override
public boolean isCellEditable(int row, int column) {
switch (column) {
case 3:
return true;
default:
return false;
}
}
#Override
public Class getColumnClass(int column) {
return getValueAt(0, column).getClass();
}
};
public MyFrame() {
table = new JTable(model);
table.setAutoCreateRowSorter(true);
table.setPreferredScrollableViewportSize(table.getPreferredSize());
table.setFillsViewportHeight(true);
table.getSelectionModel().setSelectionMode(
ListSelectionModel.SINGLE_SELECTION);
DefaultTableCellRenderer stringRenderer =
(DefaultTableCellRenderer) table.getDefaultRenderer(String.class);
stringRenderer.setHorizontalAlignment(SwingConstants.CENTER);
JScrollPane pane = new JScrollPane(table,
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
centerPanel.setLayout(new BorderLayout(10, 10));
centerPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
centerPanel.add(pane);
centerPanel.add(pane);
//
b1 = new JButton("add Row");
b1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
model.addRow(new Object[]{(tf1.getText()).trim(),
(tf2.getText()).trim(), (tf3.getText()).trim(), true});
}
});
b2 = new JButton("Delete Row");
b2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int rowToDelete = 0;
int rowToModel = 0;
if (table.getSelectedRow() > -1) {
rowToDelete = table.getSelectedRow();
rowToModel = table.convertRowIndexToModel(rowToDelete);
model.removeRow(rowToModel);
}
}
});
b3 = new JButton("RESET");
b3.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
table.getRowSorter().setSortKeys(null);
}
});
b4 = new JButton("SortName");
b4.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
table.getRowSorter().toggleSortOrder(0);
}
});
b5 = new JButton("SortNim");
b5.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
TableRowSorter rowSorter = (TableRowSorter) table.getRowSorter();
List<SortKey> sortKeys = new ArrayList<SortKey>();
SortKey sortKey = new SortKey(1, SortOrder.ASCENDING);
sortKeys.add(sortKey);
rowSorter.setSortKeys(sortKeys);
rowSorter.sort();
}
});
b6 = new JButton("SortIP");
b6.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
TableRowSorter rowSorter = (TableRowSorter) table.getRowSorter();
List<SortKey> sortKeys = new ArrayList<SortKey>();
SortKey sortKey = new SortKey(2, SortOrder.DESCENDING);
sortKeys.add(sortKey);
SortKey sortKey1 = new SortKey(1, SortOrder.ASCENDING);
sortKeys.add(sortKey1);
SortKey sortKey2 = new SortKey(0, SortOrder.UNSORTED);
sortKeys.add(sortKey2);
rowSorter.setSortKeys(sortKeys);
rowSorter.sort();
}
});
b7 = new JButton("SortIP");
buttonPanel.setLayout(new GridLayout(1, 0, 50, 0));
buttonPanel.setBorder(new EmptyBorder(2, 10, 2, 10));
buttonPanel.add(b1);
buttonPanel.add(b2);
//
buttonPanelSouth.setLayout(new GridLayout(1, 4, 5, 5));
buttonPanelSouth.add(b3);
buttonPanelSouth.add(b7);
b7.setVisible(false);
buttonPanelSouth.add(b4);
buttonPanelSouth.add(b5);
buttonPanelSouth.add(b6);
centerPanel.add(buttonPanelSouth, BorderLayout.SOUTH);
//
l1 = new JLabel("Nama : ", JLabel.RIGHT);
tf1 = new JTextField();
l2 = new JLabel("Nim : ", JLabel.RIGHT);
tf2 = new JTextField();
l3 = new JLabel("IPK : ", JLabel.RIGHT);
tf3 = new JTextField();
l4 = new JLabel("Hapus Baris ke :", JLabel.RIGHT);
tf4 = new JTextField();
textFieldPanel.setLayout(new GridLayout(4, 2, 10, 10));
textFieldPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
textFieldPanel.add(l1);
textFieldPanel.add(tf1);
textFieldPanel.add(l2);
textFieldPanel.add(tf2);
textFieldPanel.add(l3);
textFieldPanel.add(tf3);
textFieldPanel.add(l4);
textFieldPanel.add(tf4);
//
northPanel.setLayout(new BorderLayout());
northPanel.add(textFieldPanel);
northPanel.add(buttonPanel, BorderLayout.SOUTH);
//
frame.add(northPanel, BorderLayout.NORTH);
frame.add(centerPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] arg) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
MyFrame myFrame = new MyFrame();
}
});
}
}

Categories