TextField size and vertical align - java

I use MigLayout on a DialogBox.
Every panel uses MigLayout.
There is a panel for the show row.
There is a panel for every column (delivery type, choose element, Sortie).
There is a panel for the output file row.
There is a panel for button.
Maybe there is a better way to do it wihout too much panels?
My code
//set global layout
this.setLayout( new MigLayout( "wrap 3, debug" ) );
this.add( getSearchPanel(), "span 3, wrap" );
// middle section
this.add( getLivraison(), "width 33%" );
this.add( getChoixElement(), "width 33%" );
this.add( getProfile(), "width 33%" );
JLabel lblFichierSortie = new JLabel( "Output file" );
JTextField txtFichierSortie = new JTextField();
this.add( lblFichierSortie, "span 2, right" );
this.add( txtFichierSortie, "width 33%, wrap" );
this.add( getButton(), "span 3, right" );
private JPanel getSearchPanel() {
JPanel searchPanel = new JPanel( new MigLayout() );
JLabel lblEmission = new JLabel( "Show" );
JTextField txtEmission = new JTextField( 10 );
JTextField txtEM = new JTextField( 5 );
searchPanel.add( lblEmission, "width 2%" );
searchPanel.add( txtEmission, "split 2,right,width 60%, growx" );
searchPanel.add( txtEM, "width 38%, growx" );
return searchPanel;
}
private JPanel getLivraison() {
JPanel livraisonPanel = new JPanel( new MigLayout() );
JLabel lblComponent1 = new JLabel( "Delivery type" );
JCheckBox chkFluxElementaire = new JCheckBox( "Flux" );
JCheckBox chkTranscoding = new JCheckBox( "Transcoding" );
livraisonPanel.add( lblComponent1, "wrap" );
livraisonPanel.add( chkFluxElementaire, "wrap" );
livraisonPanel.add( chkTranscoding, "wrap" );
return livraisonPanel;
}
private JPanel getChoixElement() {
JPanel component2 = new JPanel( new MigLayout() );
JLabel lblChoix = new JLabel( "Choose element" );
JLabel lblVideo = new JLabel( "Vidéo" );
JLabel lblAudio = new JLabel( "Audio" );
JLabel lblAudio2 = new JLabel( "Audio 2" );
JLabel lblSubTitle = new JLabel( "ST" );
JLabel lblMontage = new JLabel( "Montage" );
//todo put combobox below every label
component2.add( lblChoix, "wrap" );
component2.add( lblVideo,"wrap" );
component2.add( lblAudio,"wrap" );
component2.add( lblAudio2, "wrap" );
component2.add( lblSubTitle, "wrap" );
component2.add( lblMontage, "wrap" );
return component2;
}
private JPanel getProfile() {
JPanel component3 = new JPanel( new MigLayout() );
JLabel lblSortie = new JLabel( "Sortie" );
component3.add( lblSortie, "wrap" );
JLabel lblProfil = new JLabel( "Profil" );
component3.add( lblProfil, "wrap" );
JComboBox cbxProfil = new JComboBox();
component3.add( cbxProfil, "wrap" );
return component3;
}
private JPanel getButton() {
JPanel buttonPanel = new JPanel( new MigLayout( "fillx,insets 0" ) );
JButton okButton = new JButton( "Ok" );
okButton.setMnemonic( 'O' );
buttonPanel.add( okButton, "split,right,width 100!" );
// Cancel button
JButton cancelButton = new JButton( "Cancel" );
cancelButton.setMnemonic( 'C' );
buttonPanel.add( cancelButton, "width 100!" );
return buttonPanel;
}
My textfield has no size until I move my windows, i don't understand why.
Also why are'nt the components of every column starting at the top of the panels?

Try this for the "top alignment problem" :
// set global layout
this.setLayout(new MigLayout("wrap 3, debug", null, "[top]"));
and for "the texfield size problem" :
this.add(getSearchPanel(), "span 3, wrap, grow");
If you want to have the same result without an inner JPanel, you can do :
final JLabel lblEmission = new JLabel("Show");
final JTextField txtEmission = new JTextField(10);
final JTextField txtEM = new JTextField(5);
this.add(lblEmission, "width 2%, span 3, split 3");
this.add(txtEmission, "right,width 60%, growx");
this.add(txtEM, "width 38%, growx");
However, this is not my favorite solution. With an inner panel the code is much more simple and reusable. I think when you will add some listeners for user interaction on the component s and controllers for the interactions with the model, this code will be over-complicated. When this will occurs, you may want to extract the SearchPanel into a reusable top-level class with a single responsability. Without a simple inner panel, it will be much more difficult to extract this class.
This is why when i design swing gui, i prefer to use first the BorderLayout and then the MigLayout (for more complex panel).

Related

Why isn't my GUI working, do I need a visible code?

I have a homework problem where I am trying to set up a GUI and do the following:
Step 1. Create a random list of 52 elements holding 52 numbers
corresponding to 52 cards in the cards folder
Step 2. Create a JFrame
2a. set title of your frame
2b. set layout of your frame to have a GridLayout
Step 3. Create 3 cards
3a. create 3 objects of ImageIcon whose image's location is
pointing to the image in the cards folder
3b. create 3 JLabel object, each one hold an ImageIcon object
created above
Step 4. Add three JLabel into your JFrame
Step 5. Pack and display your frame
I am having trouble trying to make my GUI visible and I am also having problems understanding how to implement the ImageIcon. I need to do a Grid Layout, but none of it is showing up.
import javax.swing.*;
import java.awt.*;
public class Question_2 {
static String location = "cards/";
public static void main( String[] args ) {
String[] cards;
cards = new String[ 52 ];
JFrame frmMyWindow = new JFrame( "Random Cards" );
frmMyWindow.setSize( 300, 200 );
frmMyWindow.setLocationRelativeTo( null );
frmMyWindow.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frmMyWindow.setVisible( true );
}
}
class frmMyWindow extends JFrame {
JLabel lblName;
JPanel panelMain, panelLeft, panelCenter, panelRight;
private int realityState;
private int commState;
public frmMyWindow( String Cards ) {
super( "Cards" );
realityState = commState = 0;
lblName = new JLabel( "Cards" );
panelMain = new JPanel( new GridLayout( 1, 3, 10, 10 ) );
setLayout( new BorderLayout( 20, 10 ) );
add( lblName, BorderLayout.NORTH );
add( panelMain, BorderLayout.CENTER );
panelLeft = new JPanel( new FlowLayout( FlowLayout.CENTER, 5, 10 ) );
panelCenter = new JPanel( new FlowLayout( FlowLayout.LEFT, 5, 5 ) );
panelRight = new JPanel( new FlowLayout( FlowLayout.CENTER, 5, 10 ) );
panelMain.add( panelLeft );
panelMain.add( panelCenter );
panelMain.add( panelRight );
}
}
I wanted the code to show up where there is a title that has the word Cards and then the grid layout with the 3 randomly chosen cards from the card file.
Everything is fine except you are creating JFrame instance instead of your custom class.
The following line
JFrame frmMyWindow = new JFrame( "Random Cards" );
Should be
JFrame frmMyWindow = new frmMyWindow( "Random Cards" );

How to connect combobox (String) to a JTextField on JFrame for Java

I am trying to do a hockey stats program and how do I connect the String that I created for the combobox to the JTextField. (For example, if Corey Perry on Anaheim has 3 goals, how do I put 3 goals on the Goals JTextField)? Also, if possible, how do I make -----Centre----- unclickable?
public FantasyHockey()
{
String team[] = {"Anaheim Ducks", "Arizona Coyotes", "Boston Bruins", "Buffalo Sabres", "Calgary Flames", "Caroline Huricanes", "Chicago Blackhawks", "Colorado Avalanche", "Columbus Blue Jackets", "Dallas Stars", "Detroit Red Wings", "Edmonton Oilers", "Florida Panthers", "Los Angeles Kings", "Minnesota Wild", "Montreal Canadiens", "Nashville Predators", "New Jersey Devils", "New York Islanders", "New York Rangers", "Ottawa Senators", "Philadelphia Flyers", "Pittsburgh Penguins", "San Jose Sharks", "St. Louis Blues", "Tampa Bay Lightning", "Toronto Maple Leafs", "Vancouver Canucks", "Washington Capitals", "Winnipeg Jets"};
teamName = new JComboBox( team );
teamName.setBounds(50, 48, 166, 25);
teamName.addActionListener( this );
getContentPane().setLayout(null);
getContentPane().add( teamName );
playerName = new JComboBox();
playerName.setBounds(241, 47, 191, 27);
//playerName.setPrototypeDisplayValue("XXXXXXXXXX");
getContentPane().add( playerName );
String[] Anaheim = { "-----Centres-----", "Corey Perry","Ryan Getzlaf" };
subItems.put(team[0], Anaheim);
String[] Arizona = { "Max Domi" };
subItems.put(team[1], Arizona);
String[] Bruins = { "Tuukka Rask" };
subItems.put(team[2], Bruins);
teamName.setSelectedIndex(0);
JLabel lblTeam = new JLabel("Team");
lblTeam.setBounds(50, 22, 61, 16);
getContentPane().add(lblTeam);
JLabel lblPlayer = new JLabel("Player");
lblPlayer.setBounds(241, 19, 61, 16);
getContentPane().add(lblPlayer);
Goals = new JTextField();
Goals.setBounds(25, 181, 42, 25);
getContentPane().add(Goals);
Goals.setColumns(10);
Goals.setEnabled(false);
JLabel lblGoals = new JLabel("Goals");
lblGoals.setBounds(25, 153, 61, 16);
getContentPane().add(lblGoals);
}
public void actionPerformed(ActionEvent e)
{
String item = (String)teamName.getSelectedItem();
Object o = subItems.get(item);
if (o == null)
{
playerName.setModel( new DefaultComboBoxModel() );
}
else
{
playerName.setModel( new DefaultComboBoxModel( (String[])o ) );
}
}
public void Goals(){
if(teamName.getSelectedItem().equals("Anaheim Ducks")){
if(playerName.getSelectedItem().equals("Corey Perry")){
Goals.setText("a");
}
}
}
public static void main(String[] args)
{
JFrame frame = new FantasyHockey();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible( true );
frame.setBounds(100, 100, 450, 300);
frame.setResizable(true);
}
}
if Corey Perry on Anaheim has 3 goals, how do I put 3 goals on the Goals JTextField
Then you need to store a custom Object in the ComboBoxModel. This object will have two pieces of information - playerName and playerGoals. The name will be displayed in the combo box and then when you click on the item you can get the object and then display the goals.
Check out ComboBox With Custom Renderer for an outline of this approach.
Also, if possible, how do I make -----Centre----- unclickable?
One option to display a prompt when no item is selected. Check out Combo Box Prompt for a suggestion.
Note: if you want to use these ideas you will need to modify the first solution to support the prompt, since both suggestion involve a custom renderer the code needs to combined into one.

TabbedPane iterate for loop

I received in loop iteration as:
Tab 1
Tab 2
On beginning code I have panel, tabbedpane and scrollpane:
JPanel panel = new JPanel();
JTabbedPane tabbedPane = new JTabbedPane();
JScrollPane scrollPanel = new JScrollPane();
Then receive through iteration using Event JList and receive Tab 1 and Tab 2, but can't add two tabs. So here is iterate and receive Tab 1 and Tab 2 into tab_name variable:
String tab_name = ap_data_array[2]; // Tab 1, Tab 2
tabbedPane.addTab(tab_name, panel); // Here add only once tab Tab 1
this.jPanel1.add(tabbedPane, BorderLayout.CENTER);
scrollPanel.setViewportView(new JLabel(ap_data_array[2]));
tabbedPane.setBounds(0, 0, 530, 500);
this.jPanel1.setSize(530,500);
System.out.println(tab_name); // Tab 1 then Tab 2
A result will only render 1 tab, Tab 1.
Here is full code:
String lines[] = loaded_data.split("\\r?\\n");
for (String item : lines)
{
String pattern = "AP.*";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(item);
// Added
JPanel panel = new JPanel();
JTabbedPane tabbedPane = new JTabbedPane();
JScrollPane scrollPanel = new JScrollPane();
if (m.find())
{
String ap_data = m.group(0);
String[] ap_data_array = ap_data.split("\\|", -1);
if (ap_data_array[0].equals("AP"))
{
JList source = (JList)evt.getSource();
String selected = source.getSelectedValue().toString();
// type selected
if (ap_data_array[1].equals(selected))
{
// tabs name
//ap_data_array[2] // "Tab 1" "Tab 2"
String tab_name = ap_data_array[2];
tabbedPane.addTab(tab_name, panel);
this.jPanel1.add(tabbedPane, BorderLayout.CENTER);
scrollPanel.setViewportView(new JLabel(ap_data_array[2]));
tabbedPane.setBounds(0, 0, 530, 500);
this.jPanel1.setSize(530,500);
System.out.println(tab_name); // "Tab 1" "Tab 2"
}
}
}
}
SOLUTION:
private void jList1ValueChanged(javax.swing.event.ListSelectionEvent evt) {
if (evt.getValueIsAdjusting())
{
JTabbedPane tabbedPane = new JTabbedPane();
this.jPanel1.removeAll(); // REMOVE ALL DATA IN PANEL TO RELOAD NEW TAB PANEL IN LOOP
String lines[] = loaded_data.split("\\r?\\n");
for (String item : lines)
{
String pattern = "AP.*";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(item);
JPanel panel = new JPanel();
if (m.find())
{
String ap_data = m.group(0);
String[] ap_data_array = ap_data.split("\\|", -1);
if (ap_data_array[0].equals("AP"))
{
JList source = (JList)evt.getSource();
String selected = source.getSelectedValue().toString();
// type selected
if (ap_data_array[1].equals(selected))
{
String tab_name = ap_data_array[2]; // STRING "Tab 1" and "Tab 2" loop
this.jPanel1.add(tabbedPane, BorderLayout.CENTER);
tabbedPane.add(tab_name, new JLabel(tab_name));
tabbedPane.setBounds(0, 0, 530, 500);
this.jPanel1.setSize(530,500);
}
}
}
}
}
}
If I understand your code correctly (no guarantee since it's not a minimal example program that I can run and test), inside of the for loop you're creating a new JTabbedPane with each iteration, adding a single tab to it, and then adding it to a BorderLayout-using JPanel in the BorderLayout.CENTER position. Thus if you iterate twice, you will create two JTabbedPanes, each with only one tab, and the second one will completely cover the first one. If this is indeed the source of your problems then the solution is easy: create only one JTabbedPane, do this before the for loop, and add your tabs (JPanels) inside the for loop.
Other problems include your use of setBounds(...). Don't do this.

GUI java text and textfields opposite displayed

I am new to gui in java, i spent 3
hours trying to figure out what i have done wrong or misunderstood, i should get this:
but the text in my code is displayed after textfields
textPanel = new JPanel();
textPanel.setLayout(new GridLayout(3,0));
fName = new JTextField( 15 ) ;
textPanel.add(fName);
jlbName = new JLabel ( "Firstname" );
jlbName.setHorizontalAlignment(JLabel.RIGHT);
textPanel.add(jlbName);
lName = new JTextField( 15 ) ;
textPanel.add(lName);
jlbName = new JLabel ( "LastName" );
jlbName.setHorizontalAlignment(JLabel.RIGHT);
textPanel.add(jlbName);
libNo = new JTextField( 15 ) ;
textPanel.add(libNo);
libNo.setEditable(false);
jlbName = new JLabel ( "Library Number" );
jlbName.setHorizontalAlignment(JLabel.RIGHT);
textPanel.add(jlbName);
add(textPanel,BorderLayout.EAST);
JButton jbtN = new JButton("Add borrower");
add(jbtN ,BorderLayout.SOUTH);
You are inserting the components into the panel in the wrong order. You first insert the text fields and later the labels. Do the opposite, i.e. instead of:
textPanel.add(fName);
...
textPanel.add(jlbName);
...
do:
textPanel.add(jlbName);
...
textPanel.add(fName);
...

A JFormattedTextField to accept a currency format without decimals

How do I code a JFormattedTextField to accept a currency format without decimals?
I have tried looking for my answer everywhere. Here, Oracle, Google, and Code Ranch to be specific.
My question: How do I code a formatted text field to accept a currency format without decimals. The text field can accept a value anywhere from $5 to $10,000,000. I would like it to include the "," when need. This field will not be used for mathematical expressions so there is no need to convert it from a string.
Here is the code that I am trying to use. This format is not allowing me to enter any digits at all in the formatted text field.
buildInfo method
//The buildInfo method will build the info panel
private void buildInfo()
{
info = new JPanel();
GridLayout gl = new GridLayout (3,1);
info.setLayout (gl);
//Create panel, label, and text area for pledgers name
p1 = new JPanel();
p1.setLayout(new FlowLayout(FlowLayout.LEFT));
label1 = new JLabel ("Pledger's Name: ");
p1.add (label1);
text1 = new JTextField (20);
p1.add (text1);
//Create panel, label, and text area for pledge amount
p2 = new JPanel();
p2.setLayout(new FlowLayout(FlowLayout.LEFT));
label2 = new JLabel ("Pledged Amount: ");
p2.add (label2);
NumberFormat amount = NumberFormat.getCurrencyInstance(Locale.US);
amount.setMaximumFractionDigits(0);
NumberFormatter pAmount = new NumberFormatter(amount);
pAmount.setMinimum(5.0);
pAmount.setMaximum(10000000.0);
pAmount.setAllowsInvalid(false);
text2 = new JFormattedTextField (pAmount);
text2.setColumns(12);
p2.add (text2);
//Create panel, label, and text area for charity being pledged
p3 = new JPanel();
p3.setLayout(new FlowLayout(FlowLayout.LEFT));
label3 = new JLabel ("Charity Pledged To:");
p3.add (label3);
text3 = new JTextField (20);
p3.add (text3);
//Add panels to main panel
add(p1);
add(p2);
add(p3);
}
Use
NumberFormat format = NumberFormat.getCurrencyInstance(Locale.US);
format.setMaximumFractionDigits(0);
NumberFormatter formatter = new NumberFormatter(format);
formatter.setMinimum(5.0);
formatter.setMaximum(10000000.0);
formatter.setAllowsInvalid(false);
formatter.setOverwriteMode(true);
JFormattedTextField field = new JFormattedTextField(formatter);
field.setValue(5.0);

Categories