Java - set a size to JDialog - java

I have a strange problem, i did two class (They are very similar), but in the first Class the setPreferredSize method, works in the other not; so i have to use (in this class) setSize() method. And this is really strange. I post my code:
In this class it works well
package StudentNotes;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Timer;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import StudentNotes.TextPrompt.Show;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
public class CreateCourse extends JDialog {
private JTextField tFieldCourseName;
/**
* Create the dialog.
*/
public CreateCourse(JDialog mainFrame, final StudApp studAppObj) {
super(mainFrame, ModalityType.APPLICATION_MODAL);
setPreferredSize(new Dimension(330, 200)); //it works
setTitle("Create a course");
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setAlwaysOnTop(true);
tFieldCourseName = new JTextField();
tFieldCourseName.setFont(new Font("Tahoma", Font.BOLD, 14));
tFieldCourseName.setColumns(10);
TextPrompt tp = new TextPrompt("Course name", tFieldCourseName);
tp.changeStyle(Font.ITALIC);
tp.setShow(Show.ALWAYS);
tp.setForeground(Color.GRAY);
final JLabel lblAllertcourse = new JLabel("");
lblAllertcourse.setHorizontalAlignment(SwingConstants.CENTER);
JButton btnAddCourse = new JButton("Add course");
btnAddCourse.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
javax.swing.Timer t = new javax.swing.Timer(2000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
lblAllertcourse.setText("");
}
});
String nameCourse = tFieldCourseName.getText();
ArrayList<Corso> courses = studAppObj.getCorsi();
if (nameCourse.equals("")) {
lblAllertcourse.setText("Insert a valid name course!");
t.setRepeats(false);
t.start();
return;
}
for (Corso currentCourse : courses) {
if (currentCourse.name.toUpperCase().equals(nameCourse.toUpperCase())) {
lblAllertcourse.setText("This course already exist!");
t.setRepeats(false);
t.start();
return;
}
}
studAppObj.setCorsi(new Corso(), nameCourse);
lblAllertcourse.setText("Course added successfully");
t.setRepeats(false);
t.start();
}
});
GroupLayout groupLayout = new GroupLayout(getContentPane());
groupLayout.setHorizontalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addGap(113)
.addComponent(btnAddCourse))
.addGroup(groupLayout.createSequentialGroup()
.addGap(103)
.addComponent(tFieldCourseName, GroupLayout.PREFERRED_SIZE, 119, GroupLayout.PREFERRED_SIZE))
.addGroup(groupLayout.createSequentialGroup()
.addContainerGap()
.addComponent(lblAllertcourse, GroupLayout.DEFAULT_SIZE, 304, Short.MAX_VALUE)))
.addContainerGap())
);
groupLayout.setVerticalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addGap(46)
.addComponent(tFieldCourseName, GroupLayout.PREFERRED_SIZE, 28, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(btnAddCourse)
.addPreferredGap(ComponentPlacement.UNRELATED)
.addComponent(lblAllertcourse)
.addContainerGap(44, Short.MAX_VALUE))
);
getContentPane().setLayout(groupLayout);
pack();
setLocationRelativeTo(null);
setResizable(false);
setVisible(true);
}
}
in this other class setPreferredSize does not work, the JDialog doesnt have a size so it reamins small ( i can just see the title of the Dialog and not more).
package StudentNotes;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.ScrollPaneConstants;
public class EditCourse extends JDialog {
/**
* Create the dialog.
*/
public EditCourse(JDialog mainFrame, final StudApp studAppObj) {
super(mainFrame, ModalityType.APPLICATION_MODAL);
//I have to use setSize
// if i use setPreferredSize does not work
setSize(new Dimension(330, 200));
setTitle("Edit course");
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setAlwaysOnTop(true);
ArrayList<Corso> listCourses = studAppObj.getCorsi();
listCourses.toArray();
String[] listData = { "one", "two", "three", "four",
"five", "six", "seven" };
JList list = new JList(listData);
list.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting() == true) {
ListSelectionModel lsm = (ListSelectionModel)e.getSource();
int minIndex = lsm.getMinSelectionIndex();
int maxIndex = lsm.getMaxSelectionIndex();
for (int i=minIndex; i<=maxIndex; i++) {
if (lsm.isSelectedIndex(i)) {
System.out.println("hai selezionato l'indice nr. "+i);
}
}
}
}
});
JScrollPane scrollPane = new JScrollPane(list);
scrollPane.setSize(new Dimension(118, 40));
GroupLayout groupLayout = new GroupLayout(getContentPane());
groupLayout.setHorizontalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addGap(108)
.addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 108, GroupLayout.PREFERRED_SIZE)
.addContainerGap(108, Short.MAX_VALUE))
);
groupLayout.setVerticalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addGap(21)
.addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 64, GroupLayout.PREFERRED_SIZE)
.addContainerGap(87, Short.MAX_VALUE))
);
getContentPane().setLayout(groupLayout);
setLocationRelativeTo(null);
setResizable(false);
setVisible(true);
}
}

In the second class there's no call to pack() method and that's why the dialog remains "small":
public void pack()
Causes this Window to be sized to fit the preferred size and layouts
of its subcomponents. The resulting width and height of the window are
automatically enlarged if either of dimensions is less than the
minimum size as specified by the previous call to the setMinimumSize
method.
If the window and/or its owner are not displayable yet, both of them
are made displayable before calculating the preferred size. The Window
is validated after its size is being calculated.
You should also take a look to this topic: Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?

Related

CardLayout showing blank JPanel in Java

I've searched up different tutorials and looked at the Class Profile for CardLayout and JPanel but I can't seem to get my window to show up. Currently it opens a frame with the proper dimensions and title but nothing in the actual container.
This is the code I have(P.S. I know it's a hot mess)
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
public class Casino extends JFrame implements ActionListener {
private JButton start, settings, scenario, music;
/**
* Constructor method
*/
public Casino(){
JPanel mainUI, startUI, settingsUI, scenarioUI, blackjackUI, oddorevenUI, tcmUI, overorunderUI, slotsUI;
JPanel menus = new JPanel(new CardLayout());
CardLayout GUI = (CardLayout) menus.getLayout();
mainUI = new JPanel();
getContentPane().add(mainUI);
mainUI.setBackground(new Color(53, 9, 9));
//Background items
JLabel title = new JLabel(new ImageIcon("title.png"));
title.setBounds(0,-280,780,700);
mainUI.add(title);
JLabel border = new JLabel(new ImageIcon("mainscreenborder.png"));
border.setBounds(0, 180, 780, 700);
mainUI.add(border);
//Main menu buttons
settings = new JButton();
ImageIcon s = new ImageIcon("settings-button.png");
settings.setBounds(320, 200, 122, 63);
settings.setIcon(s);
mainUI.add(settings);
music = new JButton();
ImageIcon m = new ImageIcon("music-button.png");
music.setBounds(320, 268, 122, 63);
music.setBackground(new Color(53, 9, 9));
music.setIcon(m);
mainUI.add(music);
scenario = new JButton();
ImageIcon sc = new ImageIcon("scenario-button.png");
scenario.setBounds(320, 336, 122, 63);
scenario.setBackground(new Color(53, 9, 9));
scenario.setIcon(sc);
mainUI.add(scenario);
start = new JButton();
ImageIcon st = new ImageIcon("start-button.png");
start.setBounds(320, 404, 122, 63);
start.setBackground(new Color(53, 9, 9));
start.setIcon(st);
mainUI.add(start);
menus.add(mainUI, "Main Menu");
GUI.show(menus, "Main Menu");
setSize(780, 700);
setResizable(false);
setLayout(GUI);
setTitle("White Lily Casino");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Casino wlc = new Casino();
}
}
Note: It worked before when I was using the Container c method instead of using a JPanel and CardLayout. I am trying to switch it to card layout now because I want to use buttons to navigate to multiple screens
Try adding the mainUI to the JFrame
getContentPane().add(mainUI)
or
add(mainUI)

JTree refresh without collapsing

I have a problem when refreshing a JTree instance. See the following code:
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
public class ItemTest {
private JFrame frame;
private DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
private JTree tree = new JTree(root);
private JButton button = new JButton("Rebuild");
private String[] array = new String[] { "name", "first_name", "middle_name", "last_name"};
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
ItemTest window = new ItemTest();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public ItemTest() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 523, 349);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JScrollPane scrollBar = new JScrollPane();
GroupLayout groupLayout = new GroupLayout(frame.getContentPane());
groupLayout.setHorizontalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addContainerGap()
.addComponent(scrollBar, GroupLayout.PREFERRED_SIZE, 200, GroupLayout.PREFERRED_SIZE)
.addComponent(button, GroupLayout.PREFERRED_SIZE, 85, GroupLayout.PREFERRED_SIZE)
.addContainerGap(412, Short.MAX_VALUE))
);
groupLayout.setVerticalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addGap(22)
.addComponent(scrollBar, GroupLayout.DEFAULT_SIZE, 278, Short.MAX_VALUE)
.addComponent(button, GroupLayout.DEFAULT_SIZE, 25, Short.MAX_VALUE)
.addContainerGap())
);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
root.add(new DefaultMutableTreeNode("Row 4"));
((DefaultTreeModel) tree.getModel()).nodeChanged(root);
}
});
for(String string : array) {
root.add(new DefaultMutableTreeNode(string));
}
scrollBar.setViewportView(tree);
frame.getContentPane().setLayout(groupLayout);
}
}
If we run this code, and expand the "Root" node. We will see 4 nodes in it. If we click the button "Rebuild", the tree won't update it's self. The weird thing is, if we don't expand the "Root" node at the begin (so just start the application) and click the button, and after that we expand the "Root" node, the new row is added. Does anyone knows how to refresh this tree without collapsing, because nodeChanged doesn't seem to work when you expand the "Root" node at the begin.
Note: I have to accomplish this without using insertNodeInto.
You must notify the listeners that a node was inserted:
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
root.add(new DefaultMutableTreeNode("Row 4"));
((DefaultTreeModel) tree.getModel()).nodesWereInserted(
root, new int[]{root.getChildCount()-1});
}
});

How can i change jtextfield border after 5 seconds?

I try to change jtextfield border after 5 seconds. But doesnt work. My code:
// Here vaildate a field and set border to red
if (ApplicationNameField.getText().equals("")) {
Border newBorder = BorderFactory.createLineBorder(Color.RED, 1);
ApplicationNameField.setBorder(newBorder);
ErrorCode.setText("Error field cant be empty");
}
if (ApplicationHostField.getText().equals("")) {
Border newBorder = BorderFactory.createLineBorder(Color.RED, 1);
ApplicationHostField.setBorder(newBorder);
ErrorCode.setText("Error field cant be empty");
}
// here i would change border to start normal color (color black)
try {
TimeUnit.SECONDS.sleep(5);
Border newBorder = BorderFactory.createLineBorder(Color.BLACK, 1);
ApplicationNameField.setBorder(newBorder);
Border newBorder2 = BorderFactory.createLineBorder(Color.BLACK, 1);
ApplicationHostField.setBorder(newBorder2);
} catch (InterruptedException ex) {
System.out.print(ex.getMessage());
}
After this code my JTextFields borders are black and is not colored by red color.
Also i tried with:
Thread.sleep(5000);
But effect is the same. Anyone could help?
You need to use a javax.swing.Timer to trigger the desired action after 5 seconds. Thread.wait (or any other kind of waiting) doesn't work as expected because nothing is drawn until the thread returns to the main event loop.
Agree with #ammoQ. Just provide you an example of the use of javax.swing.Timer.
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.Timer;
import javax.swing.border.AbstractBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
public class TimerTest implements ActionListener{
JTextField textField;
public void createUI(){
JFrame frame = new JFrame("Timer Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
MainPanel mainPanel = new MainPanel();
mainPanel.setBorder(BorderFactory.createEmptyBorder(5, 10, 5, 10));
frame.add(mainPanel,BorderLayout.CENTER);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
Timer timer = new Timer(5 * 1000, this);
timer.start();
}
public static void main(String[] args) {
TimerTest timerTest = new TimerTest();
timerTest.createUI();
}
#SuppressWarnings("serial")
class MainPanel extends JPanel{
public MainPanel(){
textField = new JTextField();
textField.setColumns(30);
textField.setBorder(BorderFactory.createCompoundBorder(
new LineBorder(Color.red, 3),
new EmptyBorder(new Insets(15, 25, 15, 25))));
add(textField,BorderLayout.CENTER);
setBackground(new Color(211,211,211));
setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
}
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
textField.setBorder(BorderFactory.createCompoundBorder(
new LineBorder(Color.black, 3),
new EmptyBorder(new Insets(15, 25, 15, 25))));
}
}
you can use SwingWorker to do this. see my running example below.
import java.awt.Color;
import java.awt.EventQueue;
import javax.swing.BorderFactory;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingWorker;
import javax.swing.border.EmptyBorder;
public class JTextFieldTest extends JFrame {
private JPanel contentPane;
private JTextField textField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
JTextFieldTest frame = new JTextFieldTest();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public JTextFieldTest() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 298, 220);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
textField = new JTextField();
textField.setColumns(10);
textField.setBorder(BorderFactory.createLineBorder(Color.RED));
SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
#Override
protected Void doInBackground() throws Exception {
// Simulate doing something useful.
Thread.sleep(5000);
textField.setBorder(BorderFactory.createLineBorder(Color.BLACK));
return null;
}
};
worker.execute();
GroupLayout gl_contentPane = new GroupLayout(contentPane);
gl_contentPane.setHorizontalGroup(gl_contentPane.createParallelGroup(
Alignment.LEADING).addGroup(
gl_contentPane
.createSequentialGroup()
.addGap(87)
.addComponent(textField, GroupLayout.PREFERRED_SIZE,
GroupLayout.DEFAULT_SIZE,
GroupLayout.PREFERRED_SIZE)
.addContainerGap(99, Short.MAX_VALUE)));
gl_contentPane.setVerticalGroup(gl_contentPane.createParallelGroup(
Alignment.LEADING).addGroup(
gl_contentPane
.createSequentialGroup()
.addGap(70)
.addComponent(textField, GroupLayout.PREFERRED_SIZE,
GroupLayout.DEFAULT_SIZE,
GroupLayout.PREFERRED_SIZE)
.addContainerGap(81, Short.MAX_VALUE)));
contentPane.setLayout(gl_contentPane);
}
}

How to show(add) JTextArea after button click?

i want to show my JTextArea after button CONNECT_BUTTON is clicked. What should I do ? Furthermore i'm trying to add some grid in my JTextArea because I want to use it for show some records from databse. Any ideas how to do that ?
package DataBase_Hospital;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class test extends JFrame implements ActionListener {
private JButton FIND_BUTTON;
private JButton MESSAGE_BUTTON;
private JButton CONNECT_BUTTON;
private JButton CLEAR_BUTTON;
private JButton ADD_BUTTON;
private JButton RAPORT_BUTTON;
private JButton EDIT_BUTTON;
private JButton DOWNLOAD_BUTTON;
private JTextArea DATABASE_FIELD;
private DatabaseManagement DATABASE;
public test(){
setTitle("Hospital Management");
setSize(900,600);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
JLabel background=new JLabel(new ImageIcon("/Users/Dominik/Desktop/j.jpg"));
add(background);
DATABASE_FIELD = new JTextArea();
JScrollPane scrollPane = new JScrollPane(DATABASE_FIELD);
scrollPane.setBounds(50, 50, 800, 400);
background.add(scrollPane);
DATABASE_FIELD.setEditable(true);
DATABASE_FIELD.setLayout(new GridLayout(3, 3));
//DATABASE_FIELD.setVisible(false);
CONNECT_BUTTON = new JButton();
CONNECT_BUTTON.setIcon(new ImageIcon("/Users/Dominik/Desktop/connect_no.png"));
CONNECT_BUTTON.setBounds(165, 500, 60, 60);
background.add(CONNECT_BUTTON);
CONNECT_BUTTON.addActionListener(this);
CONNECT_BUTTON.setToolTipText("Connect to Data Base");
FIND_BUTTON = new JButton();
FIND_BUTTON.setIcon(new ImageIcon("/Users/Dominik/Desktop/search.png"));
FIND_BUTTON.setBounds(240, 500, 60, 60);
background.add(FIND_BUTTON);
FIND_BUTTON.addActionListener(this);
FIND_BUTTON.setToolTipText("Find record in Data Base");
ADD_BUTTON = new JButton();
ADD_BUTTON.setIcon(new ImageIcon("/Users/Dominik/Desktop/user_add.png"));
ADD_BUTTON.setBounds(315, 500, 60, 60);
background.add(ADD_BUTTON);
ADD_BUTTON.addActionListener(this);
ADD_BUTTON.setToolTipText("Add record to Data Base");
RAPORT_BUTTON = new JButton();
RAPORT_BUTTON.setIcon(new ImageIcon("/Users/Dominik/Desktop/raport.png"));
RAPORT_BUTTON.setBounds(392, 500, 60, 60);
background.add(RAPORT_BUTTON);
RAPORT_BUTTON.addActionListener(this);
RAPORT_BUTTON.setToolTipText("Generates raport");
EDIT_BUTTON = new JButton();
EDIT_BUTTON.setIcon(new ImageIcon("/Users/Dominik/Desktop/user_edit.png"));
EDIT_BUTTON.setBounds(467, 500, 60, 60);
background.add(EDIT_BUTTON);
EDIT_BUTTON.addActionListener(this);
EDIT_BUTTON.setToolTipText("Edit record from Data Base");
CLEAR_BUTTON = new JButton();
CLEAR_BUTTON.setIcon(new ImageIcon("/Users/Dominik/Desktop/delete.png"));
CLEAR_BUTTON.setBounds(544, 500, 60, 60);
background.add(CLEAR_BUTTON);
CLEAR_BUTTON.addActionListener(this);
CLEAR_BUTTON.setToolTipText("Clear all Data Base");
MESSAGE_BUTTON = new JButton();
MESSAGE_BUTTON.setIcon(new ImageIcon("/Users/Dominik/Desktop/message.png"));
MESSAGE_BUTTON.setBounds(619, 500, 60, 60);
background.add(MESSAGE_BUTTON);
MESSAGE_BUTTON.addActionListener(this);
MESSAGE_BUTTON.setToolTipText("Send message to another user");
DOWNLOAD_BUTTON = new JButton();
DOWNLOAD_BUTTON.setIcon(new ImageIcon("/Users/Dominik/Desktop/download.png"));
DOWNLOAD_BUTTON.setBounds(694, 500, 60, 60);
background.add(DOWNLOAD_BUTTON);
DOWNLOAD_BUTTON.addActionListener(this);
DOWNLOAD_BUTTON.setToolTipText("Download Data Base to a text file");
validate();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
test window = new test();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
Object EVENT_SOURCE = e.getSource();
DATABASE = new DatabaseManagement();
if (EVENT_SOURCE == CLEAR_BUTTON)
{
System.out.println("siema");
}
else if (EVENT_SOURCE == DOWNLOAD_BUTTON)
{
dispose();
}
else if (EVENT_SOURCE == CONNECT_BUTTON)
{
DATABASE_FIELD.setText("");
//** TRZEBA ZROBIC SIATKE !!! **//
DATABASE_FIELD.append("IMIE ");
DATABASE_FIELD.append("NAZWISKO ");
DATABASE_FIELD.append("PESEL \n");
DATABASE_FIELD.append(DATABASE.showDataBase());
}
}
}
you have to set proper LayoutManager in the case that you want to use JLabel as container (Grid or FlowLayout)
don't to use NullLayout
JTextArea isn't designated to be a container remove DATABASE_FIELD.setLayout(new GridLayout(3, 3));
use JTextArea (10, 15) as intial size instead of any sizing (then valid for JScrollPane too)
add JScrollPane with JTextArea to JFrames CENTER area or to change JLabels LayoutManager to BorderLayout, then to put JButtons to another separate JLabel (Grid or FlowLayout)
setTitle("Hospital Management");
setSize(900,600);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
to move those code lines to the end of constructor, then remove validate, as aside should be revalidate() and repaint(), becuase you didn't stop for Image repainting
call pack() instead of setSize
See Initial Thread
only 1quater of possible issues, just about most important things

How to close main frame when open new one

Ive created two frames my main frame is Home and the second one is Selectie
On home there is a button which open the frame selectie, but i want when i click this button the main frame home wil dissapear and only selectie will be shown. The code for the button ive make in a other package and i dont want it in the same class as my main (home)
Code from Home:
package View;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import Controller.HomeController;
import music.PlaySound;
public class Home extends JFrame {
private JLabel label, label1, label2;
private JPanel panel;
private JButton logo, logo1, logo2, logo3, logo4, logo5, selectie;
private Container window = getContentPane();
private HomeController Controller;
public Home (){
initGUI();
Controller = new HomeController();
}
public void addHomeListener(ActionListener a){
selectie.addActionListener(a);
}
public void initGUI(){
setLayout(null);
setTitle("");
setPreferredSize(new Dimension(800,600));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
label = new JLabel();
label.setBounds(0, 0, 266, 800);
label.setBackground(Color.WHITE);
label.setOpaque(true);
window.add(label);
label1 = new JLabel();
label1.setBounds(267, 0, 266, 800);
label1.setBackground(Color.RED);
label1.setOpaque(true);
window.add(label1);
label2 = new JLabel();
label2.setBounds(533, 0, 266, 800);
label2.setBackground(Color.WHITE);
label2.setOpaque(true);
window.add(label2);
logo = new JButton(new ImageIcon("../Ajax/src/img/logotje.gif"));
logo.setBorderPainted(false);
logo.setBounds(40, 150, 188, 188);
label1.add(logo);
logo1 = new JButton(new ImageIcon("../Ajax/src/img/Ster.png"));
logo1.setBorderPainted(false);
logo1.setBounds(10, 50, 82, 82);
label1.add(logo1);
logo2 = new JButton(new ImageIcon("../Ajax/src/img/Ster.png"));
logo2.setBorderPainted(false);
logo2.setBounds(92, 20, 82, 82);
label1.add(logo2);
logo3 = new JButton(new ImageIcon("../Ajax/src/img/Ster.png"));
logo3.setBorderPainted(false);
logo3.setBounds(174, 50, 82, 82);
label1.add(logo3);
logo4 = new JButton(new ImageIcon("../Ajax/src/img/shirt.png"));
logo4.setBorderPainted(false);
logo4.setBounds(50, 50, 135, 182);
label.add(logo4);
logo5 = new JButton(new ImageIcon("../Ajax/src/img/uitshirt.png"));
logo5.setBorderPainted(false);
logo5.setBounds(65, 50, 138, 190);
label2.add(logo5);
selectie = new JButton("Selectie");
selectie.setBounds(60, 500, 99, 25);
selectie.setActionCommand("selectie");
label.add(selectie);
pack();
addHomeListener(new HomeController());
}
}
Code from the button:
package Controller;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import View.Home;
import View.Selectie;
public class HomeController implements ActionListener {
public void actionPerformed (ActionEvent e){
Selectie selectie = new Selectie();
selectie.setVisible(true);
}
}
Please do give valid attention to what #kleopatra and #mKorbel, has to say, they are very much right in pointing that out to you to make things easier.
Here I had added some comments in the code, do check this out :
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionListener;
import java.io.File;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
//import Controller.HomeController;
//import music.PlaySound;
public class Home extends JFrame {
private JLabel label, label1, label2;
private JPanel panel;
private JButton logo, logo1, logo2, logo3, logo4, logo5, selectie;
private Container window = getContentPane();
private HomeController Controller;
public Home (){
initGUI();
}
public void addHomeListener(ActionListener a){
selectie.addActionListener(a);
}
public void initGUI(){
setLayout(null);
setTitle("");
setPreferredSize(new Dimension(800,600));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
label = new JLabel();
label.setBounds(0, 0, 266, 800);
label.setBackground(Color.WHITE);
label.setOpaque(true);
window.add(label);
label1 = new JLabel();
label1.setBounds(267, 0, 266, 800);
label1.setBackground(Color.RED);
label1.setOpaque(true);
window.add(label1);
label2 = new JLabel();
label2.setBounds(533, 0, 266, 800);
label2.setBackground(Color.WHITE);
label2.setOpaque(true);
window.add(label2);
logo = new JButton(new ImageIcon("../Ajax/src/img/logotje.gif"));
logo.setBorderPainted(false);
logo.setBounds(40, 150, 188, 188);
label1.add(logo);
logo1 = new JButton(new ImageIcon("../Ajax/src/img/Ster.png"));
logo1.setBorderPainted(false);
logo1.setBounds(10, 50, 82, 82);
label1.add(logo1);
logo2 = new JButton(new ImageIcon("../Ajax/src/img/Ster.png"));
logo2.setBorderPainted(false);
logo2.setBounds(92, 20, 82, 82);
label1.add(logo2);
logo3 = new JButton(new ImageIcon("../Ajax/src/img/Ster.png"));
logo3.setBorderPainted(false);
logo3.setBounds(174, 50, 82, 82);
label1.add(logo3);
logo4 = new JButton(new ImageIcon("../Ajax/src/img/shirt.png"));
logo4.setBorderPainted(false);
logo4.setBounds(50, 50, 135, 182);
label.add(logo4);
logo5 = new JButton(new ImageIcon("../Ajax/src/img/uitshirt.png"));
logo5.setBorderPainted(false);
logo5.setBounds(65, 50, 138, 190);
label2.add(logo5);
selectie = new JButton("Selectie");
selectie.setBounds(60, 500, 99, 25);
selectie.setActionCommand("selectie");
label.add(selectie);
pack();
/*
* You are making a new object again,
* when you already had declared it as
* an instance Variable. So I used the
* one declared as instance variable..
* To this we will send the object of Home
* class, means the object of this class..
* And as we know that object of the
* class we are in is by default known
* as this, so passing this to HomeController class.
*/
Controller = new HomeController(this);
addHomeListener(Controller);
setVisible(true);
}
public static void main(String... args)
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new Home();
}
});
}
}
class HomeController implements ActionListener {
/*
* Here we declared a Home class's variable,
* that we will use to dispose that JFrame.
*/
private Home home;
public HomeController(Home home)
{
this.home = home;
}
public void actionPerformed (ActionEvent e){
home.dispose();
Selectie selectie = new Selectie();
selectie.setVisible(true);
}
}
class Selectie extends JFrame
{
public Selectie()
{
initGUI();
}
public void initGUI()
{
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationByPlatform(true);
setSize(300, 300);
}
}
I'd suggest to use CardLayout, most easiest, very confortable for (+1 for SSCCE) your code posted here
never create, re_create bunch of another JFrames, only in the cases that you have got very important reasons, then use JDialog with parent to the JFrame

Categories

Resources