Adding a button component to a java tabbed pane in java - java

i am trying to create GUI using java swings.I am just a beginner in java swings.
My primary idea was to create two tabs and add a button in one of the tabs.
I wanted to write a separate class for each tab so i created 3 classes out of which one has the main method.and the other two represent the tabs.
In one of the tabs i wanted to add a button in middle and add an action listener to that button.
below is the class which has the main method.
public class abc {
JFrame frame;
JTabbedPane tabPane;
ImageIcon close;
Dimension size;
int tabCounter = 0;
abc_export exp;
abc_import imp;
public static void main(String[] args) {
abc jtab = new abc();
jtab.start();
}
public void start(){
exp=new abc_export();
imp=new abc_import();
tabPane.addTab(null, exp.panel);
tabPane.addTab(null, imp.panel);
tabPane.setTabComponentAt(tabPane.getTabCount()-1, exp.tab);
tabPane.setTabComponentAt(tabPane.getTabCount()-1, imp.tab);
}
public abc() {
// Create a frame
frame = new JFrame();
// Create the tabbed pane.
tabPane = new JTabbedPane();
// Create a button to add a tab
// Create an image icon to use as a close button
close = new ImageIcon("C:/JAVAJAZZUP/tabClose.gif");
size = new Dimension(close.getIconWidth()+1, close.getIconHeight()+1);
//Adding into frame
frame.add(tabPane, BorderLayout.CENTER);
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
};
below is code for one of the tabs.although the other tab is also having the same code which represent other tab with different class name.
public class abc_import {
ImageIcon close;
Dimension size;
int tabCounter = 0;
JPanel tab;
final JPanel panel;
public abc_import() {
close = new ImageIcon("C:/JAVAJAZZUP/tabClose.gif");
size = new Dimension(close.getIconWidth()+1, close.getIconHeight()+1);
//Adding into frame
JLabel label = null;
panel = new JPanel();
// Create a panel to represent the tab
tab = new JPanel();
tab.setOpaque(false);
String str = "abc_import";
label = new JLabel(str);
tab.add(label, BorderLayout.WEST);
}
};
as expected both the tabs are created.But i am out of ideas about adding a button inside one of the tabs.
Now my question here is if i wanted to add a button in one of the tabs as i already said.what do i need to do?can anyone help me?

I'm not sure I understand your intent, but you might try the approach shown in the TabComponentsDemo, discussed in How to Use Tabbed Panes: Tabs With Custom Components.
A related example is shown here.

You can try by using setTabComponentAt method.
This methd has the parameter setTabComponentAt(int index, Component component), in which you just mention the component you want.
You can refer a link here.

Related

IntelliJ GUI Form not appearing

I'm making a simple weather app using IntelliJ and built in form designer. I have made and designed a form and edited the bound class file accordingly. When I actually run the code, the form I designed does now show up at all, in fact just the last line (maxtemp) is the only value that shows up on an empty white screen.
P.S I am using Gradle to build, I have also set the GUI designer to use Java source code instead of byte code (since Gradle does not support the byte code)
import org.json.JSONException;
import org.json.JSONObject;
import javax.swing.*;
import java.awt.*;
public class Frame extends JFrame {
// Get the API
private API api = new API();
// Form elements
public JPanel mainPanel;
public JLabel text;
public JLabel category;
public JLabel mintemp;
public JLabel maxtemp;
public JLabel link;
public Frame() throws Exception, JSONException {
initFrame();
}
public void initFrame() throws Exception, JSONException {
// Get API response
JSONObject wjson = api.connection();
// Filter response and get data
String[] data = api.respFilter(wjson);
// Swing components
mainPanel = new JPanel(new BorderLayout());
text = new JLabel();
category = new JLabel();
mintemp = new JLabel();
maxtemp = new JLabel();
link = new JLabel();
// Add to the frame
add(mainPanel);
add(text);
add(category);
add(mintemp);
add(maxtemp);
text.setText(data[0]);
category.setText(data[1]);
mintemp.setText(data[3]);
maxtemp.setText(data[4]);
}
public static void main(String[] args) throws Exception, JSONException {
JFrame app = new Frame();
app.setTitle("Java-WeatherApp");;
app.setSize(900, 600);
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.setLocationRelativeTo(null);
app.setVisible(true);
}
}
I'm pretty new to Java and very new to the form builder on IntelliJ. Unfortunately I could not find any good tutorials on the form builder. Any help is appreciated!
A JFrame has BorderLayout as a default layout.
In your initFrame() method when you call,
add(mainPanel);
add(text);
add(category);
add(mintemp);
add(maxtemp);
You are adding all the swing components to the JFrame. Since, you are not specifying the position of a component and since the JFrame has BorderLayout, only one component is added to the JFrame that is the last component you add to it, which the maxtemp Jlabel.
You should specify the position of a component when adding to the JFrame having BorderLayout as following,
add(minTemp, BorderLayout.NORTH);
I suggest you to learn more about BorderLayout and LayoutManagers.
OR,
You can use code similar to this,
// Swing components
mainPanel = new JPanel(new GridLayout(4, 1));
text = new JLabel();
category = new JLabel();
mintemp = new JLabel();
maxtemp = new JLabel();
link = new JLabel();
// Add to the mainPanel
mainPanel.add(text);
mainPanel.add(category);
mainPanel.add(mintemp);
mainPanel.add(maxtemp);
//Add mainPanel to Frame
add(mainPanel);
The above written code does the following,
mainPanel = new JPanel(new GridLayout(4, 1)); This line of code set GridLayout as the layout of mainPanel. GridLayout is a type of layout manager which divides the container(mainPanel) in to equal number of grids by dividing it into rows and columns.
In the given code I have divided the mainPanel into 4 rows and 1 columns, so total 4 grids.
mainPanel.add(text);
mainPanel.add(category);
mainPanel.add(mintemp);
mainPanel.add(maxtemp);
This bunch of code add the swing components to the mainPanel. When the first line of code is executed, the text label is added to mainPanel in first grid. Similarly, second line add category to the second grid and similar for the rest.
add(mainPanel); This line of code adds mainPanel to the Frame.
If you executed the above code, the output will be similar to,
Note : I have changed the text of the labels as shown in above image.

How to make a simple image class file in Java

Okai, so basically everything works but the second private class which I named project 2. In this program a grid of 2 by 2 is built out, now in one of the grid spaces (Project3), I want to have an image to be displayed.
public class Project1 extends JFrame
{
private Project2 topleft; // Buttons
private Project3 topright; // Picture
private Project4 bottomleft; // Schedule
//private Project5 bottomright; // Help - Pad
// Constructor
public Project1() throws IOException
{
// Display a title.
setTitle(" UAE University Interactive Course Calculator");
// Specify an action for the close button.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create a GridLayout manager.
setLayout(new GridLayout(2, 2));
// Create the custom panels.
topleft = new Project2();
topright = new Project3();
bottomleft = new Project4();
//bottomright = new Project5();
//bottomright = new Project5();
// Create the button panel.
add(topleft);
add(topright);
add(bottomleft);
//add(bottomright);
// setting formatting options
pack();
setResizable(true);
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setVisible(true);
}
// Main method
public static void main(String[] args) throws IOException
{
new Project1();
}
}
This is where I got to so far, maybe my logic is wrong. All I need is just an image to be displayed, that's all
public class Project3 extends JPanel
{
private JButton run,fancyButton, hel, but, done_by,exit, past;
public Project3()
{
Icon java1 = new ImageIcon( "untitled1.jpg" );
fancyButton = new JButton( "Fancy Button", java1 );
add(fancyButton);
}
}
EDIT!!!: okai now this works, but it's a buttoned image, I want it to become just an image without the button any ideas?
One of the simplest options to load and show an image on a JPanel:
Create an ImageIcon.
Create a JLabel and pass the ImageIcon as a parameter.
Add the JLabel to the JPanel (or any other swing component).
You can find a detailed example by reading How to use icons.

Improper use of JTextField (maybe) Help creating a GUI

I'm very new to Java and I'm trying to create a small program that reverses text (That part I've figured out).
Where I'm getting stuck on is my GUI, my envisioned plan for the gui is a window with a centered text field for user input then under it in the directly middle of the window a button that reverses the text from the above text box and outputs it in a text box below the button.
Right now I'm using JTextField boxes and after trying to make them look the way I want I'm getting the feeling that there's an easier way to do it, but I don't know it.
Here's my GUI class:
public class ReverseTextGUI extends ReverseRun implements ActionListener {
public static JFrame frame;
private JPanel northFlowLayoutPanel;
private JPanel centerFlowLayoutPanel;
private JPanel southFlowLayoutPanel;
private final JButton reverse = new JButton("Reverse");
private final JTextField userInput = new JTextField(50);
private final JTextField reverseOutput = new JTextField(50);
public void actionPerformed(ActionEvent e) {
reverse.addActionListener((ActionListener) reverse);
reverse.setActionCommand("Reverse");
if ("algorithm".equals(e.getActionCommand())) {
System.out.println("test");
}
}
public void initUI() {
northFlowLayoutPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
northFlowLayoutPanel.add(userInput);
userInput.setPreferredSize(new Dimension(150,100));
centerFlowLayoutPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
centerFlowLayoutPanel.add(reverse);
southFlowLayoutPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
southFlowLayoutPanel.setBorder(BorderFactory.createTitledBorder("Output text"));
southFlowLayoutPanel.add(reverseOutput);
reverseOutput.setPreferredSize(new Dimension(150,100));
JFrame frame = new JFrame("Backwardizer");
frame.setLayout(new BorderLayout()); // This is the default layout
frame.add(northFlowLayoutPanel, BorderLayout.PAGE_START);
frame.add(centerFlowLayoutPanel, BorderLayout.CENTER);
frame.add(southFlowLayoutPanel, BorderLayout.PAGE_END);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setSize(750, 500);
}
Any ideas how to either move the cursor to the start of the box (it shows up in the middle as of now) or a better way to accomplish what I'm trying to do?
For the reversing aspect, you can add the text from the first box to a string builder
StringBuilder rev = new StringBuilder(firstBox.getText());
String reversedText = rev.reverse().toString();
secondBox.setText(reversedText);
Something along those line should get the desired result if you nest it in the button action.
Any ideas how to either move the cursor to the start of the box (it shows up in the middle as of now) or a better way to accomplish what I'm trying to do?
JTextField#setCaretPosition, call this AFTER you've updated the text of the field
Make the field readonly, JTextField#setEditable and pass it false
Additionally, you could use a JList or JTextArea if you want to store multiple rows/lines of text
You should also avoid using setPreferredSize, see Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing? for more details

Switching Panels in Swing

I have a Swing application using Card Layout which basically changes the displayed panel depending on what the user selects from a drop-down menu.
One of my panels has a form. I would need for when the submit buton is pressed for all the inputs to be collected and the Panel to be switched to another one. (This second panel is defined in a separate class) I would also need for all the input to be somehow passed to a method in the new panel.
Any suggestions?
Dario
If you look at the <--s in the following code, each should solve each different question you have in your post. I figured you should know how to make a submit button, so I didn't include that. (Note: this is not running code, just suggestions);
public class MainPanel entends JPanel {
CardLayout layout = new CardLayout(); <-- card layout
JPanel panel = new JPanel(layout); <-- set layout to main panel
NewPanel newPanel = new NewPanel(); <-- you new panel
JPanel p1 = new JPanel(); <-- random panel
JTextField text = new JTextField() <-- text field in form
JButton button = new JButton();
JComboBox cbox = new JComboBox(new String[] {"newPanel", "p1"}); <-- hold panel names
public MainPanel(){
panel.add(newPanel, "newPanel"); <-- name associated with panel
panel.add(p1, "p1");
...
cbox.addAItemListener(new ItemListener(){
public void itemStateChnaged(ItemEvent e){
layout.show(panel, (string).getItem()); <-- show Panel from combobox
}
});
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String txt = text.getText();
newPanel.printText(txt); <-- Using method from other class
}
});
}
}
public class NewPanel extends JPanel {
public void printText(String text){ <-- method from other class
System.out.println(text);
}
}

How do I create 2 frames in Java and Link them together?

I just created a GUI, now I want to create another GUI and link both together.
So on the first GUI when the user selects 'next' button, the second GUI is displayed.
For this, do I have to create a new class and just create a GUI again?
Here is what I have now:
import java.awt.Color;
import javax.swing.*;
public class Wizard {
private JLabel lblPicture;
private JRadioButton btLdap, btKerbegos, btSpnego, btSaml2;
private JButton btNext;
private JPanel panel;
public static void main(String[] args) {
new Wizard();
}
public Wizard() {
JFrame frame = new JFrame("Wizard");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600,360);
frame.setVisible(true);
MyPanel();
RadioButtons();
Button();
Image();
groupButton();
frame.add(panel);
frame.setVisible(true);
}
public void MyPanel() {
panel = new JPanel();
panel.setLayout(null);}
public void RadioButtons() {
btLdap = new JRadioButton ("Ldap");
btLdap.setBounds(60,85,100,20);
panel.add(btLdap);
btKerbegos = new JRadioButton ("Kerbegos");
btKerbegos.setBounds(60,115,100,20);
panel.add(btKerbegos);
btSpnego =new JRadioButton("Spnego");
btSpnego.setBounds(60,145,100,20);
panel.add(btSpnego);
btSaml2 = new JRadioButton("Saml2");
btSaml2.setBounds(60,175,100,20);
panel.add(btSaml2);
}
public void Button() {
btNext = new JButton ("Next");
btNext.setBounds(400,260,100,20);
panel.add(btNext);
}
public void Image() {
ImageIcon image = new ImageIcon("image.jpg");
lblPicture = new JLabel(image);
lblPicture.setBounds(200,20, 330, 270);
panel.add(lblPicture);
}
private void groupButton() {
ButtonGroup bg1 = new ButtonGroup( );
bg1.add(btLdap);
bg1.add(btKerbegos);
bg1.add(btSpnego);
bg1.add(btSaml2);
}
}
To display another window, you would create the window, be it a JFrame, JDialog, or what have you, and call setVisible(true) just like you do for your first window.
You ask if your other "window" should be in another class, and likely that answer is yes. Since it will have a completely different set of behaviors and goals from the first class, better to separate out concerns.
Having said that, what you plan to do, to show multiple windows is not always the best user interface design. Better often is to show multiple views using a container that uses a CardLayout.
If you want to display another window in a modal fashion, that is, have the first window wait for the second window to be processed before allowing user interaction, the second window should be a modal JDialog or JOptionPane (a JDialog in disguise).
I think for what you want to achieve, the use of a CardLayout would be appropriate.
This enables you to have multiple panels within the one frame with only one panel visible at a time and has functionality to 'flip' through the panels like a 'deck of cards'. So on initialising your frame you create the panels you want, and specify which one to start at then your next button will go to the next panel in the list.
See the tutorial here there are also some video tutorials available on youtube.
Write the two GUI's in different classes. When you start your program, start the first GUI.
FirstGUI frame1 = new FirstGUI("Title text");
frame1.setVisible(true);
Then, in the action listener code for the button you call "next"...
frame1.setVisible(false); //if you want to save the frame
frame1.dispose(); //if you want to kill the frame
SecondGUI frame2 = new SecondGUI("Title text");
frame2.setVisible(true);

Categories

Resources