Update frame or revalidate/repaint panel - java

How to update a Java frame with changed content?
I want to update a frame or just the panel with updated content. What do I use for this
Here is where I want to revalidate the frame or repaint mainpanel or whatever will work
I have tried a number of things, but none of them have worked.
public void actionPerformed(ActionEvent e) {
//System.out.println(e.getActionCommand());
if (e.getActionCommand().equals("advance")) {
multi--;
// Revalidate update repaint here <<<<<<<<<<<<<<<<<<<
}
else if (e.getActionCommand().equals("reverse")) {
multi++;
// Revalidate update repaint here <<<<<<<<<<<<<<<<<<<
}
else {
openURL(e.getActionCommand());
}
}
Here is the whole java file
/*
*
*
*/
package build;
import java.lang.reflect.Method;
import javax.swing.JOptionPane;
import java.util.Arrays;
import java.util.*;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.AbstractButton;
import javax.swing.JScrollPane;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.ImageIcon;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
/*
* ButtonDemo.java requires the following files:
* images/right.gif
* images/middle.gif
* images/left.gif
*/
public class StockTable extends JPanel
implements ActionListener {
static int multi = 1;
int roll = 0;
static TextVars textvars = new TextVars();
static final String[] browsers = { "firefox", "opera", "konqueror", "epiphany",
"seamonkey", "galeon", "kazehakase", "mozilla", "netscape" };
JFrame frame;
JPanel mainpanel, panel1, panel2, panel3, panel4, panel2left, panel2center, panel2right;
JButton stknames_btn[] = new JButton[textvars.getNumberOfStocks()];
JLabel label[] = new JLabel[textvars.getNumberOfStocks()];
JLabel headlabel, dayspan, namelabel;
JRadioButton radioButton;
JButton button;
JScrollPane scrollpane;
int wid = 825;
public JPanel createContentPane() {
mainpanel = new JPanel();
mainpanel.setPreferredSize(new Dimension(wid, 800));
mainpanel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
panel1 = new JPanel();
panel1.setPreferredSize(new Dimension(wid, 25));
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(0,0,0,0);
mainpanel.add(panel1, c);
// Panel 2------------
panel2 = new JPanel();
panel2.setPreferredSize(new Dimension(wid, 51));
c.gridx = 0;
c.gridy = 1;
c.insets = new Insets(0,0,0,0);
mainpanel.add(panel2, c);
panel2left = new JPanel();
panel2left.setPreferredSize(new Dimension(270, 51));
c.gridx = 0;
c.gridy = 1;
c.insets = new Insets(0,0,0,0);
panel2.add(panel2left, c);
panel2center = new JPanel();
panel2center.setPreferredSize(new Dimension(258, 51));
c.gridx = 1;
c.gridy = 1;
c.insets = new Insets(0,0,0,0);
panel2.add(panel2center, c);
panel2right = new JPanel();
panel2right.setPreferredSize(new Dimension(270, 51));
c.gridx = 2;
c.gridy = 1;
c.insets = new Insets(0,0,0,0);
panel2.add(panel2right, c);
// ------------------
panel3 = new JPanel();
panel3.setLayout(new GridBagLayout());
scrollpane = new JScrollPane(panel3);
scrollpane.setPreferredSize(new Dimension(wid, 675));
c.gridx = 0;
c.gridy = 2;
c.insets = new Insets(0,0,0,0);
mainpanel.add(scrollpane, c);
ImageIcon leftButtonIcon = createImageIcon("images/right.gif");
//b1 = new JButton("Disable middle button", leftButtonIcon);
//b1.setVerticalTextPosition(AbstractButton.CENTER);
//b1.setHorizontalTextPosition(AbstractButton.LEADING); //aka LEFT, for left-to-right locales
//b1.setMnemonic(KeyEvent.VK_D);
//b1.setActionCommand("disable");
//Listen for actions on buttons 1
//b1.addActionListener(this);
//b1.setToolTipText("Click this button to disable the middle button.");
//Add Components to this container, using the default FlowLayout.
//add(b1);
headlabel = new JLabel("hellorow1");
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(0, 0, 0, 0);
panel1.add(headlabel, c);
radioButton = new JRadioButton("Percentage");
c.gridx = 2;
c.gridy = 0;
c.insets = new Insets(0, 0, 0, 0);
panel1.add(radioButton, c);
radioButton = new JRadioButton("Days Range");
c.gridx = 3;
c.gridy = 0;
c.insets = new Insets(0, 0, 0, 0);
panel1.add(radioButton, c);
radioButton = new JRadioButton("Open / Close");
c.gridx = 4;
c.gridy = 0;
c.insets = new Insets(0, 0, 0,0 );
panel1.add(radioButton, c);
button = new JButton("<<");
button.setPreferredSize(new Dimension(50, 50));
button.setActionCommand("reverse");
button.addActionListener(this);
c.gridx = 0;
c.gridy = 1;
c.insets = new Insets(0, 0, 0, 0);
panel2left.add(button, c);
dayspan = new JLabel("hellorow2");
dayspan.setHorizontalAlignment(JLabel.CENTER);
dayspan.setVerticalAlignment(JLabel.CENTER);
dayspan.setPreferredSize(new Dimension(270, 50));
c.gridx = 1;
c.gridy = 1;
c.insets = new Insets(0, 0, 0, 0);
panel2center.add(dayspan, c);
button = new JButton(">>");
button.setPreferredSize(new Dimension(50, 50));
button.setActionCommand("advance");
button.addActionListener(this);
if (multi == 0) {
button.setEnabled(false);
}
else {
button.setEnabled(true);
}
c.gridx = 2;
c.gridy = 1;
c.insets = new Insets(0, 0, 0, 0);
panel2right.add(button, c);
int availSpace_int = textvars.getStocks().size()-textvars.getNumberOfStocks()*7;
ArrayList<String[]> stocknames = textvars.getStockNames();
ArrayList<String[]> stocks = textvars.getStocks();
for (int column = 0; column < 8; column++) {
for (int row = 0; row < textvars.getNumberOfStocks(); row++) {
if (column==0) {
if (row==0) {
namelabel = new JLabel(stocknames.get(0)[0]);
namelabel.setVerticalAlignment(JLabel.CENTER);
namelabel.setHorizontalAlignment(JLabel.CENTER);
namelabel.setPreferredSize(new Dimension(100, 25));
c.gridx = column;
c.gridy = row;
c.insets = new Insets(0, 0, 0, 0);
panel3.add(namelabel, c);
}
else {
stknames_btn[row] = new JButton(stocknames.get(row)[0], leftButtonIcon);
stknames_btn[row].setVerticalTextPosition(AbstractButton.CENTER);
stknames_btn[row].setActionCommand(stocknames.get(row)[1]);
stknames_btn[row].addActionListener(this);
stknames_btn[row].setToolTipText("go to Google Finance "+stocknames.get(row)[0]);
stknames_btn[row].setPreferredSize(new Dimension(100, 25));
c.gridx = column;
c.gridy = row;
c.insets = new Insets(0, 0, 0, 0);
//scrollpane.add(stknames[row], c);
panel3.add(stknames_btn[row], c);
}
}
else {
label[row]= new JLabel(textvars.getStocks().get(columnMulti(multi))[1]);
label[row].setBorder(BorderFactory.createLineBorder(Color.black));
label[row].setVerticalAlignment(JLabel.CENTER);
label[row].setHorizontalAlignment(JLabel.CENTER);
label[row].setPreferredSize(new Dimension(100, 25));
c.gridx = column;
c.gridy = row;
c.insets = new Insets(0,0,0,0);
panel3.add(label[row], c);
}
}
}
return mainpanel;
}
public void actionPerformed(ActionEvent e) {
//System.out.println(e.getActionCommand());
if (e.getActionCommand().equals("advance")) {
multi--;
}
else if (e.getActionCommand().equals("reverse")) {
multi++;
}
else {
openURL(e.getActionCommand());
}
}
/** Returns an ImageIcon, or null if the path was invalid. */
protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = StockTable.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
public static void openURL(String url) {
String osName = System.getProperty("os.name");
try {
if (osName.startsWith("Mac OS")) {
Class<?> fileMgr = Class.forName("com.apple.eio.FileManager");
Method openURL = fileMgr.getDeclaredMethod("openURL",
new Class[] {String.class});
openURL.invoke(null, new Object[] {url});
}
else if (osName.startsWith("Windows")) {
Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);
}
else { //assume Unix or Linux
boolean found = false;
for (String browser : browsers)
if (!found) {
found = Runtime.getRuntime().exec(
new String[] {"which", browser}).waitFor() == 0;
if (found)
Runtime.getRuntime().exec(new String[] {browser, url});
}
if (!found)
throw new Exception(Arrays.toString(browsers));
}
}
catch (Exception e) {
JOptionPane.showMessageDialog(null,
"Error attempting to launch web browser\n" + e.toString());
}
}
int reit = 0;
int start = textvars.getStocks().size()-((textvars.getNumberOfStocks()*5)*7)-1;
public int columnMulti(int multi) {
reit++;
start++;
if (reit == textvars.getNumberOfStocks()) {
reit = 0;
start=start+64;
}
//start = start - (multi*(textvars.getNumberOfStocks()));
return start;
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("Stock Table");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
StockTable newContentPane = new StockTable();
//newContentPane.setOpaque(true); //content panes must be opaque
//frame.setContentPane(newContentPane);
frame.setContentPane(newContentPane.createContentPane());
frame.setSize(800, 800);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}

The moment you find yourself wanting to "re-create" a UI based on a small change, should raise alarm bells. There are situations when this is going to be a good idea, but in most cases, it's a sign of a bad design.
Let's start with...
frame.setContentPane(newContentPane.createContentPane());
This is a bad idea. You create a JPanel just to create another JPanel. All of sudden, you've not lost context to the UI.
Instead of the createContentPane, simple construct you UI from the constructor of the StockTable pane and add that to the frame...More like...
frame.setContentPane(newContentPane);
Get rid of mainPanel and use the StockTable panel directly.
I can't run your code, but it looks speciously like your trying to "emulate" a table layout. Instead, simplify your life and learn to use JTable. Updating the table more be significantly easier (not to mention look nicer) if you do...

My suggestion is if you want to update a swing component always use the Event Dispatcher Thread.
I think this may helps you
public void actionPerformed(ActionEvent e) {
//System.out.println(e.getActionCommand());
if (e.getActionCommand().equals("advance")) {
multi--;
Runnable edt = new Runnable() {
public void run() {
/*Update your components here*/
}
};
SwingUtilities.invokeLater(edt);
}
else if (e.getActionCommand().equals("reverse")) {
multi++;
Runnable edt= new Runnable() {
public void run() {
/*Update your components here*/
}
};
SwingUtilities.invokeLater(edt);
}
else {
openURL(e.getActionCommand());
}
}
}

Related

Remove Image from the JButton [duplicate]

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

Java Scrolling Bar disappears when using BorderLayout NORTH

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.

How do I make a JFrame transparent / Opaque without having to setUndecorated(true)

Is there a way that I can set the JFrame to be transparent while still leaving the Buttons / text unaffected?
If not, how can I make the JFrame transparent without using .setUndecorated(true)?
This is a totally different question, but how would I go about adding a gradient as the background color instead of having it be set to one solid color?
Click here to see what the JFrame looks like when the program runs!
class PlayAgain extends JPanel
{
private JFrame nextFrame;
public PlayAgain()
{
nextFrame = new JFrame("Tic-Tac-Toe");
nextFrame.setSize(250,125);
nextFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridBagLayout());
nextFrame.add(panel);
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(10,10,10,10);
class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
nextFrame.dispose();
frame.dispose();
XorOFrameGRID obj = new XorOFrameGRID();
}
}
class ClickNo implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
frame.dispose();
nextFrame.dispose();
}
}
//CREATING BUTTONS & LABELS
JLabel WLT;
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 3;
JLabel title = new JLabel("Would you like to play again?");
if (isWin() == 1)
{
WLT = new JLabel("YOU WON!");
panel.add(WLT,c);
}
else if (isWin() == 2)
{
WLT = new JLabel("YOU LOST!");
panel.add(WLT,c);
}
else if (isWin() == 3)
{
WLT = new JLabel("YOU TIED!");
panel.add(WLT,c);
}
JLabel or = new JLabel("or");
JButton yes = new JButton("Yes");
ActionListener listener1 = new ButtonListener();
yes.addActionListener(listener1);
JButton no = new JButton("No");
ActionListener listener2 = new ClickNo();
no.addActionListener(listener2);
c.gridwidth = 0;
//1ST COLUMN
c.anchor = GridBagConstraints.LINE_END;
c.weighty = 10;
c.gridx = 0;
c.gridy = 2;
panel.add(no,c);
//2ND COLUMN
//adds "or"
c.anchor = GridBagConstraints.CENTER;
c.gridx = 1;
c.gridy = 2;
panel.add(or,c);
//adds title
c.weighty = 0;
c.gridwidth = 3;
c.gridx = 0;
c.gridy = 1;
panel.add(title,c);
//3RD COLUMN
c.gridwidth = 0;
c.weighty = 3; // changes weight
c.anchor = GridBagConstraints.LINE_START;
c.gridx = 2;
c.gridy = 2;
panel.add(yes,c);
nextFrame.pack();
nextFrame.setLocationRelativeTo(null);
nextFrame.setResizable(false);
nextFrame.setVisible(true);
nextFrame.toFront();
}
Here is the Source code for transparent JFrame:
public class Example extends JFrame {
public Example() {
super("TranslucentWindowDemo");
setLayout(new GridBagLayout());
setSize(500,300);
setLocationRelativeTo(null);
setUndecorated(true);
getContentPane().setBackground(Color.blue);
JButton Close = new JButton("Close");
add(Close);
ActionListener al;
al = new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
System.exit(0);
}
};
Close.addActionListener (al);
}
private void initComponents() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
GroupLayout layout = new GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
pack();
}
public static void main(String args[]) {
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
if (!gd.isWindowTranslucencySupported(TRANSLUCENT)) {
System.err.println("Translucency is not supported");
System.exit(0);
}
try {
for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Example.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
Example e = new Example();
e.setOpacity(0.55f);
e.setVisible(true);
}
});
}
}
For the Opacity, you can try Pane.setOpaque(false);
And for the contents you should change to setBackground(new Color(0, 0, 0, 0));
You can read more here

JFrame with tabs is not being displayed

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.

How to align left or right inside GridBagLayout cell?

I see that GridBagLayout positions it's children with center alignment within cells. How to align left or right?
UPDATE
Constructing code (I know I could reuse c)
// button panel
JPanel button_panel = new JPanel();
button_panel.add(ok_button);
button_panel.add(cancel_button);
// placing controls to dialog
GridBagConstraints c;
GridBagLayout layout = new GridBagLayout();
setLayout(layout);
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
add(inputSource_label, c);
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 0;
add(inputSource_combo, c);
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 1;
add(output_label, c);
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 1;
add(output_combo, c);
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 2;
c.gridwidth = 2;
add(button_panel, c);
When using GridBagLayout for a tabular display of JLabel : JTextField, I like to have a method that makes my GridBagConstraints for me based on the x, y position. For example something like so:
private GridBagConstraints createGbc(int x, int y) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.anchor = (x == 0) ? GridBagConstraints.WEST : GridBagConstraints.EAST;
gbc.fill = (x == 0) ? GridBagConstraints.BOTH
: GridBagConstraints.HORIZONTAL;
gbc.insets = (x == 0) ? WEST_INSETS : EAST_INSETS;
gbc.weightx = (x == 0) ? 0.1 : 1.0;
gbc.weighty = 1.0;
return gbc;
}
The following code makes a GUI that looks like this:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.util.HashMap;
import java.util.Map;
import javax.swing.*;
public class GridBagEg {
private static void createAndShowGui() {
PlayerEditorPanel playerEditorPane = new PlayerEditorPanel();
int result = JOptionPane.showConfirmDialog(null, playerEditorPane,
"Edit Player", JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE);
if (result == JOptionPane.OK_OPTION) {
// TODO: do something with info
for (PlayerEditorPanel.FieldTitle fieldTitle :
PlayerEditorPanel.FieldTitle.values()) {
System.out.printf("%10s: %s%n", fieldTitle.getTitle(),
playerEditorPane.getFieldText(fieldTitle));
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
#SuppressWarnings("serial")
class PlayerEditorPanel extends JPanel {
enum FieldTitle {
NAME("Name"), SPEED("Speed"), STRENGTH("Strength");
private String title;
private FieldTitle(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
};
private static final Insets WEST_INSETS = new Insets(5, 0, 5, 5);
private static final Insets EAST_INSETS = new Insets(5, 5, 5, 0);
private Map<FieldTitle, JTextField> fieldMap = new HashMap<FieldTitle, JTextField>();
public PlayerEditorPanel() {
setLayout(new GridBagLayout());
setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createTitledBorder("Player Editor"),
BorderFactory.createEmptyBorder(5, 5, 5, 5)));
GridBagConstraints gbc;
for (int i = 0; i < FieldTitle.values().length; i++) {
FieldTitle fieldTitle = FieldTitle.values()[i];
gbc = createGbc(0, i);
add(new JLabel(fieldTitle.getTitle() + ":", JLabel.LEFT), gbc);
gbc = createGbc(1, i);
JTextField textField = new JTextField(10);
add(textField, gbc);
fieldMap.put(fieldTitle, textField);
}
}
private GridBagConstraints createGbc(int x, int y) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.anchor = (x == 0) ? GridBagConstraints.WEST : GridBagConstraints.EAST;
gbc.fill = (x == 0) ? GridBagConstraints.BOTH
: GridBagConstraints.HORIZONTAL;
gbc.insets = (x == 0) ? WEST_INSETS : EAST_INSETS;
gbc.weightx = (x == 0) ? 0.1 : 1.0;
gbc.weighty = 1.0;
return gbc;
}
public String getFieldText(FieldTitle fieldTitle) {
return fieldMap.get(fieldTitle).getText();
}
}
In this example, I display the JPanel in a JOptionPane, but it could just as easily be displayed in a JFrame or JApplet or JDialog or ...
For example
public class DimsPanel extends JPanel
{
public static void main(String[] args){
JFrame main = new JFrame("Dims");
JPanel myPanel = new DimsPanel();
main.setContentPane(myPanel);
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
main.setSize(400, 400);
main.setLocationRelativeTo(null);
main.setVisible(true);
}
JButton ok_button = new JButton("OK"), cancel_button = new JButton("Cancel");
JLabel inputSource_label = new JLabel("Input source:"),
output_label = new JLabel("Output:");
JComboBox inputSource_combo = new JComboBox(new String[]{"A", "B", "C"}),
output_combo = new JComboBox(new String[]{"A", "B", "C"});
public DimsPanel(){
super(new BorderLayout());
Box main = new Box(BoxLayout.Y_AXIS);
Dimension labelsWidth = new Dimension(100, 0);
JPanel inputPanel = new JPanel(new BorderLayout());
inputSource_label.setPreferredSize(labelsWidth);
inputPanel.add(inputSource_label, BorderLayout.WEST);
inputPanel.add(inputSource_combo);
JPanel outputPanel = new JPanel(new BorderLayout());
output_label.setPreferredSize(labelsWidth);
outputPanel.add(output_label, BorderLayout.WEST);
outputPanel.add(output_combo);
// button panel
JPanel button_panel = new JPanel();
button_panel.add(ok_button);
button_panel.add(cancel_button);
main.add(inputPanel);
main.add(outputPanel);
add(main, BorderLayout.NORTH);
add(button_panel);
}
}
You can run and see it. Resizing works like a charm and the layout code has only 18 lines.
The only disadvantage is that you need to specify the width of the labels by hand. If you really don't want to see setPreferredSize() in the code, then be my guest and go with GridBag. But I personally like this code more.

Categories