Picture slideshow with fade in/fade out on a JPanel - java

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);
}
}
}

Related

Multiple JComboBoxes with ActionListener

This code was taken from my original code and modified for testing purposes.
Question: Why is it that after clicking on a JComboBox, I cannot click on any other JComboBoxes?
Purpose: After clicking on the JComboBox, the selection gets copied down to the JTextField.
I have read many other posts on StackOverflow and made those changes accordingly, yet they have not solved the problem.
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class Test implements ActionListener {
JComboBox[] cb;
JTextField[] text = new JTextField[3];
JFrame frame2;
public static void main(String[] args) {
Test t = new Test();
t.changeEntry();
}
private void changeEntry() {
frame2 = new JFrame();
frame2.setLayout(new BorderLayout());
Panel p = new Panel();
p.setLayout(new GridLayout(3, 3));
initialize(p);
JTextField url = new JTextField();
JTextField username = new JTextField();
JPasswordField password = new JPasswordField();
addTextField(p, 0, url);
addTextField(p, 1, username);
addPassField(p, 2, password);
frame2.add(p, "Center");
frame2.setTitle("Entries");
frame2.setVisible(true);
frame2.setSize(500, 500);
frame2.setLocation(430, 100);
frame2.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
private void initialize(Panel p) {
String[] array1 = {"A"};
String[] array2 = {"B"};
String[] array3 = {"C"};
JComboBox aa = new JComboBox<String>(array1);
JComboBox bb = new JComboBox<String>(array2);
JComboBox cc = new JComboBox<String>(array3);
cb = new JComboBox[3];
cb[0] = aa;
cb[0].addActionListener(this);
cb[0].setActionCommand("A");
cb[1] = bb;
cb[1].addActionListener(this);
cb[1].setActionCommand("B");
cb[2] = cc;
cb[2].addActionListener(this);
cb[2].setActionCommand("C");
p.add(cb[0]);
p.add(cb[1]);
p.add(cb[2]);
}
#Override
public void actionPerformed(ActionEvent e) {
String s = e.getActionCommand();
if (s.equals("A")) {
checkSelection(cb[0], 0);
} else if (s.equals("B")) {
checkSelection(cb[1], 1);
} else if (s.equals("C")) {
checkSelection(cb[2], 2);
}
}
private void checkSelection(JComboBox cb, int i) {
String str = (String) cb.getSelectedItem();
text[i].setText(str);
}
private void addTextField(Container c, int i, JTextField tf) {
tf.setText("Edit entry here");
tf.setEditable(true);
c.add(tf);
text[i] = tf;
}
private void addPassField(Container c, int i, JPasswordField pf) {
pf.setText("test");
pf.setEditable(true);
c.add(pf);
text[i] = pf;
}
}
My professor and I looked over the code and found out that JComboBoxes do not like overlapping with JTextFields. This is the modification to the code that makes the error go away:
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class Test implements ActionListener {
JComboBox[] cb;
JTextField[] text = new JTextField[3];
JFrame frame2;
public static void main(String[] args) {
Test t = new Test();
t.changeEntry();
}
private void changeEntry() {
frame2 = new JFrame();
frame2.setLayout(new BorderLayout());
Panel p = new Panel();
p.setLayout(new GridLayout(2, 3));
JTextField url = new JTextField();
JTextField username = new JTextField();
JPasswordField password = new JPasswordField();
addTextField(p, 0, url);
addTextField(p, 1, username);
addPassField(p, 2, password);
initialize(p);
frame2.add(p, "Center");
frame2.setTitle("Entries");
frame2.setVisible(true);
frame2.setSize(500, 500);
frame2.setLocation(430, 100);
frame2.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
private void initialize(Panel p) {
String[] array1 = {"A"};
String[] array2 = {"B"};
String[] array3 = {"C"};
JComboBox aa = new JComboBox<String>(array1);
JComboBox bb = new JComboBox<String>(array2);
JComboBox cc = new JComboBox<String>(array3);
cb = new JComboBox[3];
cb[0] = aa;
cb[0].addActionListener(this);
cb[0].setActionCommand("A");
cb[1] = bb;
cb[1].addActionListener(this);
cb[1].setActionCommand("B");
cb[2] = cc;
cb[2].addActionListener(this);
cb[2].setActionCommand("C");
p.add(cb[0]);
p.add(cb[1]);
p.add(cb[2]);
}
#Override
public void actionPerformed(ActionEvent e) {
String s = e.getActionCommand();
if (s.equals("A")) {
checkSelection(cb[0], 0);
} else if (s.equals("B")) {
checkSelection(cb[1], 1);
} else if (s.equals("C")) {
checkSelection(cb[2], 2);
}
}
private void checkSelection(JComboBox cb, int i) {
String str = (String) cb.getSelectedItem();
text[i].setText(str);
}
private void addTextField(Container c, int i, JTextField tf) {
tf.setText("Edit entry here");
tf.setEditable(true);
c.add(tf);
text[i] = tf;
}
private void addPassField(Container c, int i, JPasswordField pf) {
pf.setText("test");
pf.setEditable(true);
c.add(pf);
text[i] = pf;
}
}
So, for anyone having this problem, look at the differences between my question and the modification:
p.setLayout(new GridLayout(3, 3));
initialize(p);
JTextField url = new JTextField();
JTextField username = new JTextField();
JPasswordField password = new JPasswordField();
addTextField(p, 0, url);
addTextField(p, 1, username);
addPassField(p, 2, password);
to
p.setLayout(new GridLayout(2, 3));
JTextField url = new JTextField();
JTextField username = new JTextField();
JPasswordField password = new JPasswordField();
addTextField(p, 0, url);
addTextField(p, 1, username);
addPassField(p, 2, password);
initialize(p);

How I supposed to make program to stop and wait for something? JAVA

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");
}
});
}
}
}

Graphics artifacts appear here in JPanel [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.

JProgressBar Gets Squeezed/ Resizes Improperly

I'm using a JProgressBar on my Swing gui:
When I minimize the window while it's updating with progressBar.setValue() it will squeeze like this:
Note that resizing or similar doesn't fix it.
Why does it happen and how to prevent it? What causes it? I want the progressbar to stay the same size like in the first image.
I'm using the GridBagLayout.
Code to reproduce:
import javax.swing.JFrame;
import javax.swing.SwingWorker;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import javax.swing.JProgressBar;
import java.awt.GridBagConstraints;
import javax.swing.JButton;
import java.awt.Insets;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
#SuppressWarnings("serial")
public class ProgressBarSqueezeFixedExample extends JFrame
{
public ProgressBarSqueezeFixedExample()
{
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(500, 500);
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[] { 0, 0, 0 };
gridBagLayout.rowHeights = new int[] { 0, 0, 0, 0, 0 };
gridBagLayout.columnWeights = new double[] { 1.0, 0.0, Double.MIN_VALUE };
gridBagLayout.rowWeights = new double[] { 0.0, 0.0, 0.0, 1.0,
Double.MIN_VALUE };
getContentPane().setLayout(gridBagLayout);
JProgressBar progressBar = new JProgressBar();
JTextArea textArea = new JTextArea();
JButton btnRun = new JButton("Run");
setPreferredSize(new Dimension(200, 200));
btnRun.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
SwingWorker<String, String> worker = new SwingWorker<String, String>()
{
#Override
protected String doInBackground() throws Exception
{
for (int i = 0; i < 10001; i++)
{
try
{
Thread.sleep(1);
} catch (InterruptedException e)
{
e.printStackTrace();
}
progressBar.setValue(i);
progressBar.setString(i + " %");
textArea.append(i + System.lineSeparator());
}
return null;
}
};
worker.execute();
}
});
GridBagConstraints gbc_btnRun = new GridBagConstraints();
gbc_btnRun.insets = new Insets(0, 0, 5, 5);
gbc_btnRun.gridx = 0;
gbc_btnRun.gridy = 0;
getContentPane().add(btnRun, gbc_btnRun);
JLabel lblProgress = new JLabel("Progress");
GridBagConstraints gbc_lblProgress = new GridBagConstraints();
gbc_lblProgress.insets = new Insets(0, 0, 5, 5);
gbc_lblProgress.gridx = 0;
gbc_lblProgress.gridy = 1;
getContentPane().add(lblProgress, gbc_lblProgress);
progressBar.setMaximum(10000);
progressBar.setStringPainted(true);
progressBar.setMinimumSize(progressBar.getPreferredSize()); // Fixes squeezing issues
GridBagConstraints gbc_progressBar = new GridBagConstraints();
gbc_progressBar.insets = new Insets(0, 0, 5, 5);
gbc_progressBar.gridx = 0;
gbc_progressBar.gridy = 2;
getContentPane().add(progressBar, gbc_progressBar);
JScrollPane scrollPane = new JScrollPane();
GridBagConstraints gbc_scrollPane = new GridBagConstraints();
gbc_progressBar.fill=GridBagConstraints.HORIZONTAL; // Alternate fix
gbc_scrollPane.gridwidth = 2;
gbc_scrollPane.fill = GridBagConstraints.BOTH;
gbc_scrollPane.gridx = 0;
gbc_scrollPane.gridy = 3;
getContentPane().add(scrollPane, gbc_scrollPane);
scrollPane.setViewportView(textArea);
pack();
setVisible(true);
}
public static void main(String[] args)
{
new ProgressBarSqueezeFixedExample();
}
}
The resizing of the gui and squeezing the progressbar has to to with the textArea append() how it seems.
Use GridBagConstraints#fill property that is used when the component's display area is larger than the component's requested size. It determines whether to resize the component.
gbc_progressBar.fill=GridBagConstraints.HORIZONTAL;
Note: There is no need to create multiple instance of GridBagConstraints. you can achieve same thing using single object as well.
Read more about How to Use GridBagLayout and have a look at the example.

JLabel alignment issues

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);
}

Categories