I'm creating a simple gui of options that containing a JScrollPanel.
The problem is when I'm scrolling all the content of the JPanel inside my JScrollPanel doesn't refresh like that :
Bad Refresh Scrolling
Another issues is that not all my text fields are well painted and the combobox fields are behind the first text field.
Here my code :
OptionsPanel.java the source of the problem
package scroll;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.TextEvent;
import java.awt.event.TextListener;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import scroll.NavigationButtons.Navigation;
public class OptionsPanel extends JPanel implements ActionListener, TextListener {
private static final long serialVersionUID = 3800714599366218432L;
private NavigationButtons navBtn;
private ChangeOptionCB language;
private ChangeOptionTF option1;
private ChangeOptionTF option2;
private ChangeOptionTF option3;
private ChangeOptionTF option4;
private ChangeOptionTF option5;
private ChangeOptionTF option6;
private ChangeOptionTF option7;
private JScrollPane scrollPane;
public OptionsPanel() {
super();
GridBagLayout layout = new GridBagLayout();
setLayout(layout);
GridBagConstraints constraint = new GridBagConstraints();
JPanel optionsPanel = new JPanel();
GridBagLayout l = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
optionsPanel.setLayout(l);
String[] langues = {"en", "fr", "es"};
language = new ChangeOptionCB("Languages", langues);
language.addTextListener(this);
c.gridx = 0;
c.gridy = 0;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.PAGE_START;
c.weightx = 1;
c.weighty = 0.1;
optionsPanel.add(language, c);
option1 = new ChangeOptionTF("option 1");
option1.addTextListener(this);
option1.setText("option 1");
c.gridx = 0;
c.gridy = 1;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.PAGE_START;
c.weightx = 1;
c.weighty = 0.1;
optionsPanel.add(option1, c);
option2 = new ChangeOptionTF("option 2");
option2.addTextListener(this);
option2.setText("option 2");
c.gridx = 0;
c.gridy = 2;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.PAGE_START;
c.weightx = 1;
c.weighty = 0.1;
optionsPanel.add(option2, c);
option3 = new ChangeOptionTF("option 3");
option3.addTextListener(this);
option3.setText("option 3");
c.gridx = 0;
c.gridy = 3;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.PAGE_START;
c.weightx = 1;
c.weighty = 0.1;
optionsPanel.add(option3, c);
option4 = new ChangeOptionTF("option 4");
option4.addTextListener(this);
option4.setText("option 4");
c.gridx = 0;
c.gridy = 4;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.PAGE_START;
c.weightx = 1;
c.weighty = 0.1;
optionsPanel.add(option4, c);
option5 = new ChangeOptionTF("option 5");
option5.addTextListener(this);
option5.setText("option 5");
c.gridx = 0;
c.gridy = 5;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.PAGE_START;
c.weightx = 1;
c.weighty = 0.1;
optionsPanel.add(option5, c);
option6 = new ChangeOptionTF("option 6");
option6.addTextListener(this);
option6.setText("option 6");
c.gridx = 0;
c.gridy = 6;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.PAGE_START;
c.weightx = 1;
c.weighty = 0.1;
optionsPanel.add(option6, c);
option7 = new ChangeOptionTF("option 7");
option7.addTextListener(this);
option7.setText("option 7");
c.gridx = 0;
c.gridy = 7;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.PAGE_START;
c.weightx = 1;
c.weighty = 0.1;
optionsPanel.add(option7, c);
scrollPane = new JScrollPane(optionsPanel);
constraint.gridx = 0;
constraint.gridy = 0;
constraint.fill = GridBagConstraints.BOTH;
constraint.weightx = 1;
constraint.weighty = 1;
add(scrollPane, constraint);
navBtn = new NavigationButtons(NavigationButtons.EXIT);
navBtn.addActionListener(this);
constraint.gridx = 0;
constraint.gridy = 1;
constraint.fill = GridBagConstraints.HORIZONTAL;
constraint.weightx = 1;
constraint.weighty = 0.25;
add(navBtn, constraint);
}
#Override
public void actionPerformed(ActionEvent ae) {
if (navBtn == ae.getSource()) {
int id = ae.getID();
if (Navigation.EXIT.getId() == id) {
System.out.println("Get out !!");
}
}
}
#Override
public void textValueChanged(TextEvent te) {
if (language == te.getSource()) {
System.out.println("The option as changed : "+language.getOption());
}
if (option1 == te.getSource()) {
System.out.println("The option as changed : "+option1.getNewText());
}
if (option2 == te.getSource()) {
System.out.println("The option as changed : "+option2.getNewText());
}
if (option3 == te.getSource()) {
System.out.println("The option as changed : "+option3.getNewText());
}
if (option4 == te.getSource()) {
System.out.println("The option as changed : "+option4.getNewText());
}
if (option5 == te.getSource()) {
System.out.println("The option as changed : "+option5.getNewText());
}
if (option6 == te.getSource()) {
System.out.println("The option as changed : "+option6.getNewText());
}
if (option7 == te.getSource()) {
System.out.println("The option as changed : "+option7.getNewText());
}
scrollPane.revalidate();
scrollPane.repaint();
}
}
The Main Class
package scroll;
import java.awt.Dimension;
import javax.swing.JFrame;
public class ScrollTest {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setContentPane(new OptionsPanel());
frame.setTitle("Scrool Test");
frame.pack();
Dimension dimension = new Dimension(691, 263);
frame.setSize(dimension);
frame.setPreferredSize(dimension);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
}
The different stuff that you need :
package scroll;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.TextEvent;
import java.awt.event.TextListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.event.EventListenerList;
public class ChangeOptionCB extends JPanel implements ActionListener {
private static final long serialVersionUID = 3355314012553851743L;
private JComboBox cb;
private JButton saveBtn;
private EventListenerList listeners;
public ChangeOptionCB(String label, String[] list) {
listeners = new EventListenerList();
GridBagLayout layout = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
setLayout(layout);
JLabel jLabel = new JLabel(label);
jLabel.setHorizontalAlignment(SwingConstants.LEFT);
c.fill = GridBagConstraints.LINE_START;
c.gridx = 0;
c.gridy = 0;
c.weightx = 0.1;
add(jLabel, c);
cb = new JComboBox(list);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
c.gridy = 0;
c.weightx = 0.8;
add(cb, c);
saveBtn = new JButton("Save");
saveBtn.addActionListener(this);
c.gridx = 2;
c.gridy = 0;
c.weightx = 0;
c.anchor = GridBagConstraints.LINE_END;
add(saveBtn, c);
}
#Override
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == saveBtn) {
fireTextAsChange();
}
}
public String getOption() {
return (String) cb.getSelectedItem();
}
public void addTextListener(TextListener listener) {
listeners.add(TextListener.class, listener);
}
public void removeActionListener(TextListener listener) {
listeners.remove(TextListener.class, listener);
}
private void fireTextAsChange(){
TextListener[] listenerList = (TextListener[])listeners.getListeners(TextListener.class);
for(TextListener listener : listenerList){
listener.textValueChanged(new TextEvent(this, 0));
}
}
}
package scroll;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.TextEvent;
import java.awt.event.TextListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.event.EventListenerList;
public class ChangeOptionTF extends JPanel implements ActionListener {
private static final long serialVersionUID = 3355314012553851743L;
private TextField tf;
private JButton saveBtn;
private EventListenerList listeners;
public ChangeOptionTF(String label) {
listeners = new EventListenerList();
GridBagLayout layout = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
setLayout(layout);
JLabel jLabel = new JLabel(label);
c.fill = GridBagConstraints.BOTH;
c.gridx = 0;
c.gridy = 0;
c.weightx = 1;
add(jLabel, c);
tf = new TextField();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 1;
c.weightx = 0.5;
add(tf, c);
saveBtn = new JButton("Save");
saveBtn.addActionListener(this);
c.gridx = 2;
c.gridy = 1;
c.weightx = 0;
c.anchor = GridBagConstraints.LINE_END;
add(saveBtn, c);
}
#Override
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == saveBtn) {
fireTextAsChange();
}
}
public String getNewText() {
return tf.getText();
}
public void addTextListener(TextListener listener) {
listeners.add(TextListener.class, listener);
}
public void removeActionListener(TextListener listener) {
listeners.remove(TextListener.class, listener);
}
private void fireTextAsChange(){
TextListener[] listenerList = (TextListener[])listeners.getListeners(TextListener.class);
for(TextListener listener : listenerList){
listener.textValueChanged(new TextEvent(this, 0));
}
}
public void setText(String text) {
tf.setText(text);
}
}
package scroll;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.event.EventListenerList;
public class NavigationButtons extends JPanel implements ActionListener {
private static final long serialVersionUID = -4844499317626526067L;
public enum Navigation {
NEXT(1), CANCEL(0), EXIT(-1);
private int id;
private Navigation(int id) {
this.id = id;
}
public int getId() {
return id;
}
}
public static int NEXT_CANCEL = 0;
public static int CANCEL = 1;
public static int EXIT = 2;
private JButton cancel;
private JButton next;
private JButton exit;
private EventListenerList listeners;
public NavigationButtons(int type) {
listeners = new EventListenerList();
GridBagLayout layout = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
setLayout(layout);
if ((NEXT_CANCEL == type) || (CANCEL == type)) {
cancel = new JButton("Cancel");
cancel.addActionListener(this);
c.gridwidth = 1;
c.anchor = GridBagConstraints.LINE_START;
c.weightx = 1;
add(cancel, c);
}
if (NEXT_CANCEL == type) {
next = new JButton("Next");
next.addActionListener(this);
c.gridwidth = 1;
c.anchor = GridBagConstraints.LINE_END;
c.weightx = 0;
add(next, c);
}
if (EXIT == type) {
exit = new JButton("Exit");
exit.addActionListener(this);
c.gridwidth = 1;
c.anchor = GridBagConstraints.LINE_END;
c.weightx = 1;
add(exit, c);
}
}
public void setNextEnable(boolean b) {
next.setEnabled(b);
}
#Override
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == next) {
fireActionPerformed(Navigation.NEXT);
}
if (ae.getSource() == cancel) {
fireActionPerformed(Navigation.CANCEL);
}
if (ae.getSource() == exit) {
fireActionPerformed(Navigation.EXIT);
}
}
public void addActionListener(ActionListener listener) {
listeners.add(ActionListener.class, listener);
}
public void removeActionListener(ActionListener listener) {
listeners.remove(ActionListener.class, listener);
}
public void fireActionPerformed(Navigation nav){
ActionListener[] listenerList = (ActionListener[])listeners.getListeners(ActionListener.class);
for(ActionListener listener : listenerList){
listener.actionPerformed(new ActionEvent(this, nav.getId(), null));
}
}
}
What is wrong in my code that make this ugly refresh ? I don't understand.
Maybe I need to implement a kind of listener that repaint my frame each time I scroll ?
The more strange things is, if I replace
add(scrollPane, constraint);
by
add(optionsPane, constraint);
the content get out well (at least in this example).
Thank's you
Julien
The basic problem is, you're using java.awt.TextField which is a heavy weight component inside a lighweight container. This is just asking for issues, they tend not to play well together.
Instead, use a javax.swing.JTextField
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.TextEvent;
import java.awt.event.TextListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.event.EventListenerList;
public class ChangeOptionTF extends JPanel implements ActionListener {
private static final long serialVersionUID = 3355314012553851743L;
private JTextField tf;
private JButton saveBtn;
private EventListenerList listeners;
public ChangeOptionTF(String label) {
listeners = new EventListenerList();
GridBagLayout layout = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
setLayout(layout);
JLabel jLabel = new JLabel(label);
c.fill = GridBagConstraints.BOTH;
c.gridx = 0;
c.gridy = 0;
c.weightx = 1;
add(jLabel, c);
tf = new JTextField();
Related
I am currently trying to implement an action listener to my JCheckBox so that when it is selected, it will open a JFileChooser for the user to pick a file they want the GUI to use. For starters how would I get the console to print out "Box clicked!" when a user checks the box?
It has been a while since I've programmed in Swing so any advice helps!
public class RadioPanel extends JPanel implements ActionListener
{
private static final long serialVersionUID = -1890379016551779953L;
private JCheckBox box;
private JLabel label;
public RadioPanel(String message)
{
this.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.WEST;
c.gridx = 0;
c.gridy = 0;
box = new JCheckBox();
this.add(box,c);
c.gridx = 1;
c.gridy = 0;
label = new JLabel(message);
this.add(label, c);
}
I think it's because the code does not have an event listener.
See my code below.
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
class RadioPanel extends JPanel implements ActionListener {
private static final long serialVersionUID = -1890379016551779953L;
private JCheckBox box;
private JLabel label;
public RadioPanel(String message) {
this.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.WEST;
c.gridx = 0;
c.gridy = 0;
box = new JCheckBox();
// here
box.addActionListener(event -> {
JCheckBox checkBox = (JCheckBox) event.getSource();
if (checkBox.isSelected()) {
System.out.println("Box clicked!");
}
});
this.add(box, c);
c.gridx = 1;
c.gridy = 0;
label = new JLabel(message);
this.add(label, c);
}
#Override
public void actionPerformed(ActionEvent e) {
}
}
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
AbstractButton abstractButton = (AbstractButton) actionEvent.getSource();
boolean selected = abstractButton.getModel().isSelected();
System.out.println("Is selected :" + selected);
}
};
box.addActionListener(actionListener);
This question already has answers here:
How to Remove an icon on a JButton?
(3 answers)
Closed 5 years ago.
I am working on the Tic Tac application all things are set but the only problem is that I am using images on the Button and I want to make a restart button when this restart Button pressed I want that all the images on the Button should be removed. I have also tried to setIcon(null) but when the Restart button press image is removed and one another problem arises is that Button's get disabled and I am not able to play again.
Is there is any other methods available to remove the icon from the Button?
The OP issue is more than setIcon(null), so I am giving this reply,
Try below source code, but there is a good multi pane scenario for you:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
import java.util.ArrayList;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
/*
* Used resources within this class or illustration done within is just for the
* study purpose.
*/
public class ImageExample extends JFrame {
private static final long serialVersionUID = 1L;
/*
* used fixed images resource, you can take all directory resources as per your
* need
*/
private String[] leopard = new String[] { "leopard0", "leopard1", "leopard2", "leopard3" };
private URL url;
private JLabel label1, label2, label3, label4;
private ArrayList<Integer> index = new ArrayList<Integer>();
public ImageExample() {
init();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new ImageExample();
}
});
}
private void init() {
setTitle("Add And Remove Image");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridBagLayout());
setBounds(400, 150, 625, 400);
for (int i = 0; i < leopard.length; i++)
index.add(i);
GridBagConstraints c = new GridBagConstraints();
JPanel panel = new JPanel(); // 1
panel.add(label1 = new JLabel(getIndexIcon(index.get(0))));
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
c.gridheight = 1;
add(panel, c);
panel = new JPanel(); // 2
panel.add(label2 = new JLabel(getIndexIcon(index.get(1))));
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.0;
c.gridx = 1;
c.gridy = 0;
c.gridheight = 1;
add(panel, c);
panel = new JPanel(); // 3
panel.add(label3 = new JLabel(getIndexIcon(index.get(2))));
c.fill = GridBagConstraints.HORIZONTAL;
c.weighty = 0.0;
c.gridx = 0;
c.gridy = 1;
c.gridheight = 1;
add(panel, c);
panel = new JPanel(); // 4
panel.add(label4 = new JLabel(getIndexIcon(index.get(3))));
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.0;
c.weighty = 0.0;
c.gridx = 1;
c.gridy = 1;
c.gridheight = 1;
add(panel, c);
panel = new JPanel(); // contains JButtons
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.0;
c.gridwidth = 2;
c.gridx = 0;
c.gridy = 2;
add(panel, c);
final JButton prev = new JButton("Previous");
final JButton addImage = new JButton("Add Image");
final JButton removeImage = new JButton("Remove Image");
final JButton next = new JButton("Next");
addImage.setEnabled(false);
panel.add(prev);
panel.add(addImage);
panel.add(removeImage);
panel.add(next);
prev.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
revalidateLabel(label1, revalidateIndex(0, index.get(0) - 1));
revalidateLabel(label2, revalidateIndex(1, index.get(1) - 1));
revalidateLabel(label3, revalidateIndex(2, index.get(2) - 1));
revalidateLabel(label4, revalidateIndex(3, index.get(3) - 1));
}
});
addImage.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
revalidateLabel(label1, index.get(0));
revalidateLabel(label2, index.get(1));
revalidateLabel(label3, index.get(2));
revalidateLabel(label4, index.get(3));
addImage.setEnabled(false);
removeImage.setEnabled(true);
prev.setEnabled(true);
next.setEnabled(true);
removeImage.requestFocus();
}
});
removeImage.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
removeLabelImage(label1);
removeLabelImage(label2);
removeLabelImage(label3);
removeLabelImage(label4);
prev.setEnabled(false);
next.setEnabled(false);
removeImage.setEnabled(false);
addImage.setEnabled(true);
addImage.requestFocus();
}
});
next.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
revalidateLabel(label1, revalidateIndex(0, index.get(0) + 1));
revalidateLabel(label2, revalidateIndex(1, index.get(1) + 1));
revalidateLabel(label3, revalidateIndex(2, index.get(2) + 1));
revalidateLabel(label4, revalidateIndex(3, index.get(3) + 1));
}
});
setVisible(true);
}
private ImageIcon getIndexIcon(int indexAt) {
if (indexAt < 0)
indexAt = leopard.length - 1;
if (indexAt > (leopard.length - 1))
indexAt = 0;
url = ImageExample.class.getResource("/resources/leopard" + indexAt + ".jpg");
ImageIcon icon = new ImageIcon(url.getPath());
return icon;
}
private void revalidateLabel(JLabel label, int indexAt) {
label.setIcon(getIndexIcon(indexAt));
label.revalidate();
}
private void removeLabelImage(JLabel label) {
label.setIcon(null);
label.revalidate();
}
private int revalidateIndex(int indexAt, int indx) {
if (indx < 0)
indx = leopard.length - 1;
if (indx > (leopard.length - 1))
indx = 0;
index.set(indexAt, indx);
return indx;
}
}
Problem and Code Summary:This will make sense if you run the code below. I'm using a JScrollPane and its scroll bar is disappearing when it is placed in a JPanel with a BorderLayout (NORTH). When the JPanel has a BorderLayout (CENTER), it works fine (with the scroll bar showing up). If you try to remove many of the components with the remove buttons, it gets annoying because the JScrollPane (with all of its components) clumps up in the middle of the JPanel it's in, when you want it to stay at the top. I tried to prevent this by obviously changing the BorderLayout of the JPanel from CENTER TO NORTH, but that just takes out the scroll bar completely. In the following code, the Main.placement (line 28) (change it to CENTER/NORTH to mess with it) controls the type of layout being used and line 171 shows how it is implemented. I just want to align the JSCrollPane at the top with the scroll bar showing up when it is neccessary.
Code Summary:
package main;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.util.ArrayList;
import javax.swing.BorderFactory;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
public class Main{
public static final String placement = BorderLayout.CENTER;
public static void main(String[] args){
new TimeChart(true);
}
}
#SuppressWarnings("serial")
class TimeChart extends JFrame {
private boolean admin;
private TimeTable timeTable;
private static final JLabel title;
private final JLabel volLabel;
static {
title = new JLabel("Time Chart ");
}
private class TimeTable extends JPanel {
private JScrollPane scrollPane;
private JPanel table;
public final ArrayList<SessionRow> sessionRows;
private final JButton addButton;
private final JButton applyButton;
private static final double weight_sessnum = 0.2;
private static final double weight_signinout = 1.0;
private static final double weight_time = 0.3;
private static final double weight_delete = 0.0;
public class SessionRow {
private final SessionRow thisSessionRow; // for inner classes
private JTextField sessionnum, signinField, signoutField, total;
private JButton removeButton;
private SessionRow(int y) {
thisSessionRow = this;
String signinstring = "*signin time*";
String signoutstring = "*signout time*";
sessionnum = new JTextField("Session " + y + ": ");
sessionnum.setEditable(false);
signinField = new JTextField(signinstring);
signinField.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e) {
signinField.selectAll();
}
#Override
public void focusLost(FocusEvent e) {
}
});
signinField.setEditable(admin);
signoutField = new JTextField(signoutstring);
signoutField.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e) {
signoutField.selectAll();
}
#Override
public void focusLost(FocusEvent e) {
}
});
signoutField.setEditable(admin);
String totalstring = null;
try {
totalstring = "*session total*";
} catch (Exception e) {
totalstring = " -- ";
}
total = new JTextField(totalstring);
total.setEditable(false);
removeButton = new JButton("Remove");
removeButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
thisSessionRow.remove();
sessionRows.remove(thisSessionRow);
revalidate();
repaint();
}
});
}
public void remove() {
table.remove(this.sessionnum);
table.remove(this.signinField);
table.remove(this.signoutField);
table.remove(this.total);
table.remove(this.removeButton);
}
}
public TimeTable() {
super();
table = new JPanel();
scrollPane = new JScrollPane(table);
applyButton = new JButton("<html><div style=\"text-align: center;\">Apply<br>Changes</html>");
applyButton.setMargin(new Insets(5, 5, 5, 5));
applyButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
applyAllChanges();
}
});
applyButton.setEnabled(false);
addButton = new JButton("Add");
addButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
sessionRows.add(new SessionRow(sessionRows.size() + 1));
setupAll();
revalidate();
repaint();
if (!applyButton.isEnabled())
applyButton.setEnabled(true);
}
});
sessionRows = new ArrayList<SessionRow>();
setupSessionRows();
setupAll();
this.setLayout(new BorderLayout());
this.add(scrollPane, Main.placement); //PAY ATTENTION HERE
JScrollBar bar = scrollPane.getVerticalScrollBar();
bar.setPreferredSize(new Dimension(30, 0));
bar.setUnitIncrement(10);
InputMap im = bar.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
im.put(KeyStroke.getKeyStroke("down"), "positiveUnitIncrement");
im.put(KeyStroke.getKeyStroke("up"), "negativeUnitIncrement");
scrollPane.setBorder(BorderFactory.createLineBorder(Color.red));
this.setBorder(BorderFactory.createLineBorder(Color.green));
}
public void setupSessionRows() {
sessionRows.clear();
for (int i = 0; i < 30; i++) {
sessionRows.add(new SessionRow(i + 1));
}
System.gc();
}
public void setupAll() {
table.removeAll();
table.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(0, 0, 5, 2);
c.gridx = 0;
c.gridy = 0;
initColumnHeader(c);
for (int y = 0; y < sessionRows.size(); y++) {
c.gridy++;
initSessRow(sessionRows.get(y), c);
}
c.gridy++;
if (admin) {
initNewButtonRow(c);
c.gridy++;
}
initTotalHeader(c);
}
public void initSessRow(SessionRow row, GridBagConstraints c) {
c.weightx = weight_sessnum;
c.gridx = 0;
table.add(row.sessionnum, c);
c.weightx = weight_signinout;
c.gridx = 1;
table.add(row.signinField, c);
c.weightx = weight_signinout;
c.gridx = 2;
table.add(row.signoutField, c);
c.weightx = weight_time;
c.gridx = 3;
table.add(row.total, c);
if (admin) {
c.weightx = weight_delete;
c.gridx = 4;
table.add(row.removeButton, c);
}
}
public void initTotalHeader(GridBagConstraints c) {
c.weightx = weight_sessnum;
c.gridx = 0;
JTextField totalLabel = new JTextField("Total: ");
totalLabel.setEditable(false);
table.add(totalLabel, c);
c.weightx = weight_signinout;
c.gridx = 1;
JTextField blank1 = new JTextField();
blank1.setEditable(false);
table.add(blank1, c);
c.weightx = weight_signinout;
c.gridx = 2;
JTextField blank2 = new JTextField();
blank2.setEditable(false);
table.add(blank2, c);
c.weightx = weight_time;
c.gridx = 3;
JTextField totaltime = new JTextField("*TOTAL*");
totaltime.setEditable(false);
table.add(totaltime, c);
if (admin) {
c.weightx = weight_delete;
c.gridx = 4;
table.add(applyButton, c);
}
}
public void initNewButtonRow(GridBagConstraints c) {
c.weightx = weight_sessnum;
c.gridx = 0;
table.add(addButton, c);
c.weightx = weight_signinout;
c.gridx = 1;
JTextField blank1 = new JTextField();
blank1.setEditable(false);
table.add(blank1, c);
c.weightx = weight_signinout;
c.gridx = 2;
JTextField blank2 = new JTextField();
blank2.setEditable(false);
table.add(blank2, c);
c.weightx = weight_time;
c.gridx = 3;
JTextField blank3 = new JTextField();
blank3.setEditable(false);
table.add(blank3, c);
if (admin) {
c.weightx = weight_delete;
c.gridx = 4;
JTextField blank4 = new JTextField();
blank4.setEditable(false);
table.add(blank4, c);
}
}
public void initColumnHeader(GridBagConstraints c) {
c.weightx = weight_sessnum;
c.gridx = 0;
JTextField sessnum = new JTextField("Session #");
sessnum.setEditable(false);
table.add(sessnum, c);
c.weightx = weight_signinout;
c.gridx = 1;
JTextField signintime = new JTextField("Sign in Time");
signintime.setEditable(false);
table.add(signintime, c);
c.weightx = weight_signinout;
c.gridx = 2;
JTextField signouttime = new JTextField("Sign out Time");
signouttime.setEditable(false);
table.add(signouttime, c);
c.weightx = weight_time;
c.gridx = 3;
JTextField time = new JTextField("Time");
time.setEditable(false);
table.add(time, c);
if (admin) {
c.weightx = weight_delete;
c.gridx = 4;
JTextField delete = new JTextField("Delete");
delete.setEditable(false);
table.add(delete, c);
}
}
#Override
public void revalidate() {
if (sessionRows != null) {
int i = 1;
for (SessionRow sr : sessionRows) {
sr.sessionnum.setText("Session " + i);
i++;
}
}
super.revalidate();
}
}
public TimeChart(boolean admin) {
super();
this.admin = admin;
volLabel = new JLabel("Billy");
timeTable = new TimeTable();
this.setSize(900, 900);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initFrame();
this.setVisible(true);
scrollDown();
}
public void initFrame() {
this.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.BOTH;
c.weightx = 1.0;
c.weighty = 0.0;
c.gridx = 0;
c.gridy = 0;
this.add(title, c);
c.weightx = 1.0;
c.weighty = 0.0;
c.gridx = 0;
c.gridy = 1;
this.add(volLabel, c);
c.weightx = 1.0;
c.weighty = 1.0;
c.gridx = 0;
c.gridy = 2;
this.add(timeTable, c);
}
public void scrollDown() {
JScrollBar bar = timeTable.scrollPane.getVerticalScrollBar();
bar.setValue(bar.getMaximum());
}
public void applyAllChanges() {
}
}
Thanks in advance, I really appreciate it.
I'm new to Java Swing and was trying to make a simple layout (I thought), but I have a lot of problems reaching the behavior I want. Here's my code :
setSize(800, 600);
setLocationRelativeTo(null);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
equipementPanel.setPreferredSize(new Dimension(275, 300));
grillePanel.setPreferredSize(new Dimension(300, 600));
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0; c.gridy = 0;
c.anchor = GridBagConstraints.NORTHWEST;
c.gridwidth = 1; c.gridheight = 1;
c.weightx = 0.0; c.weighty = 0.0;
this.add(equipementPanel, c);
c.fill = GridBagConstraints.BOTH;
c.gridx = 0; c.gridy = 1;
c.anchor = GridBagConstraints.SOUTHWEST;
c.gridwidth = 1; c.gridheight = 2;
c.weightx = 0.0; c.weighty = 0.0;
this.add(informationPanel, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1; c.gridy = 0;
c.anchor = GridBagConstraints.NORTHEAST;
c.weightx = 1.0; c.weighty = 1.0;
this.add(grillePanel, c);
c.fill = GridBagConstraints.BOTH;
c.gridx = 1; c.gridy = 1;
c.anchor = GridBagConstraints.SOUTHEAST;
c.weightx = 1.0; c.weighty = 0.0;
this.add(commandePanel, c);
this.validate();
Screen of my laptop is a good result of what I want.
equipementPanel = green
grillePanel = gray
But on my bigger screen...it is the gray one that should stretch. Red it's okay.
And a total disaster when I size it down .
What I want it to do is
The Gray should not have fixed height and width.
The Yellow should always have the fixed height but not width.
The Red should always have fixed width but not height.
The Green should always have both fixed.
The smallest the window could become would be set to the height of the Green + Yellow one. and width of Green + whatever nice to display.
I know that the weird behavior with the small window is because I go under 300 + 600 of my preferred size...but I need to fix some size somewhere!?!?
If I can reach the same behavior with another layout, I'd be glad to try it. If I change and use some ScrollPanel, does that change anything?
I added a mcve :
MCVE.JAVA
package mcve;
import java.awt.EventQueue;
public class MCVE {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
mcve.gui.MainWindow mainWindow = new mcve.gui.MainWindow();
mainWindow.setVisible(true);
});
}
}
MainWindow.Java
package mcve.gui;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
public class MainWindow extends JFrame
{
public MainWindow()
{
this.setExtendedState(JFrame.MAXIMIZED_BOTH);
this.setLayout(new GridBagLayout());
initComponents();
}
private void initComponents()
{
setSize(800, 600);
setLocationRelativeTo(null);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
GrillePanel grillePanel = new GrillePanel();
CommandePanel commandePanel = new CommandePanel();
InformationPanel informationPanel = new InformationPanel();
EquipementPanel equipementPanel = new EquipementPanel();
equipementPanel.setPreferredSize(new Dimension(275, 300));
grillePanel.setPreferredSize(new Dimension(300, 600));
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0; c.gridy = 0;
c.anchor = GridBagConstraints.NORTHWEST;
c.gridwidth = 1; c.gridheight = 1;
c.weightx = 0.0; c.weighty = 0.0;
this.add(equipementPanel, c);
c.fill = GridBagConstraints.BOTH;
c.gridx = 0; c.gridy = 1;
c.anchor = GridBagConstraints.SOUTHWEST;
c.gridwidth = 1; c.gridheight = 2;
c.weightx = 0.0; c.weighty = 0.0;
this.add(informationPanel, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1; c.gridy = 0;
c.anchor = GridBagConstraints.NORTHEAST;
c.weightx = 1.0; c.weighty = 1.0;
this.add(grillePanel, c);
c.fill = GridBagConstraints.BOTH;
c.gridx = 1; c.gridy = 1;
c.anchor = GridBagConstraints.SOUTHEAST;
c.weightx = 1.0; c.weighty = 0.0;
this.add(commandePanel, c);
this.validate();
}
}
the 4 panel
package mcve.gui;
import java.awt.Color;
import javax.swing.BorderFactory;
import javax.swing.JPanel;
public class InformationPanel extends JPanel
{
public InformationPanel()
{
setBackground(Color.red);
setBorder(BorderFactory.createLineBorder(Color.black));
setVisible(true);
}
}
package mcve.gui;
import java.awt.Color;
import javax.swing.BorderFactory;
import javax.swing.JPanel;
public class GrillePanel extends JPanel
{
public GrillePanel()
{
setBackground(Color.lightGray);
setBorder(BorderFactory.createLineBorder(Color.black));
setVisible(true);
}
}
package mcve.gui;
import java.awt.Color;
import javax.swing.BorderFactory;
import javax.swing.JPanel;
public class EquipementPanel extends JPanel
{
public EquipementPanel()
{
setBackground(Color.green);
setBorder(BorderFactory.createLineBorder(Color.black));
setVisible(true);
}
}
package mcve.gui;
import java.awt.Color;
import javax.swing.BorderFactory;
import javax.swing.JPanel;
public class CommandePanel extends JPanel
{
public CommandePanel()
{
setBackground(Color.yellow);
setBorder(BorderFactory.createLineBorder(Color.black));
setVisible(true);
}
}
There are two basic issues (as I see it)...
One, you are trying to manage a complex layout within a single layout manager, which is pretty hard at the best of times.
Two, you don't seem to understand what the layout manager will do when the available size of the component drops below it's preferred size, which is, in the case of GridBagLayout, revert to it's minimum size...
You can overcome some of this through the use of weights (weightx/weighty), but sometimes, you just need to provide a hard value for the minimum size as well...
Without knowing your exact needs (and you're going to need to make decisions about which components are more important), this is a rough example...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class LayoutTest {
public static void main(String[] args) {
new LayoutTest();
}
public LayoutTest() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JPanel greenPane = new JPanel() {
#Override
public Dimension getPreferredSize() {
return new Dimension(275, 300);
}
#Override
public Dimension getMinimumSize() {
return getPreferredSize();
}
#Override
public Color getBackground() {
return Color.GREEN;
}
};
JPanel redPane = new JPanel() {
#Override
public Dimension getPreferredSize() {
return new Dimension(300, 600);
}
#Override
public Dimension getMinimumSize() {
return getPreferredSize();
}
#Override
public Color getBackground() {
return Color.RED;
}
};
JPanel left = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1;
gbc.weighty = 0.25;
gbc.fill = GridBagConstraints.BOTH;
left.add(greenPane, gbc);
gbc.gridy++;
gbc.weighty = 0.75;
left.add(redPane, gbc);
JPanel yellowPane = new JPanel() {
#Override
public Dimension getPreferredSize() {
return new Dimension(600, 50);
}
#Override
public Dimension getMinimumSize() {
return getPreferredSize();
}
#Override
public Color getBackground() {
return Color.YELLOW;
}
};
JPanel grayPane = new JPanel() {
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 600);
}
#Override
public Dimension getMinimumSize() {
return getPreferredSize();
}
#Override
public Color getBackground() {
return Color.GRAY;
}
};
JPanel center = new JPanel(new GridBagLayout());
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 1;
gbc.weighty = 1;
center.add(grayPane, gbc);
gbc.gridy++;
gbc.weighty = 0;
center.add(yellowPane, gbc);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(left, BorderLayout.WEST);
frame.add(center);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
Swing layout managers are quite decent, but unfortunetly they can make a lot of troubles. I think that the only layout managers that are actually usable are BorderLayout, GroupLayout and only in some cases GridBayLayout. In most cases I have found they are useless.
Why dont you try to use 3rd party layout managers? From my experience I can tell thal MigLayout is more than great. It is very flexible and have decent API. You will get desired layout composition in no time. I am using it in all desktop projects.
I have a problem with my login screen. Somehow it is not being correctly.
All the objects (JLabel,JButton,JTextfield etc.) is not being displayed correctly. This is how it should look:
It only appears once I resize the screen size by pulling at the window border.
The JFrame contains 2 JPanels as tabs. This is the code:
Login.java
package de.immozukunft.windows;
import javax.swing.*;
import de.immozukunft.tabs.LoginTab;
import de.immozukunft.tabs.MySQLConnectionTab;
import java.awt.BorderLayout;
import java.util.Locale;
import java.util.ResourceBundle;
public class Login {
/**The Login class implements the LoginTab and the MySQLConnectionTab
* to verify the user access*/
//String management
static Locale locale = new Locale("de");
static ResourceBundle r = ResourceBundle.getBundle("Strings", locale);
JFrame window = new JFrame();
//Constructor
public Login() {
window.setTitle(r.getString("userlogin"));
frame();
}
//Frame method
private void frame() {
window.setSize(400,250);
window.setLocationRelativeTo(null);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
//Tab-panel
JTabbedPane tabbedPane = new JTabbedPane();
//Tabs
tabbedPane.addTab("Login", new LoginTab(window));
tabbedPane.addTab("MySQL Verbindung", new MySQLConnectionTab()); //TODO Strings einfügen
//Add tab-panel to frame
window.add(tabbedPane, BorderLayout.CENTER);
}
}
LoginTab.java
package de.immozukunft.tabs;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Locale;
import java.util.ResourceBundle;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import de.immozukunft.overwrittenClasses.JTextFieldImmo;
import de.immozukunft.persons.UserDetails;
import de.immozukunft.programs.MySQL;
import de.immozukunft.windows.ButtonPanel;
public class LoginTab extends JPanel {
/** LoginTab does the userverfication by
* comparing the entered data with the MySQL-database
* There is no encryption implemented*/
private static final long serialVersionUID = 1L;
//Multilingual String-Management
static Locale locale = new Locale("de");
static ResourceBundle r = ResourceBundle.getBundle("Strings", locale);
// static Connection con = null;
static Statement stnt = null;
static ResultSet rs = null;
//Constructor
public LoginTab(final JFrame window) {
panelMethod(window);
}
// LOGIN ITEMS
JLabel usernameLbl = new JLabel(r.getString("username"));
JLabel passwordLbl = new JLabel(r.getString("password"));
JTextFieldImmo usernameFld = new JTextFieldImmo(15);
JPasswordField passwordFld = new JPasswordField(15);
JButton loginBtn = new JButton(r.getString("login"));
JButton registerUserBtn = new JButton(r.getString("newUser"));
public void panelMethod(final JFrame window) {
this.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
// Insets
c.insets = new Insets(4, 5, 0, 0);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
this.add(usernameLbl, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
c.gridy = 0;
this.add(usernameFld, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 1;
this.add(passwordLbl, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
c.gridy = 1;
this.add(passwordFld, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
c.gridy = 2;
this.add(loginBtn, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 2;
this.add(registerUserBtn, c);
// Actions Listener
loginBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
MySQL.connect();
String username = usernameFld.getText().trim();
String password = String.valueOf(passwordFld.getPassword()).trim();
String sql = "SELECT username,password from per_user where username = '"
+ username + "'and password = '" + password + "'";
stnt = MySQL.getCon().createStatement();
rs = stnt.executeQuery(sql);
int count = 0;
while (rs.next()) {
count = count + 1;
}
if (count == 1) {
//JOptionPane.showMessageDialog(null, "User Found, Access Granded!"); //TODO String
window.setVisible(false);
window.dispose();
new ButtonPanel();
} else if (count > 1) {
JOptionPane.showMessageDialog(null,
"Duplicate User, Access Denied!"); // TODO String einfügen
} else {
JOptionPane.showMessageDialog(null, r.getString("userNotFound"));
}
} catch (Exception e1) {
JOptionPane.showMessageDialog(null, r.getString("unableToConnectMySQL"));
e1.printStackTrace();
}
}
});
registerUserBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
new UserDetails();
}
});
passwordFld.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
loginBtn.doClick();
}
});
}
}
MySQLConnectionTab.java
package de.immozukunft.tabs;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Locale;
import java.util.ResourceBundle;
import javax.swing.*;
import de.immozukunft.overwrittenClasses.JTextFieldImmo;
import de.immozukunft.programs.MySQL;
public class MySQLConnectionTab extends JPanel { //Subclass of Jframe, with ActionListener as interface
/** MySQLConnectionTab is a JPanel which can be implemented
* in other JTabbedPanes in order to change the MySQL connection settings
*/
private static final long serialVersionUID = 1L;
private JButton connectBtn = new JButton(r.getString("connect")); //Connect-Button
private JButton cancelBtn = new JButton(r.getString("cancel")); //Cancel-Button
private JTextFieldImmo hostFld = new JTextFieldImmo(MySQL.getHost(), 20); // Host text field
private JTextFieldImmo usernameFld = new JTextFieldImmo(MySQL.getUsername(), 20); // Username text field
private JTextFieldImmo databaseFld = new JTextFieldImmo(MySQL.getDatabase(), 20); // Database text field
private JTextFieldImmo portFld = new JTextFieldImmo(String.valueOf(MySQL.getPort()), 20); // Port text field
private JPasswordField passwordFld = new JPasswordField(MySQL.getPassword(), 20); // Password text field
private JLabel hostLbl = new JLabel(r.getString("host")); // Host text label
private JLabel usernameLbl = new JLabel(r.getString("username")); // Username text label
private JLabel databaseLbl = new JLabel(r.getString("database")); // Database text label
private JLabel portLbl = new JLabel(r.getString("port")); // Port text label
private JLabel passwordLbl = new JLabel(r.getString("password")); // Password text label
static Locale locale = new Locale("de");
static ResourceBundle r = ResourceBundle.getBundle("Strings", locale);
//Constructor
public MySQLConnectionTab() {
panelMethod();
}
public void panelMethod(){
//Create GridBagConstraints
GridBagConstraints c2 = new GridBagConstraints();
//SetLayout to GridBagLayout
this.setLayout(new GridBagLayout());
//Insets
c2.insets = new Insets(4, 5, 0, 0);
c2.fill = GridBagConstraints.HORIZONTAL;
c2.gridx = 0;
c2.gridy = 0;
this.add(hostLbl, c2);
c2.fill = GridBagConstraints.HORIZONTAL;
c2.gridx = 1;
c2.gridy = 0;
this.add(hostFld, c2);
c2.fill = GridBagConstraints.HORIZONTAL;
c2.gridx = 0;
c2.gridy = 1;
this.add(usernameLbl, c2);
c2.fill = GridBagConstraints.HORIZONTAL;
c2.gridx = 1;
c2.gridy = 1;
this.add(usernameFld, c2);
c2.fill = GridBagConstraints.HORIZONTAL;
c2.gridx = 0;
c2.gridy = 2;
this.add(databaseLbl, c2);
c2.fill = GridBagConstraints.HORIZONTAL;
c2.gridx = 1;
c2.gridy = 2;
this.add(databaseFld, c2);
c2.fill = GridBagConstraints.HORIZONTAL;
c2.gridx = 0;
c2.gridy = 3;
this.add(portLbl, c2);
c2.fill = GridBagConstraints.HORIZONTAL;
c2.gridx = 1;
c2.gridy = 3;
this.add(portFld, c2);
c2.fill = GridBagConstraints.HORIZONTAL;
c2.gridx = 0;
c2.gridy = 4;
this.add(passwordLbl, c2);
c2.fill = GridBagConstraints.HORIZONTAL;
c2.gridx = 1;
c2.gridy = 4;
this.add(passwordFld, c2);
c2.fill = GridBagConstraints.HORIZONTAL;
c2.gridx = 1;
c2.gridy = 5;
this.add(connectBtn, c2);
c2.fill = GridBagConstraints.HORIZONTAL;
c2.gridx = 0;
c2.gridy = 5;
this.add(cancelBtn, c2);
connectBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
//All the field data is being set for the MySQL-connection
MySQL.setHost(hostFld.getText());
MySQL.setUsername(usernameFld.getText());
MySQL.setDatabase(databaseFld.getText());
MySQL.setPort(Integer.parseInt(portFld.getText()));
MySQL.setPassword(String.valueOf(passwordFld.getPassword()));
JOptionPane.showMessageDialog(null, String.format("%s", MySQL.getStatus()));
}
}); // Add ActionListener for connect Button
cancelBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
hostFld.setText(MySQL.getHost());
usernameFld.setText(MySQL.getUsername());
databaseFld.setText(MySQL.getDatabase());
portFld.setText(String.valueOf(MySQL.getPort()));
passwordFld.setText(MySQL.getPassword());
}
}); // Add ActionListener for cancel Button
}
}
I am still a beginner.
It's because you are calling setVisible before you add components. Call setVisible after you add components on your JFrame.
Basically:
//Frame method
private void frame() {
//Tab-panel
JTabbedPane tabbedPane = new JTabbedPane();
//Tabs
tabbedPane.addTab("Login", new LoginTab(window));
tabbedPane.addTab("MySQL Verbindung", new MySQLConnectionTab()); //TODO Strings einfügen
//Add tab-panel to frame
window.add(tabbedPane, BorderLayout.CENTER);
//window.setSize(400,250);
window.pack();
window.setLocationRelativeTo(null);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
}
Also, call pack instead of setSize. Size of your JFrame will be based on preferred sizes of components within of JFrame and gaps between those components.