I have 1 button i. but i need another. i added another JFrame and made a new class making the button. whenever i do
frame.add(new TestButton());
it never works. i already have
frame.add(new TestPanel());
which works. but its the only working one.
here is my TestButton code
package App.Gui.Buttons;
import java.awt.Color;
import java.awt.Dimension;
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.JLabel;
import javax.swing.JPanel;
import App.Gui.Event.ExitEvent;
public class TestButton extends JPanel {
public TestButton() {
setLayout(new GridBagLayout());
JButton button = new JButton();
button.setBackground(new Color(0, 0, 0, 0));
button.setForeground(new Color(0, 0, 0, 0));
button.setBorderPainted(false);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
ExitEvent.exit();
}
});
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.CENTER;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1;
gbc.insets = new Insets(20, 50, 20, 50);
add(button, gbc);
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1;
gbc.weighty = 1;
gbc.fill = GridBagConstraints.BOTH;
JPanel contentPane = new JPanel(new GridBagLayout());
contentPane.setBackground(Color.GREEN);
contentPane.add(new JLabel("Books app"));
add(contentPane, gbc);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(1200, 750);
}
public static void addButton() {
new TestButton();
}
}
i need to add another button to do more stuff like you would need in a software. but it either never starts or, it bugs the buttons.
pls help.
A JPanel can't be shown in of itself. It needs to be added to a container hierarchy which is backed by a window based class, like JFrame.
This is a pretty basic concept, which suggests that you might be better off spending some time going through Creating a GUI With Swing, especially How to Make Frames (Main Windows)
import java.awt.EventQueue;
import javax.swing.JFrame;
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 TestButton());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
Also, JFrame uses a BorderLayout by default, so you'll only be able to present a single component at each of it's five available positions.
So, if instead, you used a GridLayout, you could get multiple instances of TestButton on the window at the same time, for example
import java.awt.EventQueue;
import java.awt.GridLayout;
import javax.swing.JFrame;
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.setLayout(new GridLayout(2, 1));
frame.add(new TestButton());
frame.add(new TestButton());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
Now, Swing components also don't support alpha based colors, they are either opaque or they are not (no translucency - you can fake it, but that's beyond the scope)
So, I'd modify you code to look more like...
JButton button = new JButton();
//button.setBackground(new Color(0, 0, 0, 0));
//button.setForeground(new Color(0, 0, 0, 0));
button.setBorderPainted(false);
button.setOpaque(false);
button.setContentAreaFilled(false);
Also, good luck on been able to click that button by the way
Full code...
import java.awt.Color;
import java.awt.Dimension;
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.JLabel;
import javax.swing.JPanel;
public class TestButton extends JPanel {
public TestButton() {
setLayout(new GridBagLayout());
JButton button = new JButton();
// button.setBackground(new Color(0, 0, 0, 0));
// button.setForeground(new Color(0, 0, 0, 0));
button.setBorderPainted(false);
button.setOpaque(false);
button.setContentAreaFilled(false);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//ExitEvent.exit();
}
});
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.CENTER;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1;
gbc.insets = new Insets(20, 50, 20, 50);
add(button, gbc);
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1;
gbc.weighty = 1;
gbc.fill = GridBagConstraints.BOTH;
JPanel contentPane = new JPanel(new GridBagLayout());
contentPane.setBackground(Color.GREEN);
contentPane.add(new JLabel("Books app"));
add(contentPane, gbc);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(1200, 750);
}
}
There are also issues with updating a realised window (adding/removing components once the window is visible on the screen). Swing is lazy and you are required to request a layout and paint pass on the container you've modified (invalidate and repaint).
But you might find CardLayout more suitable to your needs instead - but since we don't have a runnable example, it's hard to know
got a problem here, trying to create a login to database system at the moment. I have to classes : UserLogManagerMainWindow and DatabaseConnectionFrame. My program is about log management. I want to make a database connection :
UserLogManagerMainWindow class has a button "Connect to database", on it's click DatabaseConnectionFrame initialize and gets up a frame with jlabels and jtextfields, after I enter everything i need, i press "Login" button, after this I want that my UserLogManagerMainWindow class continues on pressenting the logs from connected database.
I have written some code about how it supposed to look : "the logic about what am i trying to say"
connectToDatabaseBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
DatabaseConnectionFrame dcf = new DatabaseConnectionFrame();
dcf.setVisible(true);
if(dcf.answer == true) {
importButtons(menuBar);
setJMenuBar(menuBar);
try {
DatabaseComm.getColumnNamesToPanel(model, titles);
projects = DatabaseComm.AddLogsToArrayReturnProjectNames(events);
DatabaseComm.fillDataToPanel(model, events, titles, row);
DatabaseComm.resizeColumnWidth(table);
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
else {
System.out.println("not working");
}
}
});
But if statement does not working, i know why. That's why i'm asking how to make it work? More likely, threading is the key, but not good at it at the moment. Any tips without threading? And if threading is the only way, may i get some help of it?
Giving DatabaseConnectionFrame class below either:
package manager;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.GridBagLayout;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.InetAddress;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.SwingConstants;
import javax.swing.JButton;
public class DatabaseConnectionFrame extends JFrame{
private JPanel contentPane;
private JTextField address;
private JPasswordField password;
private JTextField username;
private JButton btnLogin;
private JButton btnCancel;
private JLabel lblPort;
private JTextField port;
public boolean answer = false;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
DatabaseConnectionFrame frame = new DatabaseConnectionFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public DatabaseConnectionFrame() {
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setSize(450,250);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
GridBagLayout gbl_contentPane = new GridBagLayout();
contentPane.setLayout(gbl_contentPane);
JLabel lblDatabaseIpAddress = new JLabel("Database ip address:");
GridBagConstraints gbc_lblDatabaseIpAddress = new GridBagConstraints();
gbc_lblDatabaseIpAddress.anchor = GridBagConstraints.EAST;
gbc_lblDatabaseIpAddress.insets = new Insets(0, 0, 5, 5);
gbc_lblDatabaseIpAddress.gridx = 0;
gbc_lblDatabaseIpAddress.gridy = 0;
contentPane.add(lblDatabaseIpAddress, gbc_lblDatabaseIpAddress);
address = new JTextField();
GridBagConstraints gbc_textField = new GridBagConstraints();
gbc_textField.insets = new Insets(0, 0, 5, 0);
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 1;
gbc_textField.gridy = 0;
contentPane.add(address, gbc_textField);
address.setColumns(10);
lblPort = new JLabel("Port");
GridBagConstraints gbc_lblPort = new GridBagConstraints();
gbc_lblPort.anchor = GridBagConstraints.EAST;
gbc_lblPort.insets = new Insets(0, 0, 5, 5);
gbc_lblPort.gridx = 0;
gbc_lblPort.gridy = 1;
contentPane.add(lblPort, gbc_lblPort);
port = new JTextField();
GridBagConstraints gbc_textField1 = new GridBagConstraints();
gbc_textField1.insets = new Insets(0, 0, 5, 0);
gbc_textField1.fill = GridBagConstraints.HORIZONTAL;
gbc_textField1.gridx = 1;
gbc_textField1.gridy = 1;
contentPane.add(port, gbc_textField1);
port.setColumns(10);
JLabel lblUsername = new JLabel("Username:");
lblUsername.setHorizontalAlignment(SwingConstants.CENTER);
GridBagConstraints gbc_lblUsername = new GridBagConstraints();
gbc_lblUsername.anchor = GridBagConstraints.EAST;
gbc_lblUsername.insets = new Insets(0, 0, 5, 5);
gbc_lblUsername.gridx = 0;
gbc_lblUsername.gridy = 2;
contentPane.add(lblUsername, gbc_lblUsername);
username = new JTextField();
GridBagConstraints gbc_textField_1 = new GridBagConstraints();
gbc_textField_1.insets = new Insets(0, 0, 5, 0);
gbc_textField_1.fill = GridBagConstraints.HORIZONTAL;
gbc_textField_1.gridx = 1;
gbc_textField_1.gridy = 2;
contentPane.add(username, gbc_textField_1);
username.setColumns(10);
JLabel lblPassword = new JLabel("Password");
GridBagConstraints gbc_lblPassword = new GridBagConstraints();
gbc_lblPassword.anchor = GridBagConstraints.EAST;
gbc_lblPassword.insets = new Insets(0, 0, 5, 5);
gbc_lblPassword.gridx = 0;
gbc_lblPassword.gridy = 3;
contentPane.add(lblPassword, gbc_lblPassword);
password = new JPasswordField();
GridBagConstraints gbc_passwordField = new GridBagConstraints();
gbc_passwordField.insets = new Insets(0, 0, 5, 0);
gbc_passwordField.fill = GridBagConstraints.HORIZONTAL;
gbc_passwordField.gridx = 1;
gbc_passwordField.gridy = 3;
contentPane.add(password, gbc_passwordField);
btnLogin = new JButton("Login");
GridBagConstraints gbc_btnLogin = new GridBagConstraints();
gbc_btnLogin.insets = new Insets(0, 0, 0, 5);
gbc_btnLogin.gridx = 0;
gbc_btnLogin.gridy = 4;
contentPane.add(btnLogin, gbc_btnLogin);
btnCancel = new JButton("Cancel");
GridBagConstraints gbc_btnCancel = new GridBagConstraints();
gbc_btnCancel.gridx = 1;
gbc_btnCancel.gridy = 4;
contentPane.add(btnCancel, gbc_btnCancel);
btnCancel.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
dispose();
}
});
btnLogin.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String dbAddress = address.getText();
String dbPort = port.getText();
String dbUsername = username.getText();
char[] dbPassword = password.getPassword();
if( dbAddress.isEmpty() || dbPort.isEmpty() || dbUsername.isEmpty() || dbPassword.length == 0) {
JOptionPane.showMessageDialog(getParent(),
"All fields have to be filled!");
}
else {
if(databaseValidation(dbAddress, dbPort, dbUsername, dbPassword)) {
JOptionPane.showMessageDialog(getParent(),
"Connected!");
answer = true;
setVisible(false);
}
else {
JOptionPane.showMessageDialog(getParent(),
"There was error connecting to the database!");
answer = false;
}
}
System.out.println(answer);
}
});
}
public boolean databaseValidation(String address, String port, String username, char[] password) {
String pw = String.valueOf(password);
System.out.println(pw);
try {
Connection con = DriverManager.getConnection("jdbc:mysql://" + address + ":" + port + "/logctrl?user=" + username + "&password=" + pw );
} catch (SQLException e) {
System.out.println("Error connecting to database!");
return false;
}
System.out.println("Connected");
return true;
}
}
If you want to wait for the user input, you have two choices, you either make your own observer pattern which can be called at some point in the future when the state changes in some way or you use a dialog, which will block the codes execution at the point the dialog is made visible and will wait till it's closed
See How to use dialogs for details
import java.awt.Frame;
import java.awt.GridBagLayout;
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.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Test");
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("Show the dialog");
add(btn);
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JDialog dialog = new JDialog((Frame)SwingUtilities.getWindowAncestor(TestPane.this), "I'm in charge now", true);
JButton btn = new JButton("Waiting");
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
dialog.dispose();
}
});
dialog.add(btn);
dialog.pack();
dialog.setLocationRelativeTo(TestPane.this);
dialog.setVisible(true);
JOptionPane.showMessageDialog(TestPane.this, "You won't see this till the dialog is closed");
}
});
}
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
In my custom JPanel appears graphic artifacts. I dont know why, because I have used super.paintComponent() in all of my custom paintings.
Here is how it looks on create.
2. And here is how it looks when I click on upgrades button.
And here is the code.
Menu
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.FontFormatException;
import java.awt.Graphics;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import java.awt.GridBagLayout;
import javax.swing.JPanel;
import java.awt.GridBagConstraints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class Menu {
static JFrame frame;
public static double scale = 1.5;
private static int WIDTH = 300, HEIGHT = 400;
public static Font fontTerminal;
private JPanel menuPanel;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Menu window = new Menu();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
* #throws IOException
*/
public Menu() throws IOException {
initialize();
}
/**
* Initialize the contents of the frame.
* #throws IOException
*/
private void initialize() throws IOException {
fontTerminal = new Font("Consolas", 1, 1);
try {
fontTerminal = Font.createFont(Font.TRUETYPE_FONT, new File("res/terminal.ttf"));
} catch (FontFormatException e1) {
e1.printStackTrace();
}
frame = new JFrame();
frame.setResizable(false);
frame.setBounds(100, 100, WIDTH, HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[]{0, 0};
gridBagLayout.rowHeights = new int[]{0, 0};
gridBagLayout.columnWeights = new double[]{1.0, Double.MIN_VALUE};
gridBagLayout.rowWeights = new double[]{1.0, Double.MIN_VALUE};
frame.getContentPane().setLayout(gridBagLayout);
menuPanel = new BackgroundPanel();
menuPanel.setLayout(null);
GridBagConstraints gbc_menuPanel = new GridBagConstraints();
gbc_menuPanel.fill = GridBagConstraints.BOTH;
gbc_menuPanel.gridx = 0;
gbc_menuPanel.gridy = 0;
frame.getContentPane().add(menuPanel, gbc_menuPanel);
GameButton newgameButton = new GameButton();
int ngButtWidth = 194, ngButtHeight = 71;
newgameButton.setBounds((frame.getWidth()/2) - (ngButtWidth/2), (frame.getHeight()/2) - (ngButtHeight/2), ngButtWidth, ngButtHeight);
newgameButton.setBackground( new Color(0,0,0,0));
menuPanel.add(newgameButton);
newgameButton.setLayout(new BorderLayout(0, 0));
JLabel newgameLbl = new GLabel("New Game", newgameButton, SwingConstants.CENTER);
newgameLbl.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
GameWindow gp = new GameWindow();
frame.setVisible(false);
}
});
newgameLbl.setFont(fontTerminal.deriveFont(19f));
newgameLbl.setForeground(new Color(0,0,0));
newgameButton.add(newgameLbl, BorderLayout.CENTER);
GameButton creditsButton = new GameButton();
creditsButton.setBackground(new Color(0, 0, 0, 0));
creditsButton.setBounds(56, 262, 194, 71);
menuPanel.add(creditsButton);
creditsButton.setLayout(new BorderLayout(0, 0));
JLabel creditsLabel = new GLabel("Credits", creditsButton, SwingConstants.CENTER);
creditsLabel.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
Credits credits = new Credits();
credits.setVisible(true);
}
});
creditsLabel.setForeground(Color.BLACK);
creditsLabel.setFont(null);
creditsLabel.setBackground(new Color(0, 0, 0, 0));
creditsLabel.setFont(fontTerminal.deriveFont(19f));
creditsButton.add(creditsLabel);
}
}
GameWindow
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.UIManager.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JFrame;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.JPanel;
import java.awt.Insets;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.awt.GridLayout;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JTabbedPane;
import net.miginfocom.swing.MigLayout;
import java.awt.FlowLayout;
import javax.swing.JTable;
public class GameWindow {
private JFrame frame;
private Font fontTerminal;
private JPanel workerPanel1;
private GProgressbar Bar1;
private GameButton upgradeWorker1;
private JLabel upgradeWorker1_1;
private JPanel workerPanel2;
private GProgressbar Bar2;
private GameButton upgradeWorker2;
private JPanel workerPanel3;
private GProgressbar Bar3;
private GameButton upgradeWorker3;
private JPanel workerPanel4;
private GProgressbar Bar4;
private GameButton upgradeWorker4;
private JPanel upgradesPanel;
private JLabel upgradeWorker2_1;
private JLabel upgradeWorker3_1;
private JLabel upgradeWorker4_1;
private JPanel specialPanel;
private JPanel upgradesButton;
private JTable table, table2;
/**
* Create the application.
*/
public GameWindow() {
initialize();
this.frame.setVisible(true);
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
// If Nimbus is not available, you can set the GUI to another look and feel.
}
fontTerminal = Menu.fontTerminal;
frame = new JFrame();
frame.setResizable(false);
frame.setBounds(100, 100, 306, 430);
//frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[]{0, 0};
gridBagLayout.rowHeights = new int[]{0, 0};
gridBagLayout.columnWeights = new double[]{1.0, Double.MIN_VALUE};
gridBagLayout.rowWeights = new double[]{1.0, Double.MIN_VALUE};
frame.getContentPane().setLayout(gridBagLayout);
frame.addWindowListener( new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
frame.setVisible(false);
frame.dispose();
Menu.frame.setVisible(true);
}});
GamePanel gamePanel = new GamePanel();
gamePanel.setLayout(null);
GridBagConstraints gbc_menuPanel = new GridBagConstraints();
gbc_menuPanel.fill = GridBagConstraints.BOTH;
gbc_menuPanel.gridx = 0;
gbc_menuPanel.gridy = 0;
frame.getContentPane().add(gamePanel, gbc_menuPanel);
upgradesPanel = new JPanel();
upgradesPanel.setBounds(23, 221, 253, 174);
upgradesPanel.setBackground(new Color(0,0,0,0));
gamePanel.add(upgradesPanel);
workerPanel1 = new JPanel();
workerPanel1.setBackground(new Color(0,0,0,0));
GridBagLayout gbl_workerPanel1 = new GridBagLayout();
gbl_workerPanel1.columnWidths = new int[]{119, 118, 0};
gbl_workerPanel1.rowHeights = new int[]{36, 0};
gbl_workerPanel1.columnWeights = new double[]{0.0, 0.0, Double.MIN_VALUE};
gbl_workerPanel1.rowWeights = new double[]{0.0, Double.MIN_VALUE};
workerPanel1.setLayout(gbl_workerPanel1);
Bar1 = new GProgressbar();
Bar1.setStringPainted(true);
GridBagConstraints gbc_Bar1 = new GridBagConstraints();
gbc_Bar1.fill = GridBagConstraints.BOTH;
gbc_Bar1.insets = new Insets(0, 0, 0, 5);
gbc_Bar1.gridx = 0;
gbc_Bar1.gridy = 0;
workerPanel1.add(Bar1, gbc_Bar1);
upgradeWorker1 = new GameButton();
GridBagConstraints gbc_upgradeWorker1 = new GridBagConstraints();
gbc_upgradeWorker1.fill = GridBagConstraints.BOTH;
gbc_upgradeWorker1.gridx = 1;
gbc_upgradeWorker1.gridy = 0;
workerPanel1.add(upgradeWorker1, gbc_upgradeWorker1);
upgradeWorker1_1 = new GLabel("Upgrade", upgradeWorker1, SwingConstants.CENTER);
upgradeWorker1_1.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
//upgrade worker 1
}
});
upgradeWorker1.setLayout(new BorderLayout(0, 0));
upgradeWorker1_1.setForeground(new Color(0,0,0));
upgradeWorker1.add(upgradeWorker1_1);
workerPanel2 = new JPanel();
workerPanel2.setBackground(new Color(0, 0, 0, 0));
GridBagLayout gbl_panel = new GridBagLayout();
gbl_panel.columnWidths = new int[]{119, 118, 0};
gbl_panel.rowHeights = new int[]{36, 0};
gbl_panel.columnWeights = new double[]{0.0, 0.0, Double.MIN_VALUE};
gbl_panel.rowWeights = new double[]{0.0, Double.MIN_VALUE};
workerPanel2.setLayout(gbl_panel);
Bar2 = new GProgressbar();
Bar2.setStringPainted(true);
GridBagConstraints gbc_Bar2 = new GridBagConstraints();
gbc_Bar2.fill = GridBagConstraints.BOTH;
gbc_Bar2.insets = new Insets(0, 0, 0, 5);
gbc_Bar2.gridx = 0;
gbc_Bar2.gridy = 0;
workerPanel2.add(Bar2, gbc_Bar2);
upgradeWorker2 = new GameButton();
GridBagConstraints gbc_upgradeWorker2 = new GridBagConstraints();
gbc_upgradeWorker2.fill = GridBagConstraints.BOTH;
gbc_upgradeWorker2.gridx = 1;
gbc_upgradeWorker2.gridy = 0;
workerPanel2.add(upgradeWorker2, gbc_upgradeWorker2);
upgradeWorker2.setLayout(new BorderLayout(0, 0));
upgradeWorker2_1 = new GLabel("Upgrade", upgradeWorker2, SwingConstants.CENTER);
upgradeWorker2_1.setForeground(Color.BLACK);
upgradeWorker2_1.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
//upgrade worker 2
}
});
upgradeWorker2.setLayout(new BorderLayout(0, 0));
upgradeWorker2_1.setFont(fontTerminal.deriveFont(15f));
upgradeWorker2.add(upgradeWorker2_1);
workerPanel3 = new JPanel();
workerPanel3.setBackground(new Color(0, 0, 0, 0));
GridBagLayout gbl_workerPanel3 = new GridBagLayout();
gbl_workerPanel3.columnWidths = new int[]{119, 118, 0};
gbl_workerPanel3.rowHeights = new int[]{36, 0};
gbl_workerPanel3.columnWeights = new double[]{0.0, 0.0, Double.MIN_VALUE};
gbl_workerPanel3.rowWeights = new double[]{0.0, Double.MIN_VALUE};
workerPanel3.setLayout(gbl_workerPanel3);
Bar3 = new GProgressbar();
Bar3.setStringPainted(true);
GridBagConstraints gbc_Bar3 = new GridBagConstraints();
gbc_Bar3.fill = GridBagConstraints.BOTH;
gbc_Bar3.insets = new Insets(0, 0, 0, 5);
gbc_Bar3.gridx = 0;
gbc_Bar3.gridy = 0;
workerPanel3.add(Bar3, gbc_Bar3);
upgradeWorker3 = new GameButton();
GridBagConstraints gbc_upgradeWorker3 = new GridBagConstraints();
gbc_upgradeWorker3.fill = GridBagConstraints.BOTH;
gbc_upgradeWorker3.gridx = 1;
gbc_upgradeWorker3.gridy = 0;
workerPanel3.add(upgradeWorker3, gbc_upgradeWorker3);
upgradeWorker3.setLayout(new BorderLayout(0, 0));
upgradeWorker3_1 = new GLabel("Upgrade", upgradeWorker3, SwingConstants.CENTER);
upgradeWorker3.add(upgradeWorker3_1);
workerPanel4 = new JPanel();
workerPanel4.setBackground(new Color(0, 0, 0, 0));
GridBagLayout gbl_workerPanel4 = new GridBagLayout();
gbl_workerPanel4.columnWidths = new int[]{119, 118, 0};
gbl_workerPanel4.rowHeights = new int[]{36, 0};
gbl_workerPanel4.columnWeights = new double[]{0.0, 0.0, Double.MIN_VALUE};
gbl_workerPanel4.rowWeights = new double[]{0.0, Double.MIN_VALUE};
workerPanel4.setLayout(gbl_workerPanel4);
Bar4 = new GProgressbar();
Bar4.setStringPainted(true);
GridBagConstraints gbc_Bar4 = new GridBagConstraints();
gbc_Bar4.fill = GridBagConstraints.BOTH;
gbc_Bar4.insets = new Insets(0, 0, 0, 5);
gbc_Bar4.gridx = 0;
gbc_Bar4.gridy = 0;
workerPanel4.add(Bar4, gbc_Bar4);
upgradeWorker4 = new GameButton();
GridBagConstraints gbc_upgradeWorker4 = new GridBagConstraints();
gbc_upgradeWorker4.fill = GridBagConstraints.BOTH;
gbc_upgradeWorker4.gridx = 1;
gbc_upgradeWorker4.gridy = 0;
workerPanel4.add(upgradeWorker4, gbc_upgradeWorker4);
upgradeWorker4.setLayout(new BorderLayout(0, 0));
upgradeWorker4_1 = new GLabel("Upgrade", upgradeWorker4, SwingConstants.CENTER);
upgradeWorker4.add(upgradeWorker4_1);
GroupLayout gl_upgradesPanel = new GroupLayout(upgradesPanel);
gl_upgradesPanel.setHorizontalGroup(
gl_upgradesPanel.createParallelGroup(Alignment.LEADING)
.addGroup(gl_upgradesPanel.createSequentialGroup()
.addContainerGap()
.addGroup(gl_upgradesPanel.createParallelGroup(Alignment.LEADING)
.addComponent(workerPanel1, GroupLayout.PREFERRED_SIZE, 238, GroupLayout.PREFERRED_SIZE)
.addComponent(workerPanel2, GroupLayout.PREFERRED_SIZE, 238, GroupLayout.PREFERRED_SIZE)
.addComponent(workerPanel3, GroupLayout.PREFERRED_SIZE, 238, GroupLayout.PREFERRED_SIZE)
.addComponent(workerPanel4, GroupLayout.PREFERRED_SIZE, 238, GroupLayout.PREFERRED_SIZE))
.addContainerGap(15, Short.MAX_VALUE))
);
gl_upgradesPanel.setVerticalGroup(
gl_upgradesPanel.createParallelGroup(Alignment.LEADING)
.addGroup(gl_upgradesPanel.createSequentialGroup()
.addContainerGap()
.addComponent(workerPanel1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(workerPanel2, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(workerPanel3, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(workerPanel4, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addContainerGap(20, Short.MAX_VALUE))
);
upgradesPanel.setLayout(gl_upgradesPanel);
specialPanel = new JPanel();
specialPanel.setBackground(new Color(0,0,0,0.2f));
specialPanel.setBounds(6, 6, 288, 203);
gamePanel.add(specialPanel);
specialPanel.setLayout(null);
String[] columnNames = {"Upgrades", ""};
Object[][] data =
{
{"Vozík +2", "2000$"},
{"Kalhoty +3", "15000$"},
{"Šperháky +4", "50000$"},
{"Auto *2", "200000$"},
};
DefaultTableModel model = new DefaultTableModel(data, columnNames){
#Override
public boolean isCellEditable(int row, int column) {
if(column != 1) return false;
else return true;
}
};
table = new JTable( model );
Action upgradeMultiplier = new AbstractAction()
{
int count = 0;
public void actionPerformed(ActionEvent e)
{
/*
*
JTable table = (JTable)e.getSource();
int modelRow = Integer.valueOf( e.getActionCommand() );
String sPrice = (String) table.getModel().getValueAt(modelRow, 1);
int price = Integer.parseInt(sPrice.substring(0,sPrice.length()-1));
String sMultip = (String) table.getModel().getValueAt(modelRow, 0);
if(sMultip.lastIndexOf("*") != -1) {
int multip = Integer.parseInt(sMultip.substring(sMultip.lastIndexOf("*")+1,sMultip.length()));
if(player.money.getMoney() >= price) {
player.money.deduct(price);
worker.multiplyMultiplier(multip);
((DefaultTableModel)table.getModel()).removeRow(modelRow);
}
} else if(sMultip.lastIndexOf("+") != -1) {
int multip = Integer.parseInt(sMultip.substring(sMultip.lastIndexOf("+")+1,sMultip.length()));
if(player.money.getMoney() >= price) {
player.money.deduct(price);
worker.plusMultiplier(multip);
((DefaultTableModel)table.getModel()).removeRow(modelRow);
}
}
progressBar1.setString(worker.getProfit()+"$");
lblMultiplier.setText(worker.multiplier+"x");
*
*/
}
};
ButtonColumn buttonColumn = new ButtonColumn(table, upgradeMultiplier , 1);
buttonColumn.setMnemonic(KeyEvent.VK_D);
table.setBounds(8, 55, 272, 142);
specialPanel.add(table);
String[] columnNames2 = {"Upgrades", ""};
Object[][] data2 =
{
{"Special +1", "2000$"},
{"Special +3", "15000$"},
{"Special +4", "50000$"},
{"SPecial *2", "200000$"},
};
DefaultTableModel model2 = new DefaultTableModel(data2, columnNames2){
#Override
public boolean isCellEditable(int row, int column) {
if(column != 1) return false;
else return true;
}
};
table2 = new JTable( model2 );
Action specialUpgrade = new AbstractAction()
{
int count = 0;
public void actionPerformed(ActionEvent e)
{
/*
*
JTable table = (JTable)e.getSource();
int modelRow = Integer.valueOf( e.getActionCommand() );
String sPrice = (String) table.getModel().getValueAt(modelRow, 1);
int price = Integer.parseInt(sPrice.substring(0,sPrice.length()-1));
String sMultip = (String) table.getModel().getValueAt(modelRow, 0);
if(sMultip.lastIndexOf("*") != -1) {
int multip = Integer.parseInt(sMultip.substring(sMultip.lastIndexOf("*")+1,sMultip.length()));
if(player.money.getMoney() >= price) {
player.money.deduct(price);
worker.multiplyMultiplier(multip);
((DefaultTableModel)table.getModel()).removeRow(modelRow);
}
} else if(sMultip.lastIndexOf("+") != -1) {
int multip = Integer.parseInt(sMultip.substring(sMultip.lastIndexOf("+")+1,sMultip.length()));
if(player.money.getMoney() >= price) {
player.money.deduct(price);
worker.plusMultiplier(multip);
((DefaultTableModel)table.getModel()).removeRow(modelRow);
}
}
progressBar1.setString(worker.getProfit()+"$");
lblMultiplier.setText(worker.multiplier+"x");
*
*/
}
};
ButtonColumn buttonColumn2 = new ButtonColumn(table, specialUpgrade , 1);
buttonColumn2.setMnemonic(KeyEvent.VK_D);
table2.setBounds(8, 55, 272, 142);
table2.setVisible(false);
specialPanel.add(table2);
upgradesButton = new GameButton();
upgradesButton.setBounds(8, 6, 121, 43);
specialPanel.add(upgradesButton);
upgradesButton.setBackground(new Color(0,0,0,0));
upgradesButton.setLayout(new BorderLayout(0, 0));
GLabel label4 = new GLabel("Upgrades", (GameButton) upgradesButton, SwingConstants.CENTER);
label4.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
table.setVisible(true);
table2.setVisible(false);
}
});
upgradesButton.add(label4);
JPanel specialsButton = new GameButton();
specialsButton.setBounds(159, 6, 121, 43);
specialPanel.add(specialsButton);
specialsButton.setBackground(new Color(0,0,0,0));
specialsButton.setLayout(new BorderLayout(0, 0));
GLabel lblSpecials = new GLabel("Specials", (GameButton) specialsButton, SwingConstants.CENTER);
lblSpecials.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
table.setVisible(false);
table2.setVisible(true);
}
});
specialsButton.add(lblSpecials);
}
}
GamePanel extends JPanel
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class GamePanel extends JPanel {
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
try {
final BufferedImage image = ImageIO.read(new File("./res/gameBackground.jpg"));
g.drawImage(image, 0, 0, 300, 400, this);
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JProgressBar;
public class GProgressbar extends JProgressBar {
private static final long serialVersionUID = 1L;
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
}
}
GameButton extends JPanel
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class GameButton extends JPanel {
private static final long serialVersionUID = 1L;
boolean entered = false;
boolean pressed = false;
GameButton that = this;
public GameButton() {
this.setOpaque(true);
this.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
that.entered = true;
that.repaint();
}
#Override
public void mouseExited(MouseEvent e) {
that.entered = false;
that.repaint();
}
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
that.pressed = true;
that.repaint();
}
#Override
public void mouseReleased(MouseEvent e) {
that.pressed = false;
that.repaint();
}
});
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(new Color(0,0,0,0));
g.fillRect(0, 0, WIDTH, HEIGHT);
if(!entered) {
try {
final BufferedImage image = ImageIO.read(new File("./res/button.gif"));
g.drawImage( image, 0, 0, this.getWidth(), this.getHeight(), this);
} catch(IOException e) {
e.printStackTrace();
}
} else if(pressed){
try {
final BufferedImage image = ImageIO.read(new File("./res/buttonpressed.gif"));
g.drawImage( image, 0, 0, this.getWidth(), this.getHeight(), this);
} catch(IOException e) {
e.printStackTrace();
}
} else {
try {
final BufferedImage image = ImageIO.read(new File("./res/buttonactive.gif"));
g.drawImage( image, 0, 0, this.getWidth(), this.getHeight(), this);
} catch(IOException e) {
e.printStackTrace();
}
}
}
}
GLabel extends JLabel
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JLabel;
public class GLabel extends JLabel{
GameButton that;
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(new Color(0,0,0,0));
g.fillRect(0, 0, WIDTH, HEIGHT);
}
public GLabel(String s, GameButton that, int center) {
this.setText(s);
this.that = that;
this.setHorizontalAlignment(center);
setForeground(Color.BLACK);
setFont(Menu.fontTerminal.deriveFont(15f));
setBackground(new Color(0,0,0,0));
this.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
that.entered = true;
that.repaint();
}
#Override
public void mouseExited(MouseEvent e) {
that.entered = false;
that.repaint();
}
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
that.pressed = true;
that.repaint();
}
#Override
public void mouseReleased(MouseEvent e) {
that.pressed = false;
that.repaint();
}
});
}
}
I want to make the background fully transparent.
Then all you need is:
component.setOpaque( false );
If you need partial transparency of the background then you will get artifacts as you will be breaking the painting contract with Swing components and the opaque property. Check out
Backgrounds With Transparency for more information and solutions to this problem.
Looks like you set a fully transparent JPanel for 'workerPanel1'.
As such, the background is showing behind the JPanel.
Instead of:
workerPanel1.setBackground(new Color(0,0,0,0))
use:
workerPanel1.setBackground(new Color(0,0,0))
(which is the same as: new Color(0,0,0,255))
Edit:
If you wish to keep a transparent panel, you can do so with JPanel#setOpaque(false).
When opaque is false, the panel does not draw its background at all and you will have to keep in mind whatever is displayed behind that panel.
Currently, you have two buttons showing behind it, so you might setVisible(false) them or remove them while this panel is active.
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);
}
}
}