When I try to maximize the window, the orinigal window rendering remains while another maximized window appears making it messy.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.*;
import javax.swing.table.TableColumnModel;
/**
* #author ad *
*/
public class Blotter {
private JFrame topFrame;
private JPanel mainContentPanel;
private JList unsubscribedFields;
private JList subscribedFields;
private JButton butSubscribe;
private JButton butUnsubscribe;
private JButton butApply;
private JButton butOk;
private JButton butCancel;
private JPanel panConfirm;
private JPanel panToggle;
private JPanel panBottom;
private JPanel panLeftList;
private JPanel panRightList;
private JPanel panSubcribe;
private JPanel panUnsubscribe;
/**
* #param args
*/
public Blotter(){
topFrame = new JFrame("Subscription Fields");
mainContentPanel = new JPanel(new BorderLayout());
/*
butSubscribe = new JButton("-->");
butUnsubscribe= new JButton("<--");
butApply = new JButton("Apply");
butOk = new JButton("OK");
butCancel = new JButton("Cancel");*/
createAndBuildGui();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Blotter b = new Blotter();
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch (Exception e) {
e.printStackTrace();
}
b.createAndBuildGui();
b.fillGUI();
}
private void fillGUI() {
String[] someRow = {"S110","200","100","42","32"};
}
public void createAndBuildGui()
{
panConfirm = new JPanel(new GridLayout(1,3,5,5));
panToggle = new JPanel(new GridBagLayout());
panBottom = new JPanel(new FlowLayout());
butApply = new JButton("Apply");
butOk = new JButton("OK");
butCancel = new JButton("Cancel");
unsubscribedFields = new JList();
subscribedFields = new JList();
butSubscribe = new JButton(">>>");
butUnsubscribe = new JButton("<<<");
panSubcribe = new JPanel(new BorderLayout());
panUnsubscribe = new JPanel(new BorderLayout());
panLeftList = new JPanel(new BorderLayout());
panRightList = new JPanel(new BorderLayout());
// GridBagConstraints(int gridx, int gridy, int gridwidth,
// int gridheight, double weightx, double weighty,
// int anchor, int fill, Insets insets, int ipadx, int ipady)
panLeftList.add(unsubscribedFields, BorderLayout.CENTER);
panRightList.add(subscribedFields, BorderLayout.CENTER);
panSubcribe.add(butSubscribe, BorderLayout.SOUTH);
panUnsubscribe.add(butUnsubscribe, BorderLayout.NORTH);
panToggle.add(panLeftList,
new GridBagConstraints(0, 0, 1, 2, 0.5, 1, GridBagConstraints.CENTER,
GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
panToggle.add(panRightList,
new GridBagConstraints(2, 0, 1, 2, 0.5, 1, GridBagConstraints.CENTER,
GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
panToggle.add(panSubcribe,
new GridBagConstraints(1, 0, 1, 1, 0, 0.5, GridBagConstraints.SOUTH,
GridBagConstraints.NONE, new Insets(0, 2, 4, 4), 0, 0));
panToggle.add(panUnsubscribe,
new GridBagConstraints(1, 1, 1, 1, 0, 0.5, GridBagConstraints.NORTH,
GridBagConstraints.NONE, new Insets(0, 2, 4, 4), 0, 0));
// Building bottom OK Apply Cancel panel.
panConfirm.add(butApply, 0);
panConfirm.add(butOk, 1);
panConfirm.add(butCancel, 2);
panBottom = new JPanel(new FlowLayout(FlowLayout.RIGHT));
panBottom.add(panConfirm, BorderLayout.EAST);
// building main content panel
mainContentPanel.add(panToggle,BorderLayout.CENTER);
mainContentPanel.add(panBottom, BorderLayout.SOUTH);
topFrame.add(mainContentPanel);
topFrame.pack();
topFrame.setVisible(true);
topFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
protected void createPriceTable() {
// More fields : "Quantity Done","Quantity Open","PInst","State","Cancel State","Executing System","WaveID","Source System","TraderID","Average Price","LastExecutionPrice","ClientOrderTag","OldQuantityDone"
String[] columnNames = {"OrderId","Account","Symbol","Side","Quantity",};
Object[][] o = new Object[0][columnNames.length];
}
}
You're calling createAndBuildGui() twice: once in main and once in the constructor.
public Blotter(){
topFrame = new JFrame("Subscription Fields");
mainContentPanel = new JPanel(new BorderLayout());
// ...
createAndBuildGui(); <--------
}
public static void main(String[] args) {
Blotter b = new Blotter();
// ...
b.createAndBuildGui(); <--------
b.fillGUI();
}
If you remove one of them, it works just fine.
It depends on layout manager you are using. For example BorderLayout knows to re-render elements when frame size is changed. Unfortunately you did not mention which window works for you and which does not but I saw GridBagLayout in your code. Probably this layout (better to say usage of this layout) prevents similar behavior.
Related
I am trying to get the code to calculate the windchill, but it is not working. I want the calculations to appear on a separate window when they are done.
In addition I need the program to have a separate error dialog box appear when invalid data is entered or when a wind chill is not valid, and the text in the GUI should reflect the issue. And the file entry button when selected, should display a file selection window. File opening errors will be handled with exceptions and dialog boxes. If the file is valid and opened successfully, the program will read in the data, compute the results, and display the data and results in columns in a separate window created through a separate class and Java file, and plot the Temperature and Wind Chill values.
Code:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.Color;
import javax.swing.border.LineBorder;
import javax.swing.JLabel;
import java.awt.FlowLayout;
import java.awt.Font;
import java.util.Scanner;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class WindChillCalculations extends JFrame {
private JPanel contentPane;
private static JTextField Fahrenheit_textField;
private static JTextField Mph_textField;
private static JTextField DewPoint_textField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
WindChillCalculations frame = new WindChillCalculations();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
String fahrenheit = Fahrenheit_textField.getText();
String speed = Mph_textField.getText();
String dewpoint = DewPoint_textField.getText();
double t = Double.parseDouble(fahrenheit);
double v = Double.parseDouble(speed);
double d = Double.parseDouble(dewpoint);
//Calculate windchill
double w = 35.74 + (0.6215 * t) - (35.75 * (Math.pow(v,0.16))) + (0.4275 * (t * (Math.pow(v,0.16))));
//Format to keep the windchill to 2 digits after decimal
w = (int)(w*100)/100.0;
}
/**
* Create the frame.
*/
public WindChillCalculations() {
setTitle("Weather Data Program - Wind Chill Calculations");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 491, 383);
contentPane = new JPanel();
contentPane.setForeground(Color.WHITE);
contentPane.setBackground(Color.BLACK);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panel = new JPanel();
panel.setToolTipText("");
panel.setBorder(new LineBorder(Color.WHITE));
panel.setForeground(Color.BLACK);
panel.setBackground(Color.BLACK);
panel.setBounds(2, 4, 470, 338);
contentPane.add(panel);
panel.setLayout(null);
JLabel WindChillCalculationsLabel = new JLabel("Wind Chill Calculations");
WindChillCalculationsLabel.setBounds(146, 6, 137, 15);
WindChillCalculationsLabel.setFont(new Font("Tahoma", Font.BOLD, 12));
panel.add(WindChillCalculationsLabel);
WindChillCalculationsLabel.setForeground(Color.WHITE);
JLabel Fahrenheit_Label = new JLabel("Enter the temperature in degrees Fahrenheit:");
Fahrenheit_Label.setForeground(new Color(255, 140, 0));
Fahrenheit_Label.setBounds(10, 67, 305, 14);
panel.add(Fahrenheit_Label);
Fahrenheit_textField = new JTextField();
Fahrenheit_textField.setBounds(338, 64, 86, 20);
panel.add(Fahrenheit_textField);
Fahrenheit_textField.setHorizontalAlignment(JTextField.RIGHT);
Fahrenheit_textField.setColumns(10);
JLabel Mph_Label = new JLabel("Enter the wind speed in mph:");
Mph_Label.setForeground(new Color(255, 140, 0));
Mph_Label.setBounds(10, 123, 305, 14);
panel.add(Mph_Label);
Mph_textField = new JTextField();
Mph_textField.setColumns(10);
Mph_textField.setBounds(338, 120, 86, 20);
Mph_textField.setHorizontalAlignment(JTextField.RIGHT);
panel.add(Mph_textField);
JLabel DewPoint_Label = new JLabel("Enter the dew point in degrees Fahrenheit:");
DewPoint_Label.setForeground(new Color(255, 140, 0));
DewPoint_Label.setBounds(10, 177, 305, 14);
panel.add(DewPoint_Label);
DewPoint_textField = new JTextField();
DewPoint_textField.setColumns(10);
DewPoint_textField.setBounds(338, 174, 86, 20);
DewPoint_textField.setHorizontalAlignment(JTextField.RIGHT);
panel.add(DewPoint_textField);
JButton FileEntry_btn = new JButton("File Entry");
FileEntry_btn.setBackground(Color.BLACK);
FileEntry_btn.setForeground(new Color(255, 140, 0));
FileEntry_btn.setBounds(39, 283, 89, 23);
panel.add(FileEntry_btn);
JButton Compute_btn = new JButton("Compute");
Compute_btn.setForeground(new Color(255, 140, 0));
Compute_btn.setBackground(Color.BLACK);
Compute_btn.setBounds(301, 283, 89, 23);
panel.add(Compute_btn);
Compute_btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
WeatherOutput output = new WeatherOutput();
output.setVisible(true);
}
});
}
}
I don't think this answer will satisfy the OP. I hope others will learn from it.
Here are the changes I made to the code.
I used a JFrame. I didn't extend a JFrame. You only extend a Swing component, or any Java class, when you want to override one of the class methods.
I created the GUI and gave the user a chance to type values before I calculated the wind speed.
I eliminated all absolute positioning and used Swing layout managers. I created a master JPanel and two subordinate JPanels, one to hold the labels and text fields, and the other to hold the buttons. The master panel used a BorderLayout, the labels and text fields panel used a GridBagLayout, and the buttons panel used a GridBagLayout so the buttons would expand horizontally to fill the area.
I used camelCase variable names in the code.
Here's the GUI result.
I formatted the code so it would be easier to see the methods and classes.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
public class WindChillCalculations {
private JPanel contentPane;
private JTextField fahrenheit_textField;
private JTextField mph_textField;
private JTextField dewPoint_textField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
new WindChillCalculations();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public WindChillCalculations() {
// top, left, bottom, right
Insets topInsets = new Insets(10, 10, 10, 10);
Insets topRightInsets = new Insets(10, 0, 10, 10);
Insets insets = new Insets(0, 10, 10, 10);
Insets rightInsets = new Insets(0, 0, 10, 10);
Color textColor = new Color(255, 140, 0);
JFrame frame = new JFrame();
frame.setTitle("Weather Data Program - "
+ "Wind Chill Calculations");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = new JPanel();
contentPane.setForeground(Color.WHITE);
contentPane.setBackground(Color.BLACK);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout());
JLabel windChillCalculationsLabel = new JLabel(
"Wind Chill Calculations");
windChillCalculationsLabel.setFont(new Font(
"Tahoma", Font.BOLD, 12));
windChillCalculationsLabel.setForeground(Color.WHITE);
windChillCalculationsLabel.setHorizontalAlignment(
JLabel.CENTER);
contentPane.add(windChillCalculationsLabel,
BorderLayout.BEFORE_FIRST_LINE);
JPanel panel = new JPanel();
panel.setToolTipText("");
panel.setBorder(new LineBorder(Color.WHITE));
panel.setForeground(Color.BLACK);
panel.setBackground(Color.BLACK);
panel.setLayout(new GridBagLayout());
int gridy = 0;
JLabel fahrenheit_Label = new JLabel("Enter the "
+ "temperature in degrees Fahrenheit:");
fahrenheit_Label.setForeground(textColor);
addComponent(panel, fahrenheit_Label, 0, gridy, 1, 1,
topInsets, GridBagConstraints.LINE_START,
GridBagConstraints.HORIZONTAL);
fahrenheit_textField = new JTextField(15);
fahrenheit_textField.setHorizontalAlignment(
JTextField.RIGHT);
addComponent(panel, fahrenheit_textField, 1, gridy++, 1, 1,
topRightInsets, GridBagConstraints.LINE_START,
GridBagConstraints.HORIZONTAL);
JLabel mph_Label = new JLabel("Enter the wind "
+ "speed in mph:");
mph_Label.setForeground(textColor);
addComponent(panel, mph_Label, 0, gridy, 1, 1,
insets, GridBagConstraints.LINE_START,
GridBagConstraints.HORIZONTAL);
mph_textField = new JTextField(15);
mph_textField.setHorizontalAlignment(JTextField.RIGHT);
addComponent(panel, mph_textField, 1, gridy++, 1, 1,
rightInsets, GridBagConstraints.LINE_START,
GridBagConstraints.HORIZONTAL);
JLabel dewPoint_Label = new JLabel("Enter the "
+ "dew point in degrees Fahrenheit:");
dewPoint_Label.setForeground(textColor);
addComponent(panel, dewPoint_Label, 0, gridy, 1, 1,
insets, GridBagConstraints.LINE_START,
GridBagConstraints.HORIZONTAL);
dewPoint_textField = new JTextField(15);
dewPoint_textField.setHorizontalAlignment(
JTextField.RIGHT);
addComponent(panel, dewPoint_textField, 1, gridy++, 1, 1,
rightInsets, GridBagConstraints.LINE_START,
GridBagConstraints.HORIZONTAL);
contentPane.add(panel, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel();
buttonPanel.setBackground(Color.BLACK);
buttonPanel.setForeground(Color.BLACK);
buttonPanel.setLayout(new GridBagLayout());
JButton fileEntry_btn = new JButton("File Entry");
fileEntry_btn.setBackground(Color.BLACK);
fileEntry_btn.setForeground(textColor);
addComponent(buttonPanel, fileEntry_btn, 0, 0, 1, 1,
topInsets, GridBagConstraints.CENTER,
GridBagConstraints.HORIZONTAL);
JButton compute_btn = new JButton("Compute");
compute_btn.setForeground(textColor);
compute_btn.setBackground(Color.BLACK);
compute_btn.setBounds(301, 283, 89, 23);
addComponent(buttonPanel, compute_btn, 1, 0, 1, 1,
topRightInsets, GridBagConstraints.CENTER,
GridBagConstraints.HORIZONTAL);
compute_btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String fahrenheit = fahrenheit_textField.getText();
String speed = mph_textField.getText();
String dewpoint = dewPoint_textField.getText();
try {
double f = Double.valueOf(fahrenheit);
double s = Double.valueOf(speed);
double d = Double.valueOf(dewpoint);
WindChill windChill = new WindChill(f, s, d);
double answer = windChill.calculateWindChill();
//TODO Create output display
System.out.println(answer);
} catch (NumberFormatException e1) {
e1.printStackTrace();
}
}
});
contentPane.add(buttonPanel, BorderLayout.AFTER_LAST_LINE);
frame.add(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private void addComponent(Container container,
Component component, int gridx, int gridy,
int gridwidth, int gridheight, Insets insets,
int anchor, int fill) {
GridBagConstraints gbc = new GridBagConstraints(
gridx, gridy, gridwidth, gridheight,
1.0, 1.0, anchor, fill, insets, 0, 0);
container.add(component, gbc);
}
public class WindChill {
private final double temperature;
private final double windSpeed;
private final double dewPoint;
public WindChill(double temperature, double windSpeed,
double dewPoint) {
this.temperature = temperature;
this.windSpeed = windSpeed;
this.dewPoint = dewPoint;
}
public double calculateWindChill() {
double factor = Math.pow(windSpeed, 0.16);
return 35.74d + (0.6215d * temperature) -
(35.75d * (factor)) +
(0.4275 * (dewPoint * (factor)));
}
}
}
I'm following the previous suggestion of adopting a JList and calling setVisibleRowCount() in my JDialog.
I tried to restrict the number of rows to 2; however the dialog is packed into a big, unscrolled JList. I expected it would show only 2 rows and the rest would be reached through scrolling, leaving space for a future third element in the design (the orders list).
Please take a look at the SSCCE.
TestDialog.java
package testdialog;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class TestDialog {
private static void createAndShowGUI() {
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Click me");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
new JDViewCustomer(frame, true).setVisible(true);
}
});
frame.getContentPane().add(button, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
CustomerAddress.java
package testdialog;
public class CustomerAddress {
private final String title;
public CustomerAddress(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
}
JDViewCustomer.java
package testdialog;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridBagLayout;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.swing.BoxLayout;
import javax.swing.DefaultListModel;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
public class JDViewCustomer extends javax.swing.JDialog {
private static final long serialVersionUID = 1L;
private final JPanel jPanelCustomerInfo;
private final JPanel jPanelCustomerAddresses;
private final JPanel jPanelCustomerOrders;
private JTextField txtarea_1;
private JPanel panelNomeDoCliente;
private JPanel panelDadosDoCliente;
private JPanel panelAbaixoDeCustomerAddresses;
private JPanel panelTituloEnderecos;
private JPanel panelContendoOsEnderecos;
private JLabel lblEnderecos;
private JPanel panel;
private JScrollPane scrollPane;
private JList<CustomerAddress> jListCustomerAddresses;
public JDViewCustomer(java.awt.Frame parent, boolean modal) {
super(parent, modal);
getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
panel = new JPanel();
getContentPane().add(panel);
/*scrollPane = new JScrollPane(panel);
getContentPane().add(scrollPane);*/
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
jPanelCustomerInfo = new JPanel();
panel.add(jPanelCustomerInfo);
jPanelCustomerInfo.setBackground(new Color(255, 255, 255));
jPanelCustomerInfo.setBorder(new CompoundBorder(new LineBorder(new Color(0, 0, 0), 1, true), new EmptyBorder(10, 10, 10, 10)));
jPanelCustomerInfo.setLayout(new BoxLayout(jPanelCustomerInfo, BoxLayout.Y_AXIS));
panelNomeDoCliente = new JPanel();
panelNomeDoCliente.setBorder(new CompoundBorder(new LineBorder(new Color(0, 0, 0), 1, true), new EmptyBorder(10, 10, 10, 10)));
panelNomeDoCliente.setBackground(Color.LIGHT_GRAY);
jPanelCustomerInfo.add(panelNomeDoCliente);
GridBagLayout gbl_panelNomeDoCliente = new GridBagLayout();
gbl_panelNomeDoCliente.columnWidths = new int[]{73, 376, 45, 53, 0};
gbl_panelNomeDoCliente.rowHeights = new int[]{31, 0};
gbl_panelNomeDoCliente.columnWeights = new double[]{0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
gbl_panelNomeDoCliente.rowWeights = new double[]{0.0, Double.MIN_VALUE};
panelNomeDoCliente.setLayout(gbl_panelNomeDoCliente);
panelDadosDoCliente = new JPanel();
panelDadosDoCliente.setBorder(new CompoundBorder(new LineBorder(new Color(0, 0, 0), 1, true), new EmptyBorder(10, 10, 10, 10)));
panelDadosDoCliente.setBackground(Color.WHITE);
jPanelCustomerInfo.add(panelDadosDoCliente);
GridBagLayout gbl_panelDadosDoCliente = new GridBagLayout();
gbl_panelDadosDoCliente.columnWidths = new int[]{58, 199, 38, 102, 27, 123, 0};
gbl_panelDadosDoCliente.rowHeights = new int[]{0, 14, 0};
gbl_panelDadosDoCliente.columnWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
gbl_panelDadosDoCliente.rowWeights = new double[]{0.0, 0.0, Double.MIN_VALUE};
panelDadosDoCliente.setLayout(gbl_panelDadosDoCliente);
jPanelCustomerAddresses = new JPanel();
scrollPane = new JScrollPane(jPanelCustomerAddresses);
getContentPane().add(scrollPane);
//panel.add(jPanelCustomerAddresses);
jPanelCustomerAddresses.setBackground(new Color(255, 255, 255));
jPanelCustomerAddresses.setBorder(new CompoundBorder(new LineBorder(new Color(0, 0, 0), 1, true), new EmptyBorder(10, 10, 10, 10)));
jPanelCustomerAddresses.setLayout(new BoxLayout(jPanelCustomerAddresses, BoxLayout.Y_AXIS));
panelAbaixoDeCustomerAddresses = new JPanel();
panelAbaixoDeCustomerAddresses.setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
jPanelCustomerAddresses.add(panelAbaixoDeCustomerAddresses);
panelAbaixoDeCustomerAddresses.setLayout(new BoxLayout(panelAbaixoDeCustomerAddresses, BoxLayout.Y_AXIS));
panelTituloEnderecos = new JPanel();
panelTituloEnderecos.setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
FlowLayout fl_panelTituloEnderecos = (FlowLayout) panelTituloEnderecos.getLayout();
fl_panelTituloEnderecos.setAlignment(FlowLayout.LEFT);
panelTituloEnderecos.setBackground(Color.LIGHT_GRAY);
panelAbaixoDeCustomerAddresses.add(panelTituloEnderecos);
lblEnderecos = new JLabel("Endereço");
panelTituloEnderecos.add(lblEnderecos);
panelContendoOsEnderecos = new JPanel();
panelContendoOsEnderecos.setBorder(new CompoundBorder(new LineBorder(new Color(0, 0, 0), 1, true), new EmptyBorder(10, 10, 10, 10)));
panelContendoOsEnderecos.setBackground(Color.WHITE);
panelAbaixoDeCustomerAddresses.add(panelContendoOsEnderecos);
panelContendoOsEnderecos.setLayout(new BoxLayout(panelContendoOsEnderecos, BoxLayout.Y_AXIS));
jPanelCustomerOrders = new JPanel();
panel.add(jPanelCustomerOrders);
txtarea_1 = new JTextField();
txtarea_1.setText("Área 3");
jPanelCustomerOrders.add(txtarea_1);
txtarea_1.setColumns(10);
initComponents();
pack();
setLocationRelativeTo(parent);
LoadCustomerDataWorker worker = new LoadCustomerDataWorker(this);
ExecutorService singleThreadPool = Executors.newSingleThreadExecutor();
singleThreadPool.execute(worker);
}
public void addCustomerAddresses(List<CustomerAddress> customerAddresses) {
Objects.requireNonNull(customerAddresses);
DefaultListModel<CustomerAddress> listModel = new DefaultListModel<>();
for (CustomerAddress customerAddress : customerAddresses) {
listModel.addElement(customerAddress);
}
jListCustomerAddresses = new JList<>(listModel);
jListCustomerAddresses.setCellRenderer(new PanelIndividualCustomerAddress());
jListCustomerAddresses.setVisibleRowCount(2);
panelContendoOsEnderecos.add(jListCustomerAddresses);
pack();
}
private void initComponents() {
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Ver Cliente");
}
}
LoadCustomerDataWorker.java
package testdialog;
import java.util.ArrayList;
import java.util.List;
import javax.swing.SwingWorker;
import testdialog.JDViewCustomer;
import testdialog.CustomerAddress;
public class LoadCustomerDataWorker extends SwingWorker<Void, Void> {
private final JDViewCustomer dialog;
private List<CustomerAddress> customerAddresses = null;
public LoadCustomerDataWorker(JDViewCustomer dialog) {
this.dialog = dialog;
}
#Override
protected Void doInBackground() throws Exception {
customerAddresses = new ArrayList<>();
customerAddresses.add(new CustomerAddress("1. Casa"));
customerAddresses.add(new CustomerAddress("2. Trabalho"));
customerAddresses.add(new CustomerAddress("3. Casa"));
customerAddresses.add(new CustomerAddress("4. Trabalho"));
return null;
}
#Override
protected void done() {
if (customerAddresses != null && customerAddresses.size() > 0) {
dialog.addCustomerAddresses(customerAddresses);
}
}
}
PanelIndividualCustomerAddress.java
package testdialog;
import java.awt.Color;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.ListCellRenderer;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import testdialog.CustomerAddress;
public class PanelIndividualCustomerAddress implements ListCellRenderer<CustomerAddress> {
#Override
public Component getListCellRendererComponent(JList<? extends CustomerAddress> list, CustomerAddress value, int index, boolean isSelected,
boolean cellHasFocus) {
JPanel panelEnderecoIndividual = new JPanel();
panelEnderecoIndividual.setBorder(new CompoundBorder(new LineBorder(new Color(0, 0, 0), 1, true), new EmptyBorder(3, 3, 3, 3)));
panelEnderecoIndividual.setBackground(Color.WHITE);
panelEnderecoIndividual.setLayout(new BoxLayout(panelEnderecoIndividual, BoxLayout.Y_AXIS));
JPanel panelTituloEndereco = new JPanel();
panelTituloEndereco.setBorder(new CompoundBorder(new LineBorder(new Color(0, 0, 0), 1, true), new EmptyBorder(10, 10, 10, 10)));
FlowLayout fl_panelTituloEndereco = (FlowLayout) panelTituloEndereco.getLayout();
fl_panelTituloEndereco.setAlignment(FlowLayout.LEFT);
panelTituloEndereco.setBackground(new Color(220, 220, 220));
panelEnderecoIndividual.add(panelTituloEndereco);
JLabel lblCasa = new JLabel(value.getTitle()); // "Casa"
panelTituloEndereco.add(lblCasa);
JPanel panelDadosDoEndereco = new JPanel();
panelDadosDoEndereco.setBorder(new CompoundBorder(new LineBorder(new Color(0, 0, 0), 1, true), new EmptyBorder(10, 10, 10, 10)));
panelDadosDoEndereco.setBackground(Color.WHITE);
panelEnderecoIndividual.add(panelDadosDoEndereco);
GridBagLayout gbl_panelDadosDoEndereco = new GridBagLayout();
gbl_panelDadosDoEndereco.columnWidths = new int[]{83, 184, 68, 102, 65, 134, 0};
gbl_panelDadosDoEndereco.rowHeights = new int[]{0, 0, 20, 0};
gbl_panelDadosDoEndereco.columnWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
gbl_panelDadosDoEndereco.rowWeights = new double[]{0.0, 0.0, 0.0, Double.MIN_VALUE};
panelDadosDoEndereco.setLayout(gbl_panelDadosDoEndereco);
JLabel lblEndereco = new JLabel("Endereço:");
lblEndereco.setFont(new Font("Tahoma", Font.BOLD, 11));
GridBagConstraints gbc_lblEndereo = new GridBagConstraints();
gbc_lblEndereo.anchor = GridBagConstraints.WEST;
gbc_lblEndereo.insets = new Insets(0, 0, 5, 5);
gbc_lblEndereo.gridx = 0;
gbc_lblEndereo.gridy = 0;
panelDadosDoEndereco.add(lblEndereco, gbc_lblEndereo);
JLabel lblNomeDaRua = new JLabel("Nome da rua");
GridBagConstraints gbc_lblNomeDaRua = new GridBagConstraints();
gbc_lblNomeDaRua.anchor = GridBagConstraints.WEST;
gbc_lblNomeDaRua.gridwidth = 3;
gbc_lblNomeDaRua.insets = new Insets(0, 0, 5, 5);
gbc_lblNomeDaRua.gridx = 1;
gbc_lblNomeDaRua.gridy = 0;
panelDadosDoEndereco.add(lblNomeDaRua, gbc_lblNomeDaRua);
JLabel lblNumero = new JLabel("Número:");
lblNumero.setFont(new Font("Tahoma", Font.BOLD, 11));
GridBagConstraints gbc_lblNumero = new GridBagConstraints();
gbc_lblNumero.anchor = GridBagConstraints.WEST;
gbc_lblNumero.insets = new Insets(0, 0, 5, 5);
gbc_lblNumero.gridx = 4;
gbc_lblNumero.gridy = 0;
panelDadosDoEndereco.add(lblNumero, gbc_lblNumero);
JLabel lblValorDoNumero = new JLabel("Valor do número");
GridBagConstraints gbc_lblValorDoNumero = new GridBagConstraints();
gbc_lblValorDoNumero.anchor = GridBagConstraints.WEST;
gbc_lblValorDoNumero.insets = new Insets(0, 0, 5, 0);
gbc_lblValorDoNumero.gridx = 5;
gbc_lblValorDoNumero.gridy = 0;
panelDadosDoEndereco.add(lblValorDoNumero, gbc_lblValorDoNumero);
JLabel lblComplemento = new JLabel("Complemento:");
lblComplemento.setFont(new Font("Tahoma", Font.BOLD, 11));
GridBagConstraints gbc_lblComplemento = new GridBagConstraints();
gbc_lblComplemento.anchor = GridBagConstraints.WEST;
gbc_lblComplemento.insets = new Insets(0, 0, 5, 5);
gbc_lblComplemento.gridx = 0;
gbc_lblComplemento.gridy = 1;
panelDadosDoEndereco.add(lblComplemento, gbc_lblComplemento);
JLabel lblTextoDoComplemento = new JLabel("Texto do complemento");
GridBagConstraints gbc_lblTextoDoComplemento = new GridBagConstraints();
gbc_lblTextoDoComplemento.anchor = GridBagConstraints.WEST;
gbc_lblTextoDoComplemento.insets = new Insets(0, 0, 5, 5);
gbc_lblTextoDoComplemento.gridx = 1;
gbc_lblTextoDoComplemento.gridy = 1;
panelDadosDoEndereco.add(lblTextoDoComplemento, gbc_lblTextoDoComplemento);
JLabel lblBairro = new JLabel("Bairro:");
lblBairro.setFont(new Font("Tahoma", Font.BOLD, 11));
GridBagConstraints gbc_lblBairro = new GridBagConstraints();
gbc_lblBairro.anchor = GridBagConstraints.WEST;
gbc_lblBairro.insets = new Insets(0, 0, 5, 5);
gbc_lblBairro.gridx = 2;
gbc_lblBairro.gridy = 1;
panelDadosDoEndereco.add(lblBairro, gbc_lblBairro);
JLabel lblNomeDoBairro = new JLabel("Nome do bairro");
GridBagConstraints gbc_lblNomeDoBairro = new GridBagConstraints();
gbc_lblNomeDoBairro.anchor = GridBagConstraints.WEST;
gbc_lblNomeDoBairro.insets = new Insets(0, 0, 5, 5);
gbc_lblNomeDoBairro.gridx = 3;
gbc_lblNomeDoBairro.gridy = 1;
panelDadosDoEndereco.add(lblNomeDoBairro, gbc_lblNomeDoBairro);
JLabel lblCidade = new JLabel("Cidade:");
lblCidade.setFont(new Font("Tahoma", Font.BOLD, 11));
GridBagConstraints gbc_lblCidade = new GridBagConstraints();
gbc_lblCidade.anchor = GridBagConstraints.WEST;
gbc_lblCidade.insets = new Insets(0, 0, 5, 5);
gbc_lblCidade.gridx = 4;
gbc_lblCidade.gridy = 1;
panelDadosDoEndereco.add(lblCidade, gbc_lblCidade);
JLabel lblNomeDaCidade = new JLabel("Nome da cidade");
GridBagConstraints gbc_lblNomeDaCidade = new GridBagConstraints();
gbc_lblNomeDaCidade.anchor = GridBagConstraints.WEST;
gbc_lblNomeDaCidade.insets = new Insets(0, 0, 5, 0);
gbc_lblNomeDaCidade.gridx = 5;
gbc_lblNomeDaCidade.gridy = 1;
panelDadosDoEndereco.add(lblNomeDaCidade, gbc_lblNomeDaCidade);
JLabel lblCep = new JLabel("CEP:");
lblCep.setFont(new Font("Tahoma", Font.BOLD, 11));
GridBagConstraints gbc_lblCep = new GridBagConstraints();
gbc_lblCep.anchor = GridBagConstraints.WEST;
gbc_lblCep.insets = new Insets(0, 0, 0, 5);
gbc_lblCep.gridx = 0;
gbc_lblCep.gridy = 2;
panelDadosDoEndereco.add(lblCep, gbc_lblCep);
JLabel lblNumeroDoCep = new JLabel("Número do CEP");
GridBagConstraints gbc_lblNumeroDoCep = new GridBagConstraints();
gbc_lblNumeroDoCep.anchor = GridBagConstraints.WEST;
gbc_lblNumeroDoCep.insets = new Insets(0, 0, 0, 5);
gbc_lblNumeroDoCep.gridx = 1;
gbc_lblNumeroDoCep.gridy = 2;
panelDadosDoEndereco.add(lblNumeroDoCep, gbc_lblNumeroDoCep);
JLabel lblPontoRef = new JLabel("Ponto ref.:");
lblPontoRef.setFont(new Font("Tahoma", Font.BOLD, 11));
GridBagConstraints gbc_lblPontoRef = new GridBagConstraints();
gbc_lblPontoRef.anchor = GridBagConstraints.WEST;
gbc_lblPontoRef.insets = new Insets(0, 0, 0, 5);
gbc_lblPontoRef.gridx = 2;
gbc_lblPontoRef.gridy = 2;
panelDadosDoEndereco.add(lblPontoRef, gbc_lblPontoRef);
JLabel lblPertoDeTalLugar = new JLabel("Perto de tal lugar");
GridBagConstraints gbc_lblPertoDeTalLugar = new GridBagConstraints();
gbc_lblPertoDeTalLugar.anchor = GridBagConstraints.WEST;
gbc_lblPertoDeTalLugar.gridwidth = 3;
gbc_lblPertoDeTalLugar.gridx = 3;
gbc_lblPertoDeTalLugar.gridy = 2;
panelDadosDoEndereco.add(lblPertoDeTalLugar, gbc_lblPertoDeTalLugar);
return panelEnderecoIndividual;
}
}
setVisibleRowCount() only works if the JList is the view of a JScrollPane (that is, the main child of the JScrollPane). In your program, the JScrollPane’s view is a JPanel, not a JList.
I am trying to make a design to my java app and I want to make 2 groups I have already done creating 2 groups using JPanel but I am trying to make a legend design type. Now here is my question is there a way to make the overflow of the JPanel visible?
Take a look at the white space in the border of the jpanel there is a jlabel there but its content are out of bound of the panel I want to show them.
here is my code:
package myproject;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GUI extends JFrame {
private static final long serialVersionUID = 1L;
private JLabel jlabel1, jlabel2, lbtitle1, lbtitle2;
private JTextArea lbresult;
private JPanel layout, group1, group2;
private JButton btnlogin;
private JTextField jtxemail, jtxpass;
public GUI() {
// TODO Auto-generated constructor stub
super("This is my interface");
setSize(500,420);
setLayout(new BorderLayout(0, 0));
doDrawing();
add(layout, BorderLayout.CENTER);
}
private void doDrawing() {
// TODO Auto-generated method stub
layout = new JPanel();
layout.setLayout(null);
layout.setBackground(Color.WHITE);
layout.setSize(this.getWidth(), this.getHeight());
group1 = createGroup(group1, 0, 15, layout.getWidth() * 50/100, 50);
lbtitle1 = new JLabel("Email");
lbtitle1.setBounds(10, -15, 100, 30);
lbtitle1.setOpaque(true);
lbtitle1.setBackground(Color.WHITE);
//create label1:
jlabel1 = new JLabel("Email: ");
jlabel1.setBounds(10, 10, 100, 30);
//create textfield1:
jtxemail = new JTextField();
jtxemail.setBounds(120, 10, 100, 30);
//add objects for the group:
group1.add(lbtitle1);
group1.add(jlabel1);
group1.add(jtxemail);
layout.add(group1);
}
private JPanel createGroup(JPanel group, int x, int y, int width, int height) {
group = new JPanel();
group.setLayout(null);
group.setBounds(x, y, 0, 0);
group.setSize(width, height);
group.setBackground(new Color(0,0,0,0));
group.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY, 1, false));
return group;
}
}
You could do something like this using a combination of layouts. For instance if you wanted a single column of data for input, then the overall layout could be a GridLayout(0, 1), creating a grid of one column and variable number of rows. Then the rows themselves would be made of a JPanel that uses, say GridBagLayout. Something like so:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.util.HashMap;
import java.util.Map;
import javax.swing.*;
public class GUI2 extends JPanel {
private static final String[][] LABELS = {
{"E-Mail", "E-Mail Address"},
{"Phone", "Phone Number"},
{"Address", "Street Address"},
{"City", "City"},
{"State", "State"} };
private static final int TXT_FIELD_COLS = 15;
private Map<String, JTextField> labelFieldMap = new HashMap<>();
public GUI2() {
setLayout(new GridLayout(0, 1));
for (String[] label : LABELS) {
add(createLegend(label));
}
}
private JPanel createLegend(String[] label) {
JLabel jLabel = new JLabel(label[1]);
JTextField txtField = new JTextField(TXT_FIELD_COLS);
labelFieldMap.put(label[0], txtField);
JPanel legendPanel = new JPanel();
legendPanel.setBorder(BorderFactory.createTitledBorder(label[0]));
legendPanel.setLayout(new GridBagLayout());
int anchor = GridBagConstraints.WEST;
int fill = GridBagConstraints.HORIZONTAL;
int ins = 3;
Insets insets = new Insets(ins, ins, ins, 3* ins);
GridBagConstraints gbc = new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, anchor, fill, insets, 0, 0);
legendPanel.add(jLabel, gbc);
gbc.gridx = 1;
gbc.weightx = 0.0;
gbc.anchor = GridBagConstraints.EAST;
legendPanel.add(txtField, gbc);
return legendPanel;
}
private static void createAndShowGui() {
GUI2 mainPanel = new GUI2();
JFrame frame = new JFrame("GUI2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
Basiclly I got 2 calsses, SSPUserInput and SSPViewer.
I want to press a button in SSPUserInput class and change a JLabel name in SSPViewer. It's basically a rock paper scissor game. This is my first time posting here, I'm sorry if I've done something wrong.
package p3;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class SSPUserInput extends JPanel implements ActionListener {
private JPanel panel = new JPanel();
private JButton btnRock = new JButton ("Rock");
private JButton btnScissor = new JButton ("Scissor");
private JButton btnPaper = new JButton ("Paper");
private JButton btnNewGame = new JButton ("New game");
private JButton btnQuit = new JButton ("Quit");
private Font plainSS14 = new Font("SansSerif", Font.PLAIN, 14);
private SSPViewer lblHumanChoice;
private String rock;
private int scissor;
private int paper;
public SSPUserInput(SSPViewer lblHumanChoice) {
this.lblHumanChoice = lblHumanChoice;
}
public SSPUserInput(){
setPreferredSize (new Dimension(400, 200));
setLayout( null);
btnRock.setBounds(20, 50, 100, 35);
btnRock.setFont(plainSS14);
btnRock.addActionListener(this);
btnScissor.setBounds(155, 50, 100, 35);
btnScissor.setFont(plainSS14);
btnScissor.addActionListener(this);
btnPaper.setBounds(290, 50, 100, 35);
btnPaper.setFont(plainSS14);
btnPaper.addActionListener(this);
btnNewGame.setBounds(20, 100, 370, 35);
btnNewGame.setFont(plainSS14);
btnNewGame.addActionListener(this);
btnQuit.setBounds(20, 150, 370, 35);
btnQuit.setFont(plainSS14);
btnQuit.addActionListener(this);
add(btnRock);
add(btnScissor);
add(btnPaper);
add(btnNewGame);
add(btnQuit);
}
// public String getRock() {
// return rock;
// }
public void actionPerformed(ActionEvent e) {
if( e.getSource() == btnRock ) {
JOptionPane.showMessageDialog(null, "Hello world!");
}
else if( e.getSource() == btnScissor){
}
else if( e.getSource() == btnPaper){
}
else if( e.getSource() == btnNewGame){
}
}
}
package p3;
import java.awt.*;
import javax.swing.*;
public class SSPViewer extends JPanel {
private JLabel lblFirst = new JLabel("First to 3!");
private JLabel lblHuman = new JLabel("Human");
private JLabel lblComputer = new JLabel("Computer");
private JLabel lblHumanChoice = new JLabel();
private JLabel lblComputerChoice = new JLabel();
private JLabel lblHumanPoints = new JLabel("0");
private JLabel lblComputerPoints = new JLabel("0");
private SSPUserInput rock;
private SSPUserInput scissor;
private SSPUserInput paper;
public SSPViewer(SSPUserInput rock, SSPUserInput scissor, SSPUserInput paper) {
this.rock = rock;
this.scissor = scissor;
this.paper = paper;
}
public SSPViewer() {
setLayout(null);
setPreferredSize(new Dimension(400, 200));
lblFirst.setBounds(140, 10, 210, 24);
lblFirst.setFont(new Font("Arial", 2, 24));
lblHuman.setBounds(100, 75, 210, 17);
lblHuman.setFont(new Font("Arial", 2, 17));
lblComputer.setBounds(250, 75, 210, 17);
lblComputer.setFont(new Font("Arial", 2, 17));
lblHumanPoints.setBounds(120, 95, 210, 17);
lblHumanPoints.setFont(new Font("Arial", 2, 17));
lblComputerPoints.setBounds(280, 95, 210, 17);
lblComputerPoints.setFont(new Font("Arial", 2, 17));
lblHumanChoice.setBounds(100, 115, 210, 17);
lblHumanChoice.setFont(new Font("Arial", 2, 17));
// lblHuman.setText(rock.getRock());
lblComputerChoice.setBounds(260, 115, 210, 17);
lblComputerChoice.setFont(new Font("Arial", 2, 17));
add(lblFirst);
add(lblHuman);
add(lblComputer);
add(lblHumanPoints);
add(lblComputerPoints);
add(lblHumanChoice);
add(lblComputerChoice);
}
public JLabel getLblHumanChoice() {
return lblHumanChoice;
}
}
package p3;
import javax.swing.*;
public class SSPApp {
public static void main( String[] args ) {
SSPPlayer player = new SSPPlayer();
SSPViewer viewer = new SSPViewer();
SSPController controller = new SSPController();
SSPUserInput userInput = new SSPUserInput();
JFrame frame1 = new JFrame( "SSPViewer" );
frame1.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame1.add( viewer );
frame1.pack();
frame1.setVisible( true );
JFrame frame2 = new JFrame( "SSPUserInput" );
frame2.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame2.add( userInput );
frame2.pack();
frame2.setVisible( true );
}
}
Basically you need to hold a reference to the 'view' on the 'userInput'. And you already have it.
public ExampleFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new GridLayout(2, 1));
setContentPane(contentPane);
// create a view
SSPViewer sspViewer = new SSPViewer();
contentPane.add(sspViewer);
// pass a reference to the userInput
contentPane.add(new SSPUserInput(sspViewer));
}
on the viewer class, you need to add a method to access the local private components, for example im going to change a text of JLabel :
public class SSPViewer extends JPanel {
// code ...
// setter. lblHuman is a reference here in that class
// to the view class, so all public members are available
public void setTextExample (String s){
this.lblHuman.setText(s);
}
}
Then on the userInput class, you can 'refer' to that property on the other JPanel :
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnRock) {
JOptionPane.showMessageDialog(null, "Hello world!");
// accessible now
lblHumanChoice.setTextExample("changed from other panel");
} else ...
}
NOTE: I edited the answer.
I've added the codes here. This way when you press ROCK button(for example), it shows its name in the other window. I used JFrame and called the SSPViewer class inside of SSPUserInput class. NOTE: I think you want to call some other classes inside SSPApp(that's why I wrote it) but even if you run SSPUserInput, it still pops up two windows.Now they are somethings like that: enter image description here and like this
SSPUserInput class
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.AbstractButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SSPUserInput extends JFrame {
private JPanel contentPane;
JButton PaperButton;
JButton ScissorButton;
JButton rockButton;
SSPViewer viewer = new SSPViewer();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SSPUserInput frame = new SSPUserInput();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public SSPUserInput() {
viewer.frame.setVisible(true); //this code is important
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.CENTER);
GridBagLayout gbl_panel = new GridBagLayout();
gbl_panel.columnWidths = new int[]{0, 0, 0, 0, 0, 0, 0};
gbl_panel.rowHeights = new int[]{0, 0, 93, 9, 19, 0, 0, 0};
gbl_panel.columnWeights = new double[]{0.0, 1.0, 0.0, 1.0, 0.0, 1.0, Double.MIN_VALUE};
gbl_panel.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
panel.setLayout(gbl_panel);
rockButton = new JButton("ROCK");
GridBagConstraints gbc_rockButton = new GridBagConstraints();
gbc_rockButton.fill = GridBagConstraints.HORIZONTAL;
gbc_rockButton.insets = new Insets(0, 0, 5, 5);
gbc_rockButton.gridx = 1;
gbc_rockButton.gridy = 3;
panel.add(rockButton, gbc_rockButton);
ScissorButton = new JButton("Scissor");
GridBagConstraints gbc_ScissorButton = new GridBagConstraints();
gbc_ScissorButton.fill = GridBagConstraints.BOTH;
gbc_ScissorButton.insets = new Insets(0, 0, 5, 5);
gbc_ScissorButton.gridx = 3;
gbc_ScissorButton.gridy = 3;
panel.add(ScissorButton, gbc_ScissorButton);
PaperButton = new JButton("PAPER");
GridBagConstraints gbc_PaperButton = new GridBagConstraints();
gbc_PaperButton.fill = GridBagConstraints.HORIZONTAL;
gbc_PaperButton.insets = new Insets(0, 0, 5, 0);
gbc_PaperButton.gridx = 5;
gbc_PaperButton.gridy = 3;
panel.add(PaperButton, gbc_PaperButton);
JButton btnNewGame = new JButton("New Game");
GridBagConstraints gbc_btnNewGame = new GridBagConstraints();
gbc_btnNewGame.fill = GridBagConstraints.HORIZONTAL;
gbc_btnNewGame.insets = new Insets(0, 0, 5, 5);
gbc_btnNewGame.gridx = 3;
gbc_btnNewGame.gridy = 5;
panel.add(btnNewGame, gbc_btnNewGame);
JButton btnQuit = new JButton("Quit");
GridBagConstraints gbc_btnQuit = new GridBagConstraints();
gbc_btnQuit.fill = GridBagConstraints.HORIZONTAL;
gbc_btnQuit.insets = new Insets(0, 0, 0, 5);
gbc_btnQuit.gridx = 3;
gbc_btnQuit.gridy = 6;
panel.add(btnQuit, gbc_btnQuit);
MyListener2 listener = new MyListener2();
rockButton.addActionListener(listener);
ScissorButton.addActionListener(listener);
PaperButton.addActionListener(listener);
}
private class MyListener2 implements ActionListener {
public void mousePressed(ActionEvent e) {
//System.out.println(((JButton) e.getSource()).getText());
//String name = ((JButton) e.getSource()).getText();
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
System.out.println(((JButton) arg0.getSource()).getText());
String name = ((JButton) arg0.getSource()).getText();
viewer.humanWin.setText(name);
}
}
}
SSPViewer class
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.GridBagLayout;
import javax.swing.JLabel;
import java.awt.GridBagConstraints;
import java.awt.Insets;
public class SSPViewer {
JFrame frame;
JLabel humanWin;
JLabel computerWin;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SSPViewer window = new SSPViewer();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public SSPViewer() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.getContentPane().add(panel, BorderLayout.CENTER);
GridBagLayout gbl_panel = new GridBagLayout();
gbl_panel.columnWidths = new int[]{0, 0, 4, 0, 0, 0, 0, 0, 0};
gbl_panel.rowHeights = new int[]{0, 0, 0, 0, 0, 0, 0, 0};
gbl_panel.columnWeights = new double[]{0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, Double.MIN_VALUE};
gbl_panel.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
panel.setLayout(gbl_panel);
JLabel lblFirstTo = new JLabel("First to 3!");
GridBagConstraints gbc_lblFirstTo = new GridBagConstraints();
gbc_lblFirstTo.insets = new Insets(0, 0, 5, 5);
gbc_lblFirstTo.gridx = 5;
gbc_lblFirstTo.gridy = 2;
panel.add(lblFirstTo, gbc_lblFirstTo);
JLabel lblHuman = new JLabel("Human");
GridBagConstraints gbc_lblHuman = new GridBagConstraints();
gbc_lblHuman.gridwidth = 3;
gbc_lblHuman.insets = new Insets(0, 0, 5, 5);
gbc_lblHuman.gridx = 2;
gbc_lblHuman.gridy = 4;
panel.add(lblHuman, gbc_lblHuman);
JLabel lblComputer = new JLabel("Computer");
GridBagConstraints gbc_lblComputer = new GridBagConstraints();
gbc_lblComputer.insets = new Insets(0, 0, 5, 0);
gbc_lblComputer.gridx = 7;
gbc_lblComputer.gridy = 4;
panel.add(lblComputer, gbc_lblComputer);
humanWin = new JLabel("");
GridBagConstraints gbc_humanWin = new GridBagConstraints();
gbc_humanWin.insets = new Insets(0, 0, 0, 5);
gbc_humanWin.gridx = 3;
gbc_humanWin.gridy = 6;
panel.add(humanWin, gbc_humanWin);
computerWin = new JLabel("");
GridBagConstraints gbc_computerWin = new GridBagConstraints();
gbc_computerWin.gridx = 7;
gbc_computerWin.gridy = 6;
panel.add(computerWin, gbc_computerWin);
}
}
SSPApp class
public class SSPApp {
SSPUserInput s = new SSPUserInput();
}
I am trying to get JOGL working correctly with Swing. I have used WindowBuilder and hacked it together with a few JOGL examples. It works fine, but there is a problem. When I start the program, it starts with blank window. Even the Swing components do not come up:
Everything starts to work when I move mouse cursor over the window content or another event forces it to redraw - like change of focus, window move, re-size etc.
Here is my code:
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.media.opengl.GL;
import javax.media.opengl.GL2;
import javax.media.opengl.GLAutoDrawable;
import javax.media.opengl.GLCapabilities;
import javax.media.opengl.GLEventListener;
import javax.media.opengl.GLProfile;
import javax.media.opengl.awt.GLJPanel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import com.jogamp.opengl.util.Animator;
public class OpenGLTestMin {
private JFrame frame;
private Animator animator;
private double theta = 0;
private double s = 0;
private double c = 0;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
OpenGLTestMin window = new OpenGLTestMin();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public OpenGLTestMin() {
frame = new JFrame();
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowevent) {
animator.stop();
frame.dispose();
System.exit(0);
}
});
// frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(640, 480);
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[]{0, 0};
gridBagLayout.rowHeights = new int[]{0, 0};
gridBagLayout.columnWeights = new double[]{1.0, Double.MIN_VALUE};
gridBagLayout.rowWeights = new double[]{1.0, Double.MIN_VALUE};
frame.getContentPane().setLayout(gridBagLayout);
JPanel panelMain = new JPanel();
panelMain.setBorder(new EmptyBorder(5, 5, 5, 5));
GridBagConstraints gbc_panelMain = new GridBagConstraints();
gbc_panelMain.fill = GridBagConstraints.BOTH;
gbc_panelMain.gridx = 0;
gbc_panelMain.gridy = 0;
frame.getContentPane().add(panelMain, gbc_panelMain);
GridBagLayout gbl_panelMain = new GridBagLayout();
gbl_panelMain.columnWidths = new int[]{0, 0, 0};
gbl_panelMain.rowHeights = new int[]{0, 0};
gbl_panelMain.columnWeights = new double[]{1.0, 0.0, Double.MIN_VALUE};
gbl_panelMain.rowWeights = new double[]{1.0, Double.MIN_VALUE};
panelMain.setLayout(gbl_panelMain);
JPanel panelButton = new JPanel();
GridBagConstraints gbc_panelButton = new GridBagConstraints();
gbc_panelButton.fill = GridBagConstraints.BOTH;
gbc_panelButton.gridx = 1;
gbc_panelButton.gridy = 0;
panelMain.add(panelButton, gbc_panelButton);
GridBagLayout gbl_panelButton = new GridBagLayout();
gbl_panelButton.columnWidths = new int[]{0, 0};
gbl_panelButton.rowHeights = new int[]{0, 0, 0};
gbl_panelButton.columnWeights = new double[]{0.0, Double.MIN_VALUE};
gbl_panelButton.rowWeights = new double[]{0.0, 0.0, Double.MIN_VALUE};
panelButton.setLayout(gbl_panelButton);
JButton btn1 = new JButton("Button 1");
GridBagConstraints gbc_btn1 = new GridBagConstraints();
gbc_btn1.insets = new Insets(0, 0, 5, 0);
gbc_btn1.gridx = 0;
gbc_btn1.gridy = 0;
panelButton.add(btn1, gbc_btn1);
JButton btn2 = new JButton("Button 2");
GridBagConstraints gbc_btn2 = new GridBagConstraints();
gbc_btn2.gridx = 0;
gbc_btn2.gridy = 1;
panelButton.add(btn2, gbc_btn2);
GLProfile glprofile = GLProfile.getDefault();
GLCapabilities glcapabilities = new GLCapabilities(glprofile);
GLJPanel glcanvas = new GLJPanel(glcapabilities);
glcanvas.addGLEventListener(new GLEventListener() {
#Override
public void reshape(GLAutoDrawable glautodrawable, int x, int y, int width, int height) {
}
#Override
public void init(GLAutoDrawable glautodrawable) {
}
#Override
public void dispose(GLAutoDrawable glautodrawable) {
}
#Override
public void display(GLAutoDrawable glautodrawable) {
theta += 0.01;
s = Math.sin(theta);
c = Math.cos(theta);
GL2 gl = glautodrawable.getGL().getGL2();
gl.glClear(GL.GL_COLOR_BUFFER_BIT);
gl.glBegin(GL.GL_TRIANGLES);
gl.glColor3f(1, 0, 0);
gl.glVertex2d(-c, -c);
gl.glColor3f(0, 1, 0);
gl.glVertex2d(0, c);
gl.glColor3f(0, 0, 1);
gl.glVertex2d(s, -s);
gl.glEnd();
}
});
GridBagConstraints gbc_panel = new GridBagConstraints();
gbc_panel.insets = new Insets(0, 0, 0, 5);
gbc_panel.fill = GridBagConstraints.BOTH;
gbc_panel.gridx = 0;
gbc_panel.gridy = 0;
panelMain.add(glcanvas, gbc_panel);
animator = new Animator(glcanvas);
animator.start();
}
}
Any ideas how to fix this? I am on Windows 7.
I have found the solution. GLJPanel should be initialized directly in main method, not in EventQueue. Then it works just fine. Also note that GLCanvas has MUCH better performance than GLJPanel, however sometimes glitches a bit when resizing window.