how to put value in the checkboxes - java

this is my code, I just want to make a receipt that when you check the checkbox theres value in it and it prints the label with the value consecutively
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class GUI extends JFrame implements ActionListener
{
private JLabel label;
private JCheckBox checkbox,checkbox2,checkbox3,checkbox4,checkbox5,
checkbox6,checkbox7,checkbox8,checkbox9,
checkbox10,checkbox11,checkbox12,checkbox13,checkbox14,checkbox15,
checkbox16,checkbox17,checkbox18,checkbox19,checkbox20;
private JButton button;
public GUI()
{
Container pane= getContentPane();
pane.setLayout(new GridLayout(15,1));
JPanel jp= new JPanel();
label= new JLabel("McDonald's");
checkbox = new JCheckBox("Cheese Burger");
checkbox2 = new JCheckBox("Big Mac");
checkbox3 = new JCheckBox("Big n' Tasty");
checkbox4 = new JCheckBox("McSpicy");
checkbox5 = new JCheckBox("Quarter Pounder with Cheese");
checkbox6 = new JCheckBox("Double Cheeseburger");
checkbox7 = new JCheckBox("McChicken Sandwich");
checkbox8 = new JCheckBox("Filet-O-Fish");
checkbox9 = new JCheckBox("Cheeseburger Deluxe");
checkbox10 = new JCheckBox("Burger Mcdo");
checkbox11 = new JCheckBox("Chicken Filet with Drinks");
checkbox12 = new JCheckBox("Spaghetti with Drinks");
checkbox13 = new JCheckBox("Hot Fudge Sundae ");
checkbox14 = new JCheckBox("Caramel Sundae");
checkbox15 = new JCheckBox("Large Mcdo French Fries");
checkbox16 = new JCheckBox("Chicken Nuggets with coke");
checkbox17 = new JCheckBox("Coke Float");
checkbox18 = new JCheckBox("Green Apple Float");
checkbox19 = new JCheckBox("Crispy Chicken with rice");
checkbox20 = new JCheckBox("Oreo Sundae");
button = new JButton("Order Now");
add(label);
pane.add(checkbox);
pane.add(checkbox2);
pane.add(checkbox3);
pane.add(checkbox4);
pane.add(checkbox5);
pane.add(checkbox6);
pane.add(checkbox7);
pane.add(checkbox8);
pane.add(checkbox9);
pane.add(checkbox10);
pane.add(checkbox11);
pane.add(checkbox12);
pane.add(checkbox13);
pane.add(checkbox14);
pane.add(checkbox15);
pane.add(checkbox16);
pane.add(checkbox17);
pane.add(checkbox18);
pane.add(checkbox19);
pane.add(checkbox20);
add(button);
add(jp, BorderLayout.SOUTH);
label.setHorizontalAlignment(JLabel.CENTER);
button.setSize(10,10);
button.addActionListener(this);
setSize(500,550);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
String gulp = e.getActionCommand();
{
if ( gulp.equals("Order Now"))
{
new Receipt();
setVisible(true);
dispose();
}
}
}
public static void main(String[] args)
{
GUI r= new GUI();
}
}
here is my second code, this is the format of the receipt I want to achieve
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class Receipt extends JFrame
{
private JLabel label,label2,label3,label4,label5,
label6,label7,label8,label9,label10;;
public Receipt()
{
Container pane= getContentPane();
pane.setLayout(new GridLayout(13,1));
label= new JLabel("MC DONALD'S");
label2= new JLabel("McDonald's Tandang Sora");
label3= new JLabel("#22 Tandang Sora Corner, Commonwealth Avenue, Quezon City");
label4= new JLabel("Telephone# (02)86236");
label5= new JLabel("MACHINE SERIAL NUMBER: D123HJ01");
label6= new JLabel("Card Issuer: Sharina Tortoles");
label7= new JLabel("Account Number# 337163990");
label8= new JLabel("February 22, 2014 12:45");
label9= new JLabel("Thank You for choosing Mcdonald's");
label10= new JLabel("Please come again");
label.setHorizontalAlignment(JLabel.CENTER);
label2.setHorizontalAlignment(JLabel.CENTER);
label3.setHorizontalAlignment(JLabel.CENTER);
label4.setHorizontalAlignment(JLabel.CENTER);
label5.setHorizontalAlignment(JLabel.CENTER);
label6.setHorizontalAlignment(JLabel.CENTER);
label7.setHorizontalAlignment(JLabel.CENTER);
label8.setHorizontalAlignment(JLabel.CENTER);
label9.setHorizontalAlignment(JLabel.CENTER);
label10.setHorizontalAlignment(JLabel.CENTER);
pane.add(label, BorderLayout.NORTH);
pane.add(label2);
pane.add(label3);
pane.add(label4);
pane.add(label5);
pane.add(label6);
pane.add(label7);
pane.add(label8);
pane.add(label9);
pane.add(label10);
setSize(500,500);
setVisible(true);
}
public static void main(String[] args)
{
Receipt g= new Receipt();
}
}
Hope that it is clear to you what I want to happen with code

I guess EnumSet is what you are looking for:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.List;
import javax.swing.*;
enum Receipt {
CheeseBurger("Cheese Burger"),
BigMac("Big Mac"),
BigNTasty("Big n' Tasty"),
McSpicy("McSpicy"),
QuarterPounderWithCheese("Quarter Pounder with Cheese"),
DoubleCheeseburger("Double Cheeseburger"),
McChickenSandwich("McChicken Sandwich");
//JCheckBox("Filet-O-Fish"),
//JCheckBox("Cheeseburger Deluxe"),
//JCheckBox("Burger Mcdo"),
//JCheckBox("Chicken Filet with Drinks"),
//JCheckBox("Spaghetti with Drinks"),
//JCheckBox("Hot Fudge Sundae "),
//JCheckBox("Caramel Sundae"),
//JCheckBox("Large Mcdo French Fries"),
//JCheckBox("Chicken Nuggets with coke"),
//JCheckBox("Coke Float"),
//JCheckBox("Green Apple Float"),
//JCheckBox("Crispy Chicken with rice"),
//JCheckBox("Oreo Sundae");
private final String str;
private Receipt(String str) {
this.str = str;
}
#Override public String toString() {
return str;
}
}
public class GUI2 {
private JButton button = new JButton(new AbstractAction("Order Now") {
#Override public void actionPerformed(ActionEvent e) {
EnumSet<Receipt> r = EnumSet.noneOf(Receipt.class);
for (ReceiptCheckBox c: list) {
if (c.isSelected()) {
r.add(c.getReceipt());
}
}
JOptionPane.showMessageDialog((JComponent) e.getSource(), r);
}
});
private List<ReceiptCheckBox> list = new ArrayList<>(Receipt.values().length);
public JComponent makeUI() {
JPanel p = new JPanel();
for (Receipt r: Receipt.values()) {
ReceiptCheckBox c = new ReceiptCheckBox(r);
list.add(c);
p.add(c);
}
JPanel panel = new JPanel(new BorderLayout());
panel.add(new JLabel("McDonald's"), BorderLayout.NORTH);
panel.add(button, BorderLayout.SOUTH);
panel.add(p);
return panel;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(new GUI2().makeUI());
f.setSize(320, 240);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
class ReceiptCheckBox extends JCheckBox {
private final Receipt receipt;
public ReceiptCheckBox(Receipt receipt) {
super(receipt.toString());
this.receipt = receipt;
}
public Receipt getReceipt() {
return receipt;
}
}

Related

Java AbstractTableModel: getValueAt does not use updated data

I have a Java application with four card panels. In the first panel, I receive data for the first geographic point, in the second and third -- for the other two points, and in the fourth panel, I have a JTable that displays extracted information about these three points.
The following code can be used to compile the application. On each Card panel, try to click the button next to the JTextfield to add the data.
Package models
Class AppSingleton
public class AppSingleton
{
private static AppSingleton instance = null;
public List<List<String>> flightPlanShared = new ArrayList<List<String>>(){{
add(Arrays.asList(""));
add(Arrays.asList(""));
add(Arrays.asList(""));
}};
private AppSingleton()
{
}
public static AppSingleton getInstance()
{
if(instance == null)
{
instance = new AppSingleton();
}
return instance;
}
}
Class Model_Flightplan
import java.util.ArrayList;
import java.util.List;
import presenters.Presenter;
import views.View_MainFrame;
public class Model_Flightplan
{
AppSingleton appSingleton = AppSingleton.getInstance( );
private Presenter presenter;
private View_MainFrame viewMainFrame;
public Model_Flightplan(View_MainFrame viewMainFrame)
{
this.viewMainFrame = viewMainFrame;
}
public Presenter getPresenter() {
return presenter;
}
public void setPresenter(Presenter presenter) {
this.presenter = presenter;
}
public void addDepartureAirport()
{
List<String> component = new ArrayList<>();
component.add("KLAS");
component.add("KLAS");
component.add("KLAS");
appSingleton.flightPlanShared.set(0, component);
}
public void addDestinationAirport()
{
List<String> component = new ArrayList<>();
component.add("KLAX");
component.add("KLAX");
component.add("KLAX");
appSingleton.flightPlanShared.set( (appSingleton.flightPlanShared.size() - 2), component);
}
public void addAlternateAirport()
{
List<String> component = new ArrayList<>();
component.add("KSEA");
component.add("KSEA");
component.add("KSEA");
appSingleton.flightPlanShared.set( (appSingleton.flightPlanShared.size() - 1), component);
}
}
Class Model_TableWindsAloft
package models;
import java.util.ArrayList;
import java.util.List;
import javax.swing.table.AbstractTableModel;
public class Model_TableWindsAloft extends AbstractTableModel
{
String[] columnNames = {"ICAO","Name","Type"};
private List<List<String>> tableData = new ArrayList<>();
public Model_TableWindsAloft(List<List<String>> tableData)
{
this.tableData = tableData;
System.out.println("CONSTRUCTOR? "+tableData);
}
#Override
public int getRowCount()
{
System.out.println("DATA COUNT? "+tableData.size());
return(tableData.size());
}
#Override
public int getColumnCount() {
return(columnNames.length);
}
#Override
public String getColumnName(int column)
{
return columnNames[column] ;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex)
{
System.out.println("WHAT IS DATA 1? "+tableData);
List<String> data = tableData.get(rowIndex);
System.out.println("WHAT IS DATA 2? "+data);
if(data.size()>=3)
{
switch(columnIndex)
{
case 0:
return data.get(0);
case 1:
return data.get(1);
case 2:
return data.get(2);
default:
return null;
}
}
else
{
return null;
}
}
}
Package presenters
Class Presenter
package presenters;
import java.awt.CardLayout;
import models.Model_Flightplan;
import views.View_MainFrame;
public class Presenter
{
private final View_MainFrame viewMainFrame;
private final Model_Flightplan model;
public Presenter(View_MainFrame viewMainFrame, Model_Flightplan model)
{
this.viewMainFrame = viewMainFrame;
this.model = model;
}
public void displayTabDep()
{
CardLayout card = (CardLayout)viewMainFrame.getPanelContext().getLayout();
card.show(viewMainFrame.getPanelContext(), "cardDep");
viewMainFrame.addButtonsFlightplan();
viewMainFrame.btnPnlDeparture.setEnabled(false);
}
public void displayTabDest()
{
CardLayout card = (CardLayout)viewMainFrame.getPanelContext().getLayout();
card.show(viewMainFrame.getPanelContext(), "cardDest");
viewMainFrame.addButtonsFlightplan();
viewMainFrame.btnPnlDestination.setEnabled(false);
}
public void displayTabAlt()
{
CardLayout card = (CardLayout)viewMainFrame.getPanelContext().getLayout();
card.show(viewMainFrame.getPanelContext(), "cardAlt");
viewMainFrame.addButtonsFlightplan();
viewMainFrame.btnPnlAlternate.setEnabled(false);
}
public void displayTabWindsAloft()
{
CardLayout card = (CardLayout)viewMainFrame.getPanelContext().getLayout();
card.show(viewMainFrame.getPanelContext(), "cardWindsAloft");
viewMainFrame.addButtonsFlightplan();
viewMainFrame.btnPnlWindsAloft.setEnabled(false);
viewMainFrame.createPanelWindsAloft();
}
public void addDeparture()
{
model.addDepartureAirport();
}
public void addDestination()
{
model.addDestinationAirport();
}
public void addAlternate()
{
model.addAlternateAirport();
}
}
Package views
Class View_MainFrame
package views;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRootPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import models.AppSingleton;
import presenters.Presenter;
public class View_MainFrame
{
AppSingleton appSingleton = AppSingleton.getInstance( );
private Presenter presenter;
private JPanel panelContext;
private JFrame frame;
public JPanel pnlDep;
public JPanel pnlDest;
public JPanel pnlAlt;
public JPanel pnlWindsAloft;
public JPanel panelButtons;
public JButton btnFlightplan;
public JPanel panelButtonsAdd;
public JButton btnFlightplanDummy;
public JPanel pnlDepAirport;
private JButton btnAddDep;
private javax.swing.JPanel pnlDestAirport;
public JButton btnAddDest;
private javax.swing.JPanel pnlAltAirport;
public JButton btnAddAlt;
private javax.swing.JPanel pnlWindsAloftInfo;
private javax.swing.JPanel pnlWindsAloftTable;
public JButton btnPnlDeparture;
public JButton btnPnlDestination;
public JButton btnPnlAlternate;
public JButton btnPnlWindsAloft;
public View_MainFrame()
{
createUI();
}
private void createUI()
{
JFrame.setDefaultLookAndFeelDecorated(true);
frame = new JFrame("iGoDispatch IXEG Boeing-733");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new javax.swing.BoxLayout(frame.getContentPane(), javax.swing.BoxLayout.Y_AXIS));
Dimension frameSize = new Dimension(1050,700);
Dimension frameSizeMin = new Dimension(500,200);
frame.setPreferredSize(frameSize);
frame.setMinimumSize(frameSizeMin);
createPanelButtons();
createPanelButtonsAdd();
createPanelDeparture();
createPanelDestination();
createPanelAlternate();
pnlWindsAloft = new JPanel();
pnlWindsAloft.setLayout(new java.awt.BorderLayout());
createPanelWindsAloft();
setPanelContext(new JPanel());
getPanelContext().setLayout(new java.awt.CardLayout());
frame.getContentPane().add(getPanelContext(), java.awt.BorderLayout.SOUTH);
getPanelContext().add(pnlDep, "cardDep");
getPanelContext().add(pnlDest, "cardDest");
getPanelContext().add(pnlAlt, "cardAlt");
getPanelContext().add(pnlWindsAloft, "cardWindsAloft");
frame.pack();
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
public JPanel getPanelContext() {
return panelContext;
}
public void setPanelContext(JPanel panelContext) {
this.panelContext = panelContext;
}
private void createPanelButtons()
{
panelButtons = new JPanel();
panelButtons.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
panelButtons.setLayout(new java.awt.GridLayout(1, 0));
Dimension panelButtonsMinSize = new Dimension(1050,60);
panelButtons.setMinimumSize(panelButtonsMinSize);
btnFlightplan = new JButton();
btnFlightplan.setFont(new java.awt.Font("Lucida Grande", 1, 13)); // NOI18N
btnFlightplan.setText("Flightplan");
btnFlightplan.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
btnFlightplan.setIconTextGap(5);
btnFlightplan.setMaximumSize(new java.awt.Dimension(70, 70));
btnFlightplan.setMinimumSize(new java.awt.Dimension(70, 70));
btnFlightplan.setPreferredSize(new java.awt.Dimension(70, 70));
btnFlightplan.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
btnFlightplan.addActionListener((java.awt.event.ActionEvent evt) ->
{
getPresenter().displayTabDep();
});
panelButtons.add(btnFlightplan);
frame.getContentPane().add(panelButtons, java.awt.BorderLayout.NORTH);
}
private void createPanelButtonsAdd()
{
panelButtonsAdd = new JPanel();
panelButtonsAdd.setBorder(javax.swing.BorderFactory.createEtchedBorder());
frame.getContentPane().add(panelButtonsAdd, java.awt.BorderLayout.CENTER);
panelButtonsAdd.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));
// Dummy button
btnFlightplanDummy = new JButton();
btnFlightplanDummy.setAlignmentY(0.0F);
btnFlightplanDummy.setEnabled(false);
btnFlightplanDummy.setVisible(false);
btnFlightplanDummy.setMaximumSize(new java.awt.Dimension(50, 50));
btnFlightplanDummy.setMinimumSize(new java.awt.Dimension(50, 50));
btnFlightplanDummy.setPreferredSize(new java.awt.Dimension(50, 50));
panelButtonsAdd.add(btnFlightplanDummy);
addButtonsFlightplan();
}
public void addButtonsFlightplan()
{
removeButtons();
Dimension buttonDim = new Dimension(50, 50);
Font buttonFont = new Font("Helvetica", Font.PLAIN, 10);
btnPnlDeparture = new JButton("DEP");
btnPnlDeparture.setPreferredSize(buttonDim);
btnPnlDeparture.setFont(buttonFont);
btnPnlDeparture.setVisible(true);
btnPnlDeparture.addActionListener((ActionEvent e) ->
{
getPresenter().displayTabDep();
});
panelButtonsAdd.add(btnPnlDeparture);
btnPnlDestination = new JButton("ARR");
btnPnlDestination.setPreferredSize(buttonDim);
btnPnlDestination.setFont(buttonFont);
btnPnlDestination.setVisible(true);
btnPnlDestination.addActionListener((ActionEvent e) ->
{
getPresenter().displayTabDest();
});
panelButtonsAdd.add(btnPnlDestination);
btnPnlAlternate = new JButton("ALT");
btnPnlAlternate.setPreferredSize(buttonDim);
btnPnlAlternate.setFont(buttonFont);
btnPnlAlternate.setVisible(true);
btnPnlAlternate.addActionListener((ActionEvent e) ->
{
getPresenter().displayTabAlt();
});
panelButtonsAdd.add(btnPnlAlternate);
btnPnlWindsAloft = new JButton("WINDS");
btnPnlWindsAloft.setPreferredSize(buttonDim);
btnPnlWindsAloft.setFont(buttonFont);
btnPnlWindsAloft.setVisible(true);
btnPnlWindsAloft.addActionListener((ActionEvent e) ->
{
getPresenter().displayTabWindsAloft();
});
panelButtonsAdd.add(btnPnlWindsAloft);
panelButtonsAdd.revalidate();
panelButtonsAdd.repaint();
}
private void removeButtons()
{
panelButtonsAdd.removeAll();
panelButtonsAdd.revalidate();
panelButtonsAdd.repaint();
}
private void createPanelDeparture()
{
java.awt.GridBagConstraints gridBagConstraints;
pnlDep = new JPanel();
pnlDep.setLayout(new java.awt.BorderLayout());
pnlDepAirport = new JPanel();
pnlDepAirport.setLayout(new java.awt.GridBagLayout());
btnAddDep = new JButton();
btnAddDep.setText("ADD");
btnAddDep.setMaximumSize(new java.awt.Dimension(35, 35));
btnAddDep.setMinimumSize(new java.awt.Dimension(35, 35));
btnAddDep.setPreferredSize(new java.awt.Dimension(35, 35));
btnAddDep.addActionListener((java.awt.event.ActionEvent evt) ->
{
JFrame f = new JFrame();
JDialog modalDialog = new JDialog(f, "Busy", Dialog.ModalityType.MODELESS);
modalDialog.setSize(200, 100);
modalDialog.setLocationRelativeTo(f);
modalDialog.setUndecorated(true);
// Remove menu buttons
modalDialog.getRootPane().setWindowDecorationStyle(JRootPane.NONE);
modalDialog.getContentPane().setBackground( Color.WHITE );
// Add rotating activity indicator
ImageIcon loading = new ImageIcon("src/images/activityIndicator.gif");
modalDialog.add(new JLabel("Please wait... ", loading, JLabel.CENTER));
// Set activity indicator visible
modalDialog.setVisible(true);
new Thread(() ->
{
getPresenter().addDeparture();
SwingUtilities.invokeLater(() ->
{
modalDialog.setVisible(false);
modalDialog.dispose();
});
}).start();
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(5, 15, 5, 5);
pnlDepAirport.add(btnAddDep, gridBagConstraints);
pnlDep.add(pnlDepAirport);
}
private void createPanelDestination()
{
java.awt.GridBagConstraints gridBagConstraints;
pnlDest = new JPanel();
pnlDest.setLayout(new java.awt.BorderLayout());
pnlDestAirport = new javax.swing.JPanel();
pnlDestAirport.setLayout(new java.awt.GridBagLayout());
btnAddDest = new javax.swing.JButton();
btnAddDest.setText("jButton1");
btnAddDest.setMaximumSize(new java.awt.Dimension(35, 35));
btnAddDest.setMinimumSize(new java.awt.Dimension(35, 35));
btnAddDest.setPreferredSize(new java.awt.Dimension(35, 35));
btnAddDest.addActionListener((java.awt.event.ActionEvent evt) ->
{
JFrame f = new JFrame();
JDialog modalDialog = new JDialog(f, "Busy", Dialog.ModalityType.MODELESS);
modalDialog.setSize(200, 100);
modalDialog.setLocationRelativeTo(f);
modalDialog.setUndecorated(true);
// Remove menu buttons
modalDialog.getRootPane().setWindowDecorationStyle(JRootPane.NONE);
modalDialog.getContentPane().setBackground( Color.WHITE );
// Add rotating activity indicator
ImageIcon loading = new ImageIcon("src/images/activityIndicator.gif");
modalDialog.add(new JLabel("Please wait... ", loading, JLabel.CENTER));
// Set activity indicator visible
modalDialog.setVisible(true);
new Thread(() ->
{
getPresenter().addDestination();
SwingUtilities.invokeLater(() ->
{
//displayValues();
modalDialog.setVisible(false);
modalDialog.dispose();
});
}).start();
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(5, 15, 5, 5);
pnlDestAirport.add(btnAddDest, gridBagConstraints);
pnlDest.add(pnlDestAirport);
}
private void createPanelAlternate()
{
java.awt.GridBagConstraints gridBagConstraints;
pnlAlt = new JPanel();
pnlAlt.setLayout(new java.awt.BorderLayout());
pnlAltAirport = new JPanel();
pnlAltAirport.setLayout(new java.awt.GridBagLayout());
btnAddAlt = new JButton();
btnAddAlt.setText("ADD");
btnAddAlt.setMaximumSize(new java.awt.Dimension(35, 35));
btnAddAlt.setMinimumSize(new java.awt.Dimension(35, 35));
btnAddAlt.setPreferredSize(new java.awt.Dimension(35, 35));
btnAddAlt.addActionListener((java.awt.event.ActionEvent evt) ->
{
JFrame f = new JFrame();
JDialog modalDialog = new JDialog(f, "Busy", Dialog.ModalityType.MODELESS);
modalDialog.setSize(200, 100);
modalDialog.setLocationRelativeTo(f);
modalDialog.setUndecorated(true);
// Remove menu buttons
modalDialog.getRootPane().setWindowDecorationStyle(JRootPane.NONE);
modalDialog.getContentPane().setBackground( Color.WHITE );
// Add rotating activity indicator
ImageIcon loading = new ImageIcon("src/images/activityIndicator.gif");
modalDialog.add(new JLabel("Please wait... ", loading, JLabel.CENTER));
// Set activity indicator visible
modalDialog.setVisible(true);
new Thread(() ->
{
getPresenter().addAlternate();
SwingUtilities.invokeLater(() ->
{
modalDialog.setVisible(false);
modalDialog.dispose();
});
}).start();
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(5, 15, 5, 5);
pnlAltAirport.add(btnAddAlt, gridBagConstraints);
pnlAlt.add(pnlAltAirport);
}
public void createPanelWindsAloft()
{
pnlWindsAloftInfo = new javax.swing.JPanel();
pnlWindsAloftInfo.setLayout(new java.awt.GridLayout(1, 0));
pnlWindsAloftTable = new javax.swing.JPanel();
pnlWindsAloftTable.setLayout(new BorderLayout());
javax.swing.JTable tblWindsAloft = new javax.swing.JTable(new Model_TableWindsAloft(createDataForWindsTable()));
JScrollPane scrollWindsAloft = new JScrollPane(tblWindsAloft,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
tblWindsAloft.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
tblWindsAloft.setFillsViewportHeight(true);
pnlWindsAloftTable.add(scrollWindsAloft, BorderLayout.CENTER);
pnlWindsAloftInfo.add(pnlWindsAloftTable);
pnlWindsAloft.add(pnlWindsAloftInfo, java.awt.BorderLayout.CENTER);
}
public List<List<String>> createDataForWindsTable()
{
List<List<String>> finalResult = new ArrayList<>();
System.out.println("SIZE: "+finalResult.size());
for (int i=0; i<appSingleton.flightPlanShared.size(); i++)
{
String icao;
String name;
String type;
if(appSingleton.flightPlanShared.get(i).size()>2)
{
icao = appSingleton.flightPlanShared.get(i).get(2);
name = appSingleton.flightPlanShared.get(i).get(1);
type = appSingleton.flightPlanShared.get(i).get(0);
}
else
{
icao = "";
name = "";
type = "";
}
List<String> components = new ArrayList<>();
components.add(icao);
components.add(name);
components.add(type);
System.out.println("COMPONENTS: "+components);
finalResult.add(components);
}
/* THIS WORKS!
String a1 = "LAS VEGAS/MC CARRAN ";
String a2 = "KLAS";
String a3 = "PORTDEP";
List<String> a = new ArrayList<>();
a.add(a1);
a.add(a2);
a.add(a3);
String b1 = "LOS ANGELES INTL";
String b2 = "KLAX";
String b3 = "PORTDEST";
List<String> b = new ArrayList<>();
b.add(b1);
b.add(b2);
b.add(b3);
String c1 = "SEATTLE-TACOMA INTL";
String c2 = "KSEA";
String c3 = "PORTALT";
List<String> c = new ArrayList<>();
c.add(c1);
c.add(c2);
c.add(c3);
finalResult.add(a);
finalResult.add(b);
finalResult.add(c);
*/
System.out.println("DATA CREATED: "+finalResult);
return finalResult;
}
public Presenter getPresenter() {
return presenter;
}
public void setPresenter(Presenter presenter) {
this.presenter = presenter;
}
}
Main
package testjtable;
import javax.swing.SwingUtilities;
import models.Model_Flightplan;
import presenters.Presenter;
import views.View_MainFrame;
public class TestJTable {
public static void main(String[] args)
{
SwingUtilities.invokeLater(() ->
{
View_MainFrame viewMainFrame = new View_MainFrame();
viewMainFrame.setPresenter(new Presenter(viewMainFrame, new Model_Flightplan(viewMainFrame)));
});
}
}
Data does not appear inside the table unless (!!!) I click outside of the application.
EDIT:
I solved the problem by updating the model using the setValueAt() method:
#Override
public void setValueAt(Object value, int row, int col)
{
setTableData(appSingleton.flightPlanShared);
fireTableCellUpdated(row, col);
}
You appear to be creating a new JTable and a new JPanel that holds it, with each press of the create winds aloft button.
Here is your btnPnlWindsAloft JButton's ActionListener:
btnPnlWindsAloft.addActionListener((ActionEvent e) -> {
getPresenter().displayTabWindsAloft();
});
Notice that it calls getPresenter().displayTabWindsAloft(); which is:
public void displayTabWindsAloft() {
CardLayout card = (CardLayout) viewMainFrame.getPanelContext().getLayout();
card.show(viewMainFrame.getPanelContext(), "cardWindsAloft");
viewMainFrame.addButtonsFlightplan();
viewMainFrame.btnPnlWindsAloft.setEnabled(false);
viewMainFrame.createPanelWindsAloft();
}
And notice that this method calls viewMainFrame.createPanelWindsAloft(); which is:
public void createPanelWindsAloft() {
pnlWindsAloftInfo = new javax.swing.JPanel();
pnlWindsAloftInfo.setLayout(new java.awt.GridLayout(1, 0));
pnlWindsAloftTable = new javax.swing.JPanel();
pnlWindsAloftTable.setLayout(new BorderLayout());
javax.swing.JTable tblWindsAloft = new javax.swing.JTable(
new Model_TableWindsAloft(createDataForWindsTable()));
JScrollPane scrollWindsAloft = new JScrollPane(tblWindsAloft,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
tblWindsAloft.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
tblWindsAloft.setFillsViewportHeight(true);
pnlWindsAloftTable.add(scrollWindsAloft, BorderLayout.CENTER);
pnlWindsAloftInfo.add(pnlWindsAloftTable);
pnlWindsAloft.add(pnlWindsAloftInfo, java.awt.BorderLayout.CENTER);
}
... and every time this method is called, it creates a new pnlWindsAloftInfo JPanel, a new pnlWindsAloftTable JPanel, a new tblWindsAloft JTable which it fills with a new table model, via a call to createDataForWindsTable(). Again, why are you re-creating these components and models unnecessarily?
Don't do this -- create your key components just once, and then while the program is running, change the state of the JTable's model as well as the state of the visibility of the "card" JPanel that holds the JTable, but don't keep re-creating JTables and models, some of which hold data, and some that don't.
Also the complexity of your program is needlessly huge, and this is likely preventing you from seeing the problem -- refactor and simply everything.
Side issue: you are setting sizes of key components almost guaranteeing that they will not display appropriately on most systems (such as my system where the button text is displaying as ...). You'll want to avoid this as well.
My current MCVE of your code:
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRootPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.AbstractTableModel;
public class TestJTable {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
View_MainFrame viewMainFrame = new View_MainFrame();
viewMainFrame.setPresenter(
new Presenter(viewMainFrame, new Model_Flightplan(viewMainFrame)));
});
}
}
class View_MainFrame {
AppSingleton appSingleton = AppSingleton.getInstance();
private Presenter presenter;
private JPanel panelContext;
private JFrame frame;
public JPanel pnlDep;
public JPanel pnlDest;
public JPanel pnlAlt;
public JPanel pnlWindsAloft;
public JPanel panelButtons;
public JButton btnFlightplan;
public JPanel panelButtonsAdd;
public JButton btnFlightplanDummy;
public JPanel pnlDepAirport;
private JButton btnAddDep;
private javax.swing.JPanel pnlDestAirport;
public JButton btnAddDest;
private javax.swing.JPanel pnlAltAirport;
public JButton btnAddAlt;
private javax.swing.JPanel pnlWindsAloftInfo;
private javax.swing.JPanel pnlWindsAloftTable;
public JButton btnPnlDeparture;
public JButton btnPnlDestination;
public JButton btnPnlAlternate;
public JButton btnPnlWindsAloft;
public View_MainFrame() {
createUI();
}
private void createUI() {
JFrame.setDefaultLookAndFeelDecorated(true);
frame = new JFrame("iGoDispatch IXEG Boeing-733");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(
new javax.swing.BoxLayout(frame.getContentPane(), javax.swing.BoxLayout.Y_AXIS));
Dimension frameSize = new Dimension(1050, 700);
Dimension frameSizeMin = new Dimension(500, 200);
frame.setPreferredSize(frameSize);
frame.setMinimumSize(frameSizeMin);
createPanelButtons();
createPanelButtonsAdd();
createPanelDeparture();
createPanelDestination();
createPanelAlternate();
pnlWindsAloft = new JPanel();
pnlWindsAloft.setLayout(new java.awt.BorderLayout());
createPanelWindsAloft();
setPanelContext(new JPanel());
getPanelContext().setLayout(new java.awt.CardLayout());
frame.getContentPane().add(getPanelContext(), java.awt.BorderLayout.SOUTH);
getPanelContext().add(pnlDep, "cardDep");
getPanelContext().add(pnlDest, "cardDest");
getPanelContext().add(pnlAlt, "cardAlt");
getPanelContext().add(pnlWindsAloft, "cardWindsAloft");
frame.pack();
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
public JPanel getPanelContext() {
return panelContext;
}
public void setPanelContext(JPanel panelContext) {
this.panelContext = panelContext;
}
private void createPanelButtons() {
panelButtons = new JPanel();
panelButtons.setBorder(
new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
panelButtons.setLayout(new java.awt.GridLayout(1, 0));
Dimension panelButtonsMinSize = new Dimension(1050, 60);
panelButtons.setMinimumSize(panelButtonsMinSize);
btnFlightplan = new JButton();
btnFlightplan.setFont(new java.awt.Font("Lucida Grande", 1, 13));
btnFlightplan.setText("Flightplan");
btnFlightplan.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
btnFlightplan.setIconTextGap(5);
btnFlightplan.setMaximumSize(new java.awt.Dimension(90, 70));
btnFlightplan.setMinimumSize(new java.awt.Dimension(90, 70));
btnFlightplan.setPreferredSize(new java.awt.Dimension(90, 70));
btnFlightplan.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
btnFlightplan.addActionListener((java.awt.event.ActionEvent evt) -> {
getPresenter().displayTabDep();
});
panelButtons.add(btnFlightplan);
frame.getContentPane().add(panelButtons, java.awt.BorderLayout.NORTH);
}
private void createPanelButtonsAdd() {
panelButtonsAdd = new JPanel();
panelButtonsAdd.setBorder(javax.swing.BorderFactory.createEtchedBorder());
frame.getContentPane().add(panelButtonsAdd, java.awt.BorderLayout.CENTER);
panelButtonsAdd.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));
btnFlightplanDummy = new JButton();
btnFlightplanDummy.setAlignmentY(0.0F);
btnFlightplanDummy.setEnabled(false);
btnFlightplanDummy.setVisible(false);
btnFlightplanDummy.setMaximumSize(new java.awt.Dimension(50, 50));
btnFlightplanDummy.setMinimumSize(new java.awt.Dimension(50, 50));
btnFlightplanDummy.setPreferredSize(new java.awt.Dimension(50, 50));
panelButtonsAdd.add(btnFlightplanDummy);
addButtonsFlightplan();
}
public void addButtonsFlightplan() {
removeButtons();
Dimension buttonDim = new Dimension(150, 50);
Font buttonFont = new Font("Helvetica", Font.PLAIN, 10);
btnPnlDeparture = new JButton("DEP");
btnPnlDeparture.setPreferredSize(buttonDim);
btnPnlDeparture.setFont(buttonFont);
btnPnlDeparture.setVisible(true);
btnPnlDeparture.addActionListener((ActionEvent e) -> {
getPresenter().displayTabDep();
});
panelButtonsAdd.add(btnPnlDeparture);
btnPnlDestination = new JButton("ARR");
btnPnlDestination.setPreferredSize(buttonDim);
btnPnlDestination.setFont(buttonFont);
btnPnlDestination.setVisible(true);
btnPnlDestination.addActionListener((ActionEvent e) -> {
getPresenter().displayTabDest();
});
panelButtonsAdd.add(btnPnlDestination);
btnPnlAlternate = new JButton("ALT");
btnPnlAlternate.setPreferredSize(buttonDim);
btnPnlAlternate.setFont(buttonFont);
btnPnlAlternate.setVisible(true);
btnPnlAlternate.addActionListener((ActionEvent e) -> {
getPresenter().displayTabAlt();
});
panelButtonsAdd.add(btnPnlAlternate);
btnPnlWindsAloft = new JButton("WINDS");
btnPnlWindsAloft.setPreferredSize(buttonDim);
btnPnlWindsAloft.setFont(buttonFont);
btnPnlWindsAloft.setVisible(true);
btnPnlWindsAloft.addActionListener((ActionEvent e) -> {
getPresenter().displayTabWindsAloft();
});
panelButtonsAdd.add(btnPnlWindsAloft);
panelButtonsAdd.revalidate();
panelButtonsAdd.repaint();
}
private void removeButtons() {
panelButtonsAdd.removeAll();
panelButtonsAdd.revalidate();
panelButtonsAdd.repaint();
}
private void createPanelDeparture() {
java.awt.GridBagConstraints gridBagConstraints;
pnlDep = new JPanel();
pnlDep.setLayout(new java.awt.BorderLayout());
pnlDepAirport = new JPanel();
pnlDepAirport.setLayout(new java.awt.GridBagLayout());
btnAddDep = new JButton();
btnAddDep.setText("ADD");
btnAddDep.setMaximumSize(new java.awt.Dimension(75, 35));
btnAddDep.setMinimumSize(new java.awt.Dimension(75, 35));
btnAddDep.setPreferredSize(new java.awt.Dimension(75, 35));
btnAddDep.addActionListener((java.awt.event.ActionEvent evt) -> {
JFrame f = new JFrame();
JDialog modalDialog = new JDialog(f, "Busy", Dialog.ModalityType.MODELESS);
modalDialog.setSize(200, 100);
modalDialog.setLocationRelativeTo(f);
modalDialog.setUndecorated(true);
modalDialog.getRootPane().setWindowDecorationStyle(JRootPane.NONE);
modalDialog.getContentPane().setBackground(Color.WHITE);
modalDialog.add(new JLabel("Please wait... ", JLabel.CENTER));
modalDialog.setVisible(true);
new Thread(() -> {
getPresenter().addDeparture();
SwingUtilities.invokeLater(() -> {
modalDialog.setVisible(false);
modalDialog.dispose();
});
}).start();
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(5, 15, 5, 5);
pnlDepAirport.add(btnAddDep, gridBagConstraints);
pnlDep.add(pnlDepAirport);
}
private void createPanelDestination() {
java.awt.GridBagConstraints gridBagConstraints;
pnlDest = new JPanel();
pnlDest.setLayout(new java.awt.BorderLayout());
pnlDestAirport = new javax.swing.JPanel();
pnlDestAirport.setLayout(new java.awt.GridBagLayout());
btnAddDest = new javax.swing.JButton();
btnAddDest.setText("jButton1");
btnAddDest.setMaximumSize(new java.awt.Dimension(75, 35));
btnAddDest.setMinimumSize(new java.awt.Dimension(75, 35));
btnAddDest.setPreferredSize(new java.awt.Dimension(75, 35));
btnAddDest.addActionListener((java.awt.event.ActionEvent evt) -> {
JFrame f = new JFrame();
JDialog modalDialog = new JDialog(f, "Busy", Dialog.ModalityType.MODELESS);
modalDialog.setSize(200, 100);
modalDialog.setLocationRelativeTo(f);
modalDialog.setUndecorated(true);
modalDialog.getRootPane().setWindowDecorationStyle(JRootPane.NONE);
modalDialog.getContentPane().setBackground(Color.WHITE);
modalDialog.add(new JLabel("Please wait... ", JLabel.CENTER));
modalDialog.setVisible(true);
new Thread(() -> {
getPresenter().addDestination();
SwingUtilities.invokeLater(() -> {
modalDialog.setVisible(false);
modalDialog.dispose();
});
}).start();
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(5, 15, 5, 5);
pnlDestAirport.add(btnAddDest, gridBagConstraints);
pnlDest.add(pnlDestAirport);
}
private void createPanelAlternate() {
java.awt.GridBagConstraints gridBagConstraints;
pnlAlt = new JPanel();
pnlAlt.setLayout(new java.awt.BorderLayout());
pnlAltAirport = new JPanel();
pnlAltAirport.setLayout(new java.awt.GridBagLayout());
btnAddAlt = new JButton();
btnAddAlt.setText("ADD");
btnAddAlt.setMaximumSize(new java.awt.Dimension(75, 35));
btnAddAlt.setMinimumSize(new java.awt.Dimension(75, 35));
btnAddAlt.setPreferredSize(new java.awt.Dimension(75, 35));
btnAddAlt.addActionListener((java.awt.event.ActionEvent evt) -> {
JFrame f = new JFrame();
JDialog modalDialog = new JDialog(f, "Busy", Dialog.ModalityType.MODELESS);
modalDialog.setSize(200, 100);
modalDialog.setLocationRelativeTo(f);
modalDialog.setUndecorated(true);
modalDialog.getRootPane().setWindowDecorationStyle(JRootPane.NONE);
modalDialog.getContentPane().setBackground(Color.WHITE);
modalDialog.add(new JLabel("Please wait... ", JLabel.CENTER));
modalDialog.setVisible(true);
new Thread(() -> {
getPresenter().addAlternate();
SwingUtilities.invokeLater(() -> {
modalDialog.setVisible(false);
modalDialog.dispose();
});
}).start();
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(5, 15, 5, 5);
pnlAltAirport.add(btnAddAlt, gridBagConstraints);
pnlAlt.add(pnlAltAirport);
}
public void createPanelWindsAloft() {
pnlWindsAloftInfo = new javax.swing.JPanel();
pnlWindsAloftInfo.setLayout(new java.awt.GridLayout(1, 0));
pnlWindsAloftTable = new javax.swing.JPanel();
pnlWindsAloftTable.setLayout(new BorderLayout());
javax.swing.JTable tblWindsAloft = new javax.swing.JTable(
new Model_TableWindsAloft(createDataForWindsTable()));
JScrollPane scrollWindsAloft = new JScrollPane(tblWindsAloft,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
tblWindsAloft.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
tblWindsAloft.setFillsViewportHeight(true);
pnlWindsAloftTable.add(scrollWindsAloft, BorderLayout.CENTER);
pnlWindsAloftInfo.add(pnlWindsAloftTable);
pnlWindsAloft.add(pnlWindsAloftInfo, java.awt.BorderLayout.CENTER);
}
public List<List<String>> createDataForWindsTable() {
List<List<String>> finalResult = new ArrayList<>();
System.out.println("SIZE: " + finalResult.size());
for (int i = 0; i < appSingleton.flightPlanShared.size(); i++) {
String icao;
String name;
String type;
if (appSingleton.flightPlanShared.get(i).size() > 2) {
icao = appSingleton.flightPlanShared.get(i).get(2);
name = appSingleton.flightPlanShared.get(i).get(1);
type = appSingleton.flightPlanShared.get(i).get(0);
} else {
icao = "";
name = "";
type = "";
}
List<String> components = new ArrayList<>();
components.add(icao);
components.add(name);
components.add(type);
System.out.println("COMPONENTS: " + components);
finalResult.add(components);
}
/*
* THIS WORKS! String a1 = "LAS VEGAS/MC CARRAN "; String a2 = "KLAS";
* String a3 = "PORTDEP";
*
* List<String> a = new ArrayList<>(); a.add(a1); a.add(a2); a.add(a3);
*
* String b1 = "LOS ANGELES INTL"; String b2 = "KLAX"; String b3 =
* "PORTDEST"; List<String> b = new ArrayList<>(); b.add(b1); b.add(b2);
* b.add(b3);
*
* String c1 = "SEATTLE-TACOMA INTL"; String c2 = "KSEA"; String c3 =
* "PORTALT"; List<String> c = new ArrayList<>(); c.add(c1); c.add(c2);
* c.add(c3);
*
* finalResult.add(a); finalResult.add(b); finalResult.add(c);
*/
System.out.println("DATA CREATED: " + finalResult);
return finalResult;
}
public Presenter getPresenter() {
return presenter;
}
public void setPresenter(Presenter presenter) {
this.presenter = presenter;
}
}
class Presenter {
private final View_MainFrame viewMainFrame;
private final Model_Flightplan model;
public Presenter(View_MainFrame viewMainFrame, Model_Flightplan model) {
this.viewMainFrame = viewMainFrame;
this.model = model;
}
public void displayTabDep() {
CardLayout card = (CardLayout) viewMainFrame.getPanelContext().getLayout();
card.show(viewMainFrame.getPanelContext(), "cardDep");
viewMainFrame.addButtonsFlightplan();
viewMainFrame.btnPnlDeparture.setEnabled(false);
}
public void displayTabDest() {
CardLayout card = (CardLayout) viewMainFrame.getPanelContext().getLayout();
card.show(viewMainFrame.getPanelContext(), "cardDest");
viewMainFrame.addButtonsFlightplan();
viewMainFrame.btnPnlDestination.setEnabled(false);
}
public void displayTabAlt() {
CardLayout card = (CardLayout) viewMainFrame.getPanelContext().getLayout();
card.show(viewMainFrame.getPanelContext(), "cardAlt");
viewMainFrame.addButtonsFlightplan();
viewMainFrame.btnPnlAlternate.setEnabled(false);
}
public void displayTabWindsAloft() {
CardLayout card = (CardLayout) viewMainFrame.getPanelContext().getLayout();
card.show(viewMainFrame.getPanelContext(), "cardWindsAloft");
viewMainFrame.addButtonsFlightplan();
viewMainFrame.btnPnlWindsAloft.setEnabled(false);
viewMainFrame.createPanelWindsAloft();
}
public void addDeparture() {
model.addDepartureAirport();
}
public void addDestination() {
model.addDestinationAirport();
}
public void addAlternate() {
model.addAlternateAirport();
}
}
class Model_TableWindsAloft extends AbstractTableModel {
String[] columnNames = { "ICAO", "Name", "Type" };
private List<List<String>> tableData = new ArrayList<>();
public Model_TableWindsAloft(List<List<String>> tableData) {
this.tableData = tableData;
System.out.println("CONSTRUCTOR? " + tableData);
}
#Override
public int getRowCount() {
System.out.println("DATA COUNT? " + tableData.size());
return (tableData.size());
}
#Override
public int getColumnCount() {
return (columnNames.length);
}
#Override
public String getColumnName(int column) {
return columnNames[column];
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
System.out.println("WHAT IS DATA 1? " + tableData);
List<String> data = tableData.get(rowIndex);
System.out.println("WHAT IS DATA 2? " + data);
if (data.size() >= 3) {
switch (columnIndex) {
case 0:
return data.get(0);
case 1:
return data.get(1);
case 2:
return data.get(2);
default:
return null;
}
} else {
return null;
}
}
}
class Model_Flightplan {
AppSingleton appSingleton = AppSingleton.getInstance();
private Presenter presenter;
private View_MainFrame viewMainFrame;
public Model_Flightplan(View_MainFrame viewMainFrame) {
this.viewMainFrame = viewMainFrame;
}
public Presenter getPresenter() {
return presenter;
}
public void setPresenter(Presenter presenter) {
this.presenter = presenter;
}
public void addDepartureAirport() {
List<String> component = new ArrayList<>();
component.add("KLAS");
component.add("KLAS");
component.add("KLAS");
appSingleton.flightPlanShared.set(0, component);
}
public void addDestinationAirport() {
List<String> component = new ArrayList<>();
component.add("KLAX");
component.add("KLAX");
component.add("KLAX");
appSingleton.flightPlanShared.set((appSingleton.flightPlanShared.size() - 2), component);
}
public void addAlternateAirport() {
List<String> component = new ArrayList<>();
component.add("KSEA");
component.add("KSEA");
component.add("KSEA");
appSingleton.flightPlanShared.set((appSingleton.flightPlanShared.size() - 1), component);
}
}
class AppSingleton {
private static AppSingleton instance = null;
public List<List<String>> flightPlanShared = new ArrayList<List<String>>() {
{
add(Arrays.asList(""));
add(Arrays.asList(""));
add(Arrays.asList(""));
}
};
private AppSingleton() {
}
public static AppSingleton getInstance() {
if (instance == null) {
instance = new AppSingleton();
}
return instance;
}
}

Changing panels in gui

What I am trying to do is change the right side of my GUI each time I press a button. First button shows a JLabel second button a JTextField. Expected outcome change in panels. Outcome is that when I press the buttons nothing happens.
package javaapplication37;
import java.awt.GridLayout;
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.*;
public class Gui extends JFrame {
JTextField f1;
JPanel b, p1, p2;
JPanel p3;
JLabel l1;
JButton b2, b1;
String a;
public Gui() {
a="Input here";
setSize(600,600);
l1=new JLabel("8a petuxei");
b = new JPanel();
p3 = new JPanel();
p1 = new JPanel();
p2 = new JPanel();
b.setLayout(new GridLayout(2, 1));
b1 = new JButton("Eleos");
b2 = new JButton("elpizw");
b.add(b1);
b.add(b2);
b.setSize(150,600);
p1.setSize(450,600);
add(b);
add(p1);
ActionListener pou = new Listener(p1);
b1.addActionListener(pou);
p2.add(l1);
f1=new JTextField(a);
a=f1.getText();
p3.add(f1);
}
public class Listener implements ActionListener {
JPanel k;
public Listener(JPanel k) {
this.k = k;
}
#Override
public void actionPerformed(ActionEvent e) {
k.remove(getContentPane());
k.add(p2);
}
}
public class l implements ActionListener {
JPanel k;
public l(JPanel k) {
this.k = k;
}
#Override
public void actionPerformed(ActionEvent e) {
k.remove(getContentPane());
k.add(p3);
}
}
}
You need to be using a CardLayout. If you need help ask me.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
public class Gui extends JFrame implements ActionListener {
private JPanel menu = new JPanel();
private CardLayout contentLayout = new CardLayout();
private JPanel content = new JPanel(contentLayout);
private java.util.List<Card> cardList = new ArrayList<>();
public Gui() {
int i;
for (i = 0; i < 10; i++) {
Card card;
if(i % 2 == 0) card = new TextAreaCard("Card " + i, "this is the content for card #" + i);
else card = new LabelCard("Card " + i, "content for Label Card #" + i);
JButton btn = new JButton(card.name);
menu.add(btn);
btn.addActionListener(this);
content.add(card, card.name);
cardList.add(card);
}
menu.setLayout(new GridLayout(i, 1));
add(menu, BorderLayout.WEST);
add(content, BorderLayout.CENTER);
}
#Override
public void actionPerformed(ActionEvent e) {
contentLayout.show(content, e.getActionCommand());
}
class Card extends JPanel{
final String name;
public Card(String name){
this.name = name;
}
}
class TextAreaCard extends Card implements ActionListener {
JTextArea textArea = new JTextArea();
JButton btn = new JButton("OK");
public TextAreaCard(String name, String text) {
super(name);
textArea.setText(text);
setLayout(new BorderLayout());
add(textArea, BorderLayout.CENTER);
add(btn, BorderLayout.SOUTH);
btn.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(this, textArea.getText(), "click OK", JOptionPane.NO_OPTION);
}
}
class LabelCard extends Card{
JLabel label = new JLabel();
public LabelCard(String name, String text) {
super(name);
label.setText(text);
add(label);
}
}
public static void main(String [] args){
Gui gui = new Gui();
gui.setSize(600, 500);
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setVisible(true);
}
}

component must be showing on the screen to determine its location when changing JCOMBOX

I am receiving this error when i change items in the Jcombobox, nothing breaks it just shows this error, is there anyway to just throw it so it doesn't show up. everything still works fine, but if you wish to have a look at the code. i will post below.
Error message:
java.awt.IllegalComponentStateException: component must be showing on the screen to determine its location
at java.awt.Component.getLocationOnScreen_NoTreeLock(Component.java:2056)
at java.awt.Component.getLocationOnScreen(Component.java:2030)
at sun.lwawt.macosx.CAccessibility$23.call(CAccessibility.java:395)
at sun.lwawt.macosx.CAccessibility$23.call(CAccessibility.java:393)
at sun.lwawt.macosx.LWCToolkit$CallableWrapper.run(LWCToolkit.java:538)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:301)
And my code which i don't know which section to show so its all their.
import javax.swing.*;
import java.awt.Dialog.ModalityType;
import java.awt.event.*;
import java.awt.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
public class TouchOn extends JDialog {
private JPanel mainPanel;
public ArrayList Reader(String Txtfile) {
try {
ArrayList<String> Trains = new ArrayList<String>();
int count = 0;
String testing = "";
File file = new File(Txtfile);
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null)
{
stringBuffer.append(line);
count += count;
if(!line.contains("*")){
Trains.add(line + "\n");
}
stringBuffer.append("\n");
}
fileReader.close();
//Arrays.asList(Trains).stream().forEach(s -> System.out.println(s));
return Trains;
} catch (IOException e) {
e.printStackTrace();
}
//return toString();
return null;
}
public TouchOn()
{
setPanels();
setModalityType(ModalityType.APPLICATION_MODAL);
setSize(400, 300);
setVisible(true);
}
public void setPanels()
{
mainPanel = new JPanel(new GridLayout(0, 2));
JPanel containerPanel = new JPanel(new GridLayout(0, 1));
JLabel startDay = new JLabel("Day:");
JTextField sDay = new JTextField();
JLabel startMonth = new JLabel("Month:");
JTextField sMonth = new JTextField();
JLabel startYear = new JLabel("Year:");
JTextField sYear = new JTextField("2015");
String trainline = "";
JLabel touchOnTimehr = new JLabel("Time Hour: ");
JLabel touchOnTimem = new JLabel("Time Minute:");
JLabel station = new JLabel("Station: ");
JTextField touchOnTimeFieldhour = new JTextField();
JTextField touchOnTimeFieldminute = new JTextField();
JPanel lowerPanel = new JPanel(new FlowLayout());
ArrayList<String> stations = Reader("TrainLines.txt");
JComboBox<String> cb = new JComboBox<>(stations.toArray(new String[stations.size()]));
JRadioButton belgrave = new JRadioButton("Belgrave Line");
belgrave.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
}
});
JRadioButton glenwaverly = new JRadioButton("Glen Waverly Line");
glenwaverly.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
}
});
ButtonGroup bG = new ButtonGroup();
JButton apply = new JButton("Touch on");
JButton cancel = new JButton("Cancel");
cancel.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
dispose();
}
});
apply.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String timestamp = new java.text.SimpleDateFormat("dd/MM/yyyy").format(new Date());
String day = sDay.getText();
String month = sMonth.getText();
String year = sYear.getText();
String hour = touchOnTimeFieldhour.getText();
String minute = touchOnTimeFieldminute.getText();
if(belgrave.isSelected()){
String trainline = belgrave.getText();
}
if(glenwaverly.isSelected()){
String trainline = glenwaverly.getText();
}
System.out.println(trainline);
}
});
cb.setVisible(true);
bG.add(belgrave);
bG.add(glenwaverly);
mainPanel.add(startDay);
mainPanel.add(sDay);
mainPanel.add(startMonth);
mainPanel.add(sMonth);
mainPanel.add(startYear);
mainPanel.add(sYear);
mainPanel.add(touchOnTimehr);
mainPanel.add(touchOnTimeFieldhour);
mainPanel.add(touchOnTimem);
mainPanel.add(touchOnTimeFieldminute);
mainPanel.add(belgrave);
mainPanel.add(glenwaverly);
mainPanel.add(station);
mainPanel.add(new JLabel());
mainPanel.add(cb);
lowerPanel.add(apply);
lowerPanel.add(cancel);
touchOnTimeFieldhour.setSize(10,10);
containerPanel.add(mainPanel);
containerPanel.add(lowerPanel);
add(containerPanel);
}
}
Don't create multiple JComboBoxes and then swap visibility. Instead use one JComboBox and create multiple combo box models, such as by using DefaultComboBoxModel<String>, and then swap out the model that it holds by using its setModel(...) method. Problem solved.
Note that using a variation on your code -- I'm not able to reproduce your problem:
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Date;
import javax.swing.AbstractAction;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class TestFoo2 {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndDisplayGui();
}
});
}
public static void createAndDisplayGui() {
final JFrame frame = new JFrame("Foo");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JButton button = new JButton(new AbstractAction("Press Me") {
#Override
public void actionPerformed(ActionEvent evt) {
TouchOn2 touchOn2 = new TouchOn2(frame);
touchOn2.setVisible(true);
}
});
JPanel panel = new JPanel();
panel.add(button);
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
#SuppressWarnings("serial")
class TouchOn2 extends JDialog {
private JPanel mainPanel;
#SuppressWarnings({ "rawtypes", "unused" })
public ArrayList Reader(String Txtfile) {
ArrayList<String> list = new ArrayList<>();
for (int i = 0; i < 100; i++) {
list.add("Data String Number " + (i + 1));
}
// return toString();
// !! return null;
return list;
}
public TouchOn2(Window owner) {
super(owner);
setPanels();
setModalityType(ModalityType.APPLICATION_MODAL);
setSize(400, 300);
setVisible(true);
}
#SuppressWarnings("unchecked")
public void setPanels() {
mainPanel = new JPanel(new GridLayout(0, 2));
JPanel containerPanel = new JPanel(new GridLayout(0, 1));
JLabel startDay = new JLabel("Day:");
final JTextField sDay = new JTextField();
JLabel startMonth = new JLabel("Month:");
final JTextField sMonth = new JTextField();
JLabel startYear = new JLabel("Year:");
final JTextField sYear = new JTextField("2015");
final String trainline = "";
JLabel touchOnTimehr = new JLabel("Time Hour: ");
JLabel touchOnTimem = new JLabel("Time Minute:");
JLabel station = new JLabel("Station: ");
final JTextField touchOnTimeFieldhour = new JTextField();
final JTextField touchOnTimeFieldminute = new JTextField();
JPanel lowerPanel = new JPanel(new FlowLayout());
ArrayList<String> stations = Reader("TrainLines.txt");
final JComboBox<String> cb = new JComboBox<>(
stations.toArray(new String[stations.size()]));
final JRadioButton belgrave = new JRadioButton("Belgrave Line");
belgrave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
final JRadioButton glenwaverly = new JRadioButton("Glen Waverly Line");
glenwaverly.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
ButtonGroup bG = new ButtonGroup();
JButton apply = new JButton("Touch on");
JButton cancel = new JButton("Cancel");
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
}
});
apply.addActionListener(new ActionListener() {
#SuppressWarnings("unused")
public void actionPerformed(ActionEvent e) {
String timestamp = new java.text.SimpleDateFormat("dd/MM/yyyy")
.format(new Date());
String day = sDay.getText();
String month = sMonth.getText();
String year = sYear.getText();
String hour = touchOnTimeFieldhour.getText();
String minute = touchOnTimeFieldminute.getText();
if (belgrave.isSelected()) {
// !! ***** note you're shadowing variables here!!!! ****
String trainline = belgrave.getText();
}
if (glenwaverly.isSelected()) {
// !! and here too
String trainline = glenwaverly.getText();
}
System.out.println(trainline);
}
});
cb.setVisible(true);
bG.add(belgrave);
bG.add(glenwaverly);
mainPanel.add(startDay);
mainPanel.add(sDay);
mainPanel.add(startMonth);
mainPanel.add(sMonth);
mainPanel.add(startYear);
mainPanel.add(sYear);
mainPanel.add(touchOnTimehr);
mainPanel.add(touchOnTimeFieldhour);
mainPanel.add(touchOnTimem);
mainPanel.add(touchOnTimeFieldminute);
mainPanel.add(belgrave);
mainPanel.add(glenwaverly);
mainPanel.add(station);
mainPanel.add(new JLabel());
mainPanel.add(cb);
lowerPanel.add(apply);
lowerPanel.add(cancel);
touchOnTimeFieldhour.setSize(10, 10);
containerPanel.add(mainPanel);
containerPanel.add(lowerPanel);
add(containerPanel);
}
}

Basic Multiply and Divide Java GUI

I am trying to have the number the user inputs into the frame either multiply by 2 or divide by 3 depending on which button they decide to click. I am having an hard time with working out the logic to do this. I know this needs to take place in the actionperformed method.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Quiz4 extends JFrame ActionListener
{
// Global Variable Declarations
// Our list input fields
private JLabel valueLabel = new JLabel("Enter a value between 1 and 20: ");
private JTextField valueField = new JTextField(25);
// create action buttons
private JButton multiButton = new JButton("x2");
private JButton divideButton = new JButton("/3");
private JScrollPane displayScrollPane;
private JTextArea display = new JTextArea(10,5);
// input number
private BufferedReader infirst;
// output number
private NumberWriter outNum;
public Quiz4()
{
//super("List Difference Tool");
getContentPane().setLayout( new BorderLayout() );
// create our input panel
JPanel inputPanel = new JPanel(new GridLayout(1,1));
inputPanel.add(valueLabel);
inputPanel.add(valueField);
getContentPane().add(inputPanel,"Center");
// create and populate our diffPanel
JPanel diffPanel = new JPanel(new GridLayout(1,2,1,1));
diffPanel.add(multiButton);
diffPanel.add(divideButton);
getContentPane().add(diffPanel, "South");
//diffButton.addActionListener(this);
} // Quiz4()
public void actionPerformed(ActionEvent ae)
{
} // actionPerformed()
public static void main(String args[])
{
Quiz4 f = new Quiz4();
f.setSize(1200, 200);
f.setVisible(true);
f.addWindowListener(new WindowAdapter()
{ // Quit the application
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
} // main()
} // end of class
Here's something simpler, but it essentially does what you want out of your program. I added an ActionListener to each of the buttons to handle what I want, which was to respond to what was typed into the textbox. I just attach the ActionListener to the button, and then in the actionPerformed method, I define what I want to happen.
import java.awt.FlowLayout;
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.SwingUtilities;
public class Quizx extends JFrame {
private JPanel panel;
private JTextField textfield;
private JLabel ansLabel;
public Quizx() {
panel = new JPanel(new FlowLayout());
this.getContentPane().add(panel);
addLabel();
addTextField();
addButtons();
addAnswerLabel();
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.setTitle("Quiz 4");
this.setSize(220, 150);
this.setLocationRelativeTo(null);
this.setResizable(false);
this.setVisible(true);
}
private void addTextField() {
textfield = new JTextField();
textfield.setColumns(9);
panel.add(textfield);
}
private void addButtons() {
JButton multButton = new JButton("x2");
JButton divButton = new JButton("/3");
panel.add(multButton);
panel.add(divButton);
addMultListener(multButton);
addDivListener(divButton);
}
private void addLabel() {
JLabel valueLabel = new JLabel("Enter a value between 1 and 20: ");
panel.add(valueLabel);
}
private void addAnswerLabel() {
ansLabel = new JLabel();
panel.add(ansLabel);
}
private void addMultListener(JButton button) {
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
ansLabel.setText(String.valueOf(Integer.parseInt(textfield.getText().trim()) * 2));
}
});
}
private void addDivListener(JButton button) {
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
ansLabel.setText(String.valueOf(Double.parseDouble(textfield.getText().trim()) /3));
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Quizx();
}
});
}
}
Hope that helps.

Applet not appearing full

I just created an applet
public class HomeApplet extends JApplet {
private static final long serialVersionUID = -7650916407386219367L;
//Called when this applet is loaded into the browser.
public void init() {
//Execute a job on the event-dispatching thread; creating this applet's GUI.
// setSize(400, 400);
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
createGUI();
}
});
} catch (Exception e) {
System.err.println("createGUI didn't complete successfully");
}
}
private void createGUI() {
RconSection rconSection = new RconSection();
rconSection.setOpaque(true);
// CommandArea commandArea = new CommandArea();
// commandArea.setOpaque(true);
JTabbedPane tabbedPane = new JTabbedPane();
// tabbedPane.setSize(400, 400);
tabbedPane.addTab("Rcon Details", rconSection);
// tabbedPane.addTab("Commad Area", commandArea);
setContentPane(tabbedPane);
}
}
where the fisrt tab is:
package com.rcon;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import com.Bean.RconBean;
import com.util.Utility;
public class RconSection extends JPanel implements ActionListener{
/**
*
*/
private static final long serialVersionUID = -9021500288377975786L;
private static String TEST_COMMAND = "test";
private static String CLEAR_COMMAND = "clear";
private static JTextField ipText = new JTextField();
private static JTextField portText = new JTextField();
private static JTextField rPassText = new JTextField();
// private DynamicTree treePanel;
public RconSection() {
// super(new BorderLayout());
JLabel ip = new JLabel("IP");
JLabel port = new JLabel("Port");
JLabel rPass = new JLabel("Rcon Password");
JButton testButton = new JButton("Test");
testButton.setActionCommand(TEST_COMMAND);
testButton.addActionListener(this);
JButton clearButton = new JButton("Clear");
clearButton.setActionCommand(CLEAR_COMMAND);
clearButton.addActionListener(this);
JPanel panel = new JPanel(new GridLayout(3,2));
panel.add(ip);
panel.add(ipText);
panel.add(port);
panel.add(portText);
panel.add(rPass);
panel.add(rPassText);
JPanel panel1 = new JPanel(new GridLayout(1,3));
panel1.add(testButton);
panel1.add(clearButton);
add(panel);
add(panel1);
// add(panel, BorderLayout.NORTH);
// add(panel1, BorderLayout.SOUTH);
}
#Override
public void actionPerformed(ActionEvent arg0) {
if(arg0.getActionCommand().equals(TEST_COMMAND)){
String ip = ipText.getText().trim();
if(!Utility.checkIp(ip)){
ipText.requestFocusInWindow();
ipText.selectAll();
JOptionPane.showMessageDialog(this,"Invalid Ip!!!");
return;
}
String port = portText.getText().trim();
if(port.equals("") || !Utility.isIntNumber(port)){
portText.requestFocusInWindow();
portText.selectAll();
JOptionPane.showMessageDialog(this,"Invalid Port!!!");
return;
}
String pass = rPassText.getText().trim();
if(pass.equals("")){
rPassText.requestFocusInWindow();
rPassText.selectAll();
JOptionPane.showMessageDialog(this,"Enter Rcon Password!!!");
return;
}
RconBean rBean = RconBean.getBean();
rBean.setIp(ip);
rBean.setPassword(pass);
rBean.setPort(Integer.parseInt(port));
if(!Utility.testConnection()){
rPassText.requestFocusInWindow();
rPassText.selectAll();
JOptionPane.showMessageDialog(this,"Invalid Rcon!!!");
return;
}else{
JOptionPane.showMessageDialog(this,"Correct Rcon!!!");
return;
}
}
else if(arg0.getActionCommand().equals(CLEAR_COMMAND)){
ipText.setText("");
portText.setText("");
rPassText.setText("");
}
}
}
it appears as
is has cropped some data how to display it full and make the applet non resizable as well. i tried setSize(400, 400); but it didnt helped the inner area remains the same and outer boundaries increases
Here's another variation on your layout. Using #Andrew's tag-in-source method, it's easy to test from the command line:
$ /usr/bin/appletviewer HomeApplet.java
// <applet code='HomeApplet' width='400' height='200'></applet>
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class HomeApplet extends JApplet {
#Override
public void init() {
try {
SwingUtilities.invokeAndWait(new Runnable() {
#Override
public void run() {
createGUI();
}
});
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
private void createGUI() {
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("Rcon1", new RconSection());
tabbedPane.addTab("Rcon2", new RconSection());
this.add(tabbedPane);
}
private static class RconSection extends JPanel implements ActionListener {
private static final String TEST_COMMAND = "test";
private static final String CLEAR_COMMAND = "clear";
private JTextField ipText = new JTextField();
private JTextField portText = new JTextField();
private JTextField rPassText = new JTextField();
public RconSection() {
super(new BorderLayout());
JLabel ip = new JLabel("IP");
JLabel port = new JLabel("Port");
JLabel rPass = new JLabel("Rcon Password");
JButton testButton = new JButton("Test");
testButton.setActionCommand(TEST_COMMAND);
testButton.addActionListener(this);
JButton clearButton = new JButton("Clear");
clearButton.setActionCommand(CLEAR_COMMAND);
clearButton.addActionListener(this);
JPanel panel = new JPanel(new GridLayout(3, 2));
panel.add(ip);
panel.add(ipText);
panel.add(port);
panel.add(portText);
panel.add(rPass);
panel.add(rPassText);
JPanel buttons = new JPanel(); // default FlowLayout
buttons.add(testButton);
buttons.add(clearButton);
add(panel, BorderLayout.NORTH);
add(buttons, BorderLayout.SOUTH);
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(e);
}
}
}
As I mentioned in a comment, this question is really about how to layout components in a container. This example presumes you wish to add the extra space to the text fields and labels. The size of the applet is set in the HTML.
200x130 200x150
/*
<applet
code='FixedSizeLayout'
width='200'
height='150'>
</applet>
*/
import java.awt.*;
import javax.swing.*;
public class FixedSizeLayout extends JApplet {
public void init() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
initGui();
}
});
}
private void initGui() {
JTabbedPane tb = new JTabbedPane();
tb.addTab("Rcon Details", new RconSection());
setContentPane(tb);
validate();
}
}
class RconSection extends JPanel {
private static String TEST_COMMAND = "test";
private static String CLEAR_COMMAND = "clear";
private static JTextField ipText = new JTextField();
private static JTextField portText = new JTextField();
private static JTextField rPassText = new JTextField();
public RconSection() {
super(new BorderLayout(3,3));
JLabel ip = new JLabel("IP");
JLabel port = new JLabel("Port");
JLabel rPass = new JLabel("Rcon Password");
JButton testButton = new JButton("Test");
testButton.setActionCommand(TEST_COMMAND);
JButton clearButton = new JButton("Clear");
clearButton.setActionCommand(CLEAR_COMMAND);
JPanel panel = new JPanel(new GridLayout(3,2));
panel.add(ip);
panel.add(ipText);
panel.add(port);
panel.add(portText);
panel.add(rPass);
panel.add(rPassText);
JPanel panel1 = new JPanel(new FlowLayout(FlowLayout.CENTER,5,5));
panel1.add(testButton);
panel1.add(clearButton);
add(panel, BorderLayout.CENTER);
add(panel1, BorderLayout.SOUTH);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Container c = new RconSection();
JOptionPane.showMessageDialog(null, c);
}
});
}
}
Size of applet viewer does not depend on your code.
JApplet is not window, so in java code you can't write japplet dimensions. You have to change run settings. I don't know where exactly are in other ide's, but in Eclipse you can change dimensions in Project Properties -> Run/Debug settings -> click on your launch configurations file (for me there were only 1 - main class) -> edit -> Parameters. There you can choose width and height for your applet. save changes and you are good to go

Categories

Resources