Related
The JTextArea named txtaObservation is occupying five horizontal slots of its container's GridBagLayout. Its text should wrap by when it reaches the fifth slot, below the label named lblObservationLimit, however it is wrapping too soon, just about in the first slot. How do I make it wrap at the correct slot?
JDViewCustomer.java
package test2;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.util.Objects;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
public class JDViewCustomer extends javax.swing.JDialog {
private static final long serialVersionUID = 1L;
private JTextArea txtaObservation;
private JPanel panelCustomerData;
private final CustomerData customerData;
private JLabel lblObservationLimit;
public JDViewCustomer(java.awt.Frame parent, boolean modal, CustomerData customerData) {
super(parent, modal);
this.customerData = Objects.requireNonNull(customerData);
getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
layoutCustomerDataSection();
addCustomerData();
initComponents();
}
public void layoutCustomerDataSection() {
panelCustomerData = new JPanel();
panelCustomerData.setBorder(new CompoundBorder(new LineBorder(new Color(0, 0, 0), 1, true), new EmptyBorder(10, 10, 10, 10)));
panelCustomerData.setBackground(Color.WHITE);
getContentPane().add(panelCustomerData);
GridBagLayout gbl_panelCustomerData = new GridBagLayout();
gbl_panelCustomerData.columnWidths = new int[]{58, 199, 38, 102, 27, 138, 0};
gbl_panelCustomerData.rowHeights = new int[]{0, 14, 0};
gbl_panelCustomerData.columnWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
gbl_panelCustomerData.rowWeights = new double[]{0.0, 0.0, Double.MIN_VALUE};
panelCustomerData.setLayout(gbl_panelCustomerData);
lblObservationLimit = new JLabel("Observation limit");
GridBagConstraints gbc_lblObservationLimit = new GridBagConstraints();
gbc_lblObservationLimit.insets = new Insets(0, 0, 5, 0);
gbc_lblObservationLimit.gridx = 5;
gbc_lblObservationLimit.gridy = 0;
panelCustomerData.add(lblObservationLimit, gbc_lblObservationLimit);
txtaObservation = new JTextArea("Observation text");
txtaObservation.setFont(new Font("Tahoma", Font.PLAIN, 11));
txtaObservation.setLineWrap(true);
txtaObservation.setWrapStyleWord(true);
GridBagConstraints gbc_txtaObservation = new GridBagConstraints();
gbc_txtaObservation.gridwidth = 5;
gbc_txtaObservation.anchor = GridBagConstraints.NORTHWEST;
gbc_txtaObservation.gridx = 1;
gbc_txtaObservation.gridy = 1;
panelCustomerData.add(txtaObservation, gbc_txtaObservation);
}
public void addCustomerData() {
txtaObservation.setText(customerData.getObservation());
}
private void initComponents() {
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("View customer");
pack();
setLocationRelativeTo(getParent());
}
}
CustomerData.java
package test2;
public class CustomerData {
private final String observation;
public CustomerData(String observation) {
this.observation = observation;
}
public String getObservation() {
return observation;
}
}
Test2.java
package test2;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class Test2 {
private static void createAndShowGUI() {
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
CustomerData customerData = new CustomerData("Testing a long observation text that should wrap only when reaching the observation limit.");
new JDViewCustomer(frame, true, customerData).setVisible(true);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Try this for JDViewCustomer.java -- comments are flagged with "// kwb". I didn't realize until just now that it was unofficially answered!
import java.awt.Color;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.util.Objects;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
public class JDViewCustomer extends javax.swing.JDialog {
private static final long serialVersionUID = 1L;
private JTextArea txtaObservation;
private JPanel panelCustomerData;
private final CustomerData customerData;
private JLabel lblObservationLimit;
public JDViewCustomer(java.awt.Frame parent, boolean modal, CustomerData customerData) {
super(parent, modal);
this.customerData = Objects.requireNonNull(customerData);
getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
layoutCustomerDataSection();
addCustomerData();
initComponents();
}
public void layoutCustomerDataSection() {
panelCustomerData = new JPanel();
panelCustomerData.setBorder(new CompoundBorder(new LineBorder(new Color(0, 0, 0), 1, true), new EmptyBorder(10, 10, 10, 10)));
panelCustomerData.setBackground(Color.WHITE);
getContentPane().add(panelCustomerData);
GridBagLayout gbl_panelCustomerData = new GridBagLayout();
gbl_panelCustomerData.columnWidths = new int[]{58, 199, 38, 102, 27, 138, 0};
gbl_panelCustomerData.rowHeights = new int[]{0, 14, 0};
gbl_panelCustomerData.columnWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
gbl_panelCustomerData.rowWeights = new double[]{0.0, 0.0, Double.MIN_VALUE};
panelCustomerData.setLayout(gbl_panelCustomerData);
lblObservationLimit = new JLabel("Observation limit");
GridBagConstraints gbc_lblObservationLimit = new GridBagConstraints();
gbc_lblObservationLimit.insets = new Insets(0, 0, 5, 0);
gbc_lblObservationLimit.gridx = 5;
gbc_lblObservationLimit.gridy = 0;
// kwb set gridheight to total number of rows
gbc_lblObservationLimit.gridheight = 2;
panelCustomerData.add(lblObservationLimit, gbc_lblObservationLimit);
txtaObservation = new JTextArea("Observation text");
// kwb just to help view issue
txtaObservation.setBorder(BorderFactory.createLineBorder(Color.blue));
txtaObservation.setFont(new Font("Tahoma", Font.PLAIN, 11));
txtaObservation.setLineWrap(true);
txtaObservation.setWrapStyleWord(true);
GridBagConstraints gbc_txtaObservation = new GridBagConstraints();
gbc_txtaObservation.gridwidth = 5;
gbc_txtaObservation.anchor = GridBagConstraints.NORTHWEST;
// kwb fill all available horizontal space
gbc_txtaObservation.fill = GridBagConstraints.HORIZONTAL;
// kwb change to start in column 0, adjust as necessary
gbc_txtaObservation.gridx = 0;
gbc_txtaObservation.gridy = 1;
panelCustomerData.add(txtaObservation, gbc_txtaObservation);
}
public void addCustomerData() {
txtaObservation.setText(customerData.getObservation());
}
private void initComponents() {
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("View customer");
pack();
setLocationRelativeTo(getParent());
}
}
I got 5 JTextareas that stand for output for the sorting I need help regarding displaying or appending iteration in each JTextArea to show the algorithm of sorting.
I have got values of { 5,3,9,7,1,8 }
JTextArea1 |3, 5, 7, 1, 8, 9|
JTextArea2 |3, 5, 1, 7, 8, 9|
JTextArea3 |3, 5, 1, 7, 8, 9|
JTextArea4 |1, 3, 5, 7, 8, 9|
JTextArea5 |1, 3, 5, 7, 8, 9|
My problem is how can I append those values in each textarea.
My code is too long, I'm sorry for that.
My code is not finished yet. I just ended on the button of ascbubble but it can run.
//importing needed packages
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Sorting extends JPanel
{
// String needed to contain the values then convert into int
int int1,int2,int3,int4,int5,temp;
String str1,str2,str3,str4,str5;
//Buttons needed
JButton ascbubble,descbubble,
ascballoon,descballoon,
clear;
//Output Area of the result sorting
JTextArea output1,output2,
output3,output4,
output5;
//Text Field for user to input numbers
JTextField input1,input2,
input3,input4,
input5;
Sorting()
{
//set color of the background
setBackground(Color.black);
//initialize JButton,JTextArea and JTextField
//JButton
ascbubble = new JButton("Ascending Bubble");
descbubble = new JButton("Descending Bubble");
ascballoon = new JButton("Ascending Balloon");
descballoon = new JButton("Descending Balloon");
clear = new JButton("Clear");
//JTextArea
output1 = new JTextArea(" ");
output2 = new JTextArea(" ");
output3 = new JTextArea(" ");
output4 = new JTextArea(" ");
output5 = new JTextArea(" ");
//JTextField
input1 = new JTextField("00");
input2 = new JTextField("00");
input3 = new JTextField("00");
input4 = new JTextField("00");
input5 = new JTextField("00");
//SetBounds
setLayout(null);
input1.setBounds(120, 50, 30, 20);
input2.setBounds(170, 50, 30, 20);
input3.setBounds(220, 50, 30, 20);
input4.setBounds(270, 50, 30, 20);
input5.setBounds(320, 50, 30, 20);
ascbubble.setBounds(50, 120, 150, 40);
descbubble.setBounds(50, 180, 150, 40);
clear.setBounds(210, 140, 100, 50);
ascballoon.setBounds(320, 120, 150, 40);
descballoon.setBounds(320, 180, 150, 40);
output1.setBounds(20, 300, 80, 100);
output2.setBounds(120, 300, 80, 100);
output3.setBounds(220, 300, 80, 100);
output4.setBounds(320, 300, 80, 100);
output5.setBounds(420, 300, 80, 100);
//add function to the buttons
thehandler handler = new thehandler();
ascbubble.addActionListener(handler);
descbubble.addActionListener(handler);
ascballoon.addActionListener(handler);
descballoon.addActionListener(handler);
//add to the frame
add(input1);
add(input2);
add(input3);
add(input4);
add(input5);
add(output1);
add(output2);
add(output3);
add(output4);
add(output5);
add(ascbubble);
add(descbubble);
add(ascballoon);
add(descballoon);
add(clear);
}
private class thehandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==ascbubble)
{
//input1
str1=input1.getText();
int1=Integer.parseInt(str1);
//input2
str2=input2.getText();
int2=Integer.parseInt(str2);
//input3
str3=input3.getText();
int3=Integer.parseInt(str3);
//input4
str4=input4.getText();
int4=Integer.parseInt(str4);
//input5
str5=input5.getText();
int5=Integer.parseInt(str5);
int contain[]={int1,int2,int3,int4,int5};
//formula for Buble Sort Ascending Order
for ( int pass = 1; pass < contain.length; pass++ )
{
for ( int i = 0; i < contain.length - pass; i++ )
{
if ( contain[ i ] > contain[ i + 1 ] )
{
temp = contain[ i ];
contain[ i ] = contain[ i + 1 ];
contain[ i + 1 ] = temp;
}
}
}
}
}
}
public static void main(String[]args)
{
JFrame frame = new JFrame("Sorting");
frame.add(new Sorting());
frame.setSize(550, 500);
frame.setVisible(true);
}
}
First of all, JTextArea has a simple append method, so you only need one. On each pass, you simply need to generate a new String which represents the current state of the array
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.StringJoiner;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Sort {
public static void main(String[] args) {
new Sort();
}
public Sort() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JTextField fieldValues;
private JTextArea fieldResults;
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.insets = new Insets(2, 2, 2, 2);
fieldValues = new JTextField(20);
fieldResults = new JTextArea(10, 20);
add(fieldValues, gbc);
JButton btn = new JButton("Sort");
add(btn, gbc);
add(new JScrollPane(fieldResults), gbc);
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String[] values = fieldValues.getText().split(",");
int[] contain = new int[values.length];
for (int index = 0; index < values.length; index++) {
contain[index] = Integer.parseInt(values[index].trim());
}
for (int pass = 1; pass < contain.length; pass++) {
for (int i = 0; i < contain.length - pass; i++) {
if (contain[i] > contain[i + 1]) {
int temp = contain[i];
contain[i] = contain[i + 1];
contain[i + 1] = temp;
StringJoiner sj = new StringJoiner(", ", "", "\n");
for (int value : contain) {
sj.add(Integer.toString(value));
}
fieldResults.append(sj.toString());
}
}
}
}
});
}
}
}
Now, the problem with this is, the larger the dataset, the more time it will take to sort, this will mean the UI will pause until the sort is completed
One solution would be to use a SwingWorker, for example...
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.List;
import java.util.StringJoiner;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingWorker;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Sort {
public static void main(String[] args) {
new Sort();
}
public Sort() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JTextField fieldValues;
private JTextArea fieldResults;
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.insets = new Insets(2, 2, 2, 2);
fieldValues = new JTextField(20);
fieldResults = new JTextArea(10, 20);
add(fieldValues, gbc);
JButton btn = new JButton("Sort");
add(btn, gbc);
add(new JScrollPane(fieldResults), gbc);
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
btn.setEnabled(false);
String text = fieldValues.getText();
SortWorker worker = new SortWorker(text);
worker.addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent evt) {
String name = evt.getPropertyName();
if ("state".equals(name)) {
if (worker.getState() == SwingWorker.StateValue.DONE) {
btn.setEnabled(true);
}
}
}
});
worker.execute();
}
});
}
public class SortWorker extends SwingWorker<int[], String> {
private String text;
public SortWorker(String text) {
this.text = text;
}
#Override
protected void process(List<String> chunks) {
for (String value : chunks) {
fieldResults.append(value);
}
}
#Override
protected int[] doInBackground() throws Exception {
String[] values = text.split(",");
int[] contain = new int[values.length];
for (int index = 0; index < values.length; index++) {
contain[index] = Integer.parseInt(values[index].trim());
}
for (int pass = 1; pass < contain.length; pass++) {
for (int i = 0; i < contain.length - pass; i++) {
if (contain[i] > contain[i + 1]) {
int temp = contain[i];
contain[i] = contain[i + 1];
contain[i + 1] = temp;
StringJoiner sj = new StringJoiner(", ", "", "\n");
for (int value : contain) {
sj.add(Integer.toString(value));
}
publish(sj.toString());
}
}
}
return contain;
}
}
}
}
Hi I am working on an innovation in my company to handle the hits from the server so for that user has to add the service names in my application which is of monitoring application. So i have kept a button which will give the jtextfields counting to 9 so during submit button, how will i get the values from all the textboxes, below is my code,
package com.Lawrence;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class Sample2 implements ActionListener
{
JFrame mainFrame;
static int count = 0;
static int width_textfield = 10;
static int height_textfield = 40;
static int height = 0;
JButton addTextField,submit;
JTextField virtualDirectories;
JLabel virtualDirectoriesName;
ArrayList<String> texts = new ArrayList<String>();
public Sample2()
{
mainFrame = new JFrame("Add Virtual Directory");
mainFrame.setSize(640,640);
mainFrame.setResizable(false);
mainFrame.setLayout(null);
addTextField = new JButton();
addTextField.setText("Add Virtual directory");
addTextField.setBounds(10, 10, 200, 25);
addTextField.addActionListener(this);
mainFrame.add(addTextField);
submit = new JButton();
submit.setText("Submit");
submit.setBounds(180, 560, 100, 25);
submit.addActionListener(this);
mainFrame.add(submit);
mainFrame.setVisible(true);
height = mainFrame.getHeight();
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand()== "Add Virtual directory")
{
if(height_textfield <= height-80)
{
virtualDirectoriesName = new JLabel("Virtual Directory"+"\t"+":");
virtualDirectoriesName.setBounds(10,height_textfield,200, 25);
mainFrame.add(virtualDirectoriesName);
virtualDirectories = new JTextField();
virtualDirectories.setBounds(150,height_textfield,200,25);
mainFrame.add(virtualDirectories);
texts.add(virtualDirectories.getText());
count++;
//width_textfield++;
height_textfield = height_textfield+60;
mainFrame.revalidate();
mainFrame.repaint();
//http://www.dreamincode.net/forums/topic/381446-getting-the-values-from-mutiple-textfields-in-java-swing/
}
else
{
JOptionPane.showMessageDialog(mainFrame, "can only add"+count+"virtual Directories");
}
}
if(e.getActionCommand() == "Submit")
{
ArrayList<String> texts = new ArrayList<String>();
for(int i = 0; i< count;i++)
{
texts.add(virtualDirectories.getText());
}
System.out.println(texts.size());
System.out.println(texts.toString());
}
}
}
So i need to get the values from those textboxes and add it to an arraylist and then processing it to enter into my server for parsing the log files.So please explain me how to do it
You could store every textfield into an arraylist, just like you did with the texts. Also, please take a look at how to use layout managers.
ArrayList<JTextField> fields = new ArrayList<JTextField>();
fields.add(virtualDirectories);
for (int i = 0; i < count; i++) {
texts.add(fields.get(i).getText());
}
Edit:
This is a version of your code using layout managers. (plus the lines above, of course)
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Sample2 implements ActionListener {
JFrame mainFrame;
JPanel bottom;
JPanel center;
JPanel centerPanel1;
JPanel centerPanel2;
static int count = 0;
static int width_textfield = 10;
static int height_textfield = 40;
static int height = 0;
JButton addTextField, submit;
JTextField virtualDirectories;
JLabel virtualDirectoriesName;
ArrayList<JTextField> fields = new ArrayList<JTextField>();
ArrayList<String> texts = new ArrayList<String>();
int maxFields = 10;
public Sample2() {
mainFrame = new JFrame("Add Virtual Directory");
mainFrame.setSize(640, 640);
mainFrame.setResizable(false);
addTextField = new JButton();
addTextField.setText("Add Virtual directory");
addTextField.setBounds(10, 10, 200, 25);
addTextField.addActionListener(this);
submit = new JButton();
submit.setText("Submit");
submit.setBounds(180, 560, 100, 25);
submit.addActionListener(this);
center = new JPanel(new GridLayout(1, 2));
centerPanel1 = new JPanel(new GridLayout(maxFields, 1, 0, 20));
centerPanel2 = new JPanel();
center.add(centerPanel1);
center.add(centerPanel2);
bottom = new JPanel(new FlowLayout());
bottom.add(addTextField);
bottom.add(submit);
mainFrame.getContentPane().add(bottom, BorderLayout.SOUTH);
mainFrame.getContentPane().add(center, BorderLayout.CENTER);
mainFrame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand() == "Add Virtual directory") {
if (count < maxFields) {
JPanel p = new JPanel(new GridLayout(1, 2));
virtualDirectoriesName = new JLabel("Virtual Directory" + "\t" + ":");
virtualDirectories = new JTextField();
p.add(virtualDirectoriesName);
p.add(virtualDirectories);
centerPanel1.add(p);
texts.add(virtualDirectories.getText());
fields.add(virtualDirectories);
count++;
// width_textfield++;
height_textfield = height_textfield + 60;
mainFrame.revalidate();
mainFrame.repaint();
// http://www.dreamincode.net/forums/topic/381446-getting-the-values-from-mutiple-textfields-in-java-swing/
} else {
JOptionPane.showMessageDialog(mainFrame, "can only add " + maxFields + " virtual Directories");
}
}
if (e.getActionCommand() == "Submit") {
ArrayList<String> texts = new ArrayList<String>();
for (int i = 0; i < count; i++) {
texts.add(fields.get(i).getText());
}
System.out.println(texts.size());
System.out.println(texts.toString());
}
}
public static void main(String[] args) {
new Sample2();
}
}
I'm just making a small application on window builder and need some help with it. I've made 2 frames individually and I don't know how to specify the action of the button in such a way that when I click on the 'next' botton in the first frame, I want it to move to the second frame.
Here's the source code for each file.
first.java
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.AbstractAction;
import java.awt.event.ActionEvent;
import javax.swing.Action;
import javax.swing.JTextArea;
import java.awt.Font;
import java.awt.event.ActionListener;
public class first extends JFrame {
private JPanel contentPane;
private final Action action = new SwingAction();
private final Action action_1 = new SwingAction();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
first frame = new first();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public first() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnNext = new JButton("Next");
btnNext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btnNext.setAction(action_1);
btnNext.setBounds(257, 228, 55, 23);
contentPane.add(btnNext);
JButton btnExit = new JButton("Exit");
btnExit.setBounds(344, 228, 51, 23);
contentPane.add(btnExit);
JRadioButton rdbtnAdd = new JRadioButton("Add");
rdbtnAdd.setBounds(27, 80, 109, 23);
contentPane.add(rdbtnAdd);
JRadioButton rdbtnDelete = new JRadioButton("Delete");
rdbtnDelete.setBounds(27, 130, 109, 23);
contentPane.add(rdbtnDelete);
JRadioButton rdbtnEdit = new JRadioButton("Edit");
rdbtnEdit.setBounds(27, 180, 109, 23);
contentPane.add(rdbtnEdit);
JLabel lblSelectAnOption = new JLabel("Select an Option");
lblSelectAnOption.setFont(new Font("Tahoma", Font.PLAIN, 14));
lblSelectAnOption.setBounds(27, 36, 121, 23);
contentPane.add(lblSelectAnOption);
}
private class SwingAction extends AbstractAction {
public SwingAction() {
putValue(NAME, "Next");
putValue(SHORT_DESCRIPTION, "Some short description");
}
public void actionPerformed(ActionEvent e) {
new second_add();
}
}
}
second.java
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JComboBox;
import javax.swing.AbstractAction;
import java.awt.event.ActionEvent;
import javax.swing.Action;
import java.awt.event.ActionListener;
public class second_add extends JFrame {
private JPanel contentPane;
private JTextField txtTypeYourQuestion;
private JTextField txtQuestionWeight;
private JTextField txtEnter;
private JTextField txtEnter_1;
private JTextField txtValue;
private JTextField txtValue_1;
private final Action action = new SwingAction();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
second_add frame = new second_add();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public second_add() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
txtTypeYourQuestion = new JTextField();
txtTypeYourQuestion.setBounds(22, 11, 177, 20);
txtTypeYourQuestion.setText("Type your Question Here");
contentPane.add(txtTypeYourQuestion);
txtTypeYourQuestion.setColumns(10);
txtQuestionWeight = new JTextField();
txtQuestionWeight.setBounds(209, 11, 86, 20);
txtQuestionWeight.setText("Question weight");
contentPane.add(txtQuestionWeight);
txtQuestionWeight.setColumns(10);
txtEnter = new JTextField();
txtEnter.setBounds(22, 55, 86, 20);
txtEnter.setText("Enter . . .");
contentPane.add(txtEnter);
txtEnter.setColumns(10);
txtEnter_1 = new JTextField();
txtEnter_1.setText("Enter . . . ");
txtEnter_1.setBounds(22, 104, 86, 20);
contentPane.add(txtEnter_1);
txtEnter_1.setColumns(10);
txtValue = new JTextField();
txtValue.setText("Value . .");
txtValue.setBounds(118, 55, 51, 20);
contentPane.add(txtValue);
txtValue.setColumns(10);
txtValue_1 = new JTextField();
txtValue_1.setText("Value . .");
txtValue_1.setBounds(118, 104, 51, 20);
contentPane.add(txtValue_1);
txtValue_1.setColumns(10);
JButton btnFinish = new JButton("Finish");
btnFinish.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnFinish.setAction(action);
btnFinish.setBounds(335, 228, 89, 23);
contentPane.add(btnFinish);
JButton btnAddChoice = new JButton("Add choice");
btnAddChoice.setBounds(236, 228, 89, 23);
contentPane.add(btnAddChoice);
JButton btnAddQuestion = new JButton("Add question");
btnAddQuestion.setBounds(136, 228, 89, 23);
contentPane.add(btnAddQuestion);
}
private class SwingAction extends AbstractAction {
public SwingAction() {
putValue(NAME, "");
putValue(SHORT_DESCRIPTION, "Some short description");
}
public void actionPerformed(ActionEvent e) {
}
}
}
Having multiple JFrame instances in one application is bad usability
Consider using something like a CardLayout instead.
Modify like this-
JButton btnNext = new JButton("Next");
btnNext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
second_add second = new second_add();
setVisible(false); // Hide current frame
second.setVisible(true);
}
});
You can navigate to a frame by creating its object and using setVisible method to display it. If you want to do it on a button click, write it inside its event handler.
JFrame o = new JFrame();
o.setVisible(true);
dispose(); // This will close the current frame
The quick and dirty solution would to set the first frame's visibility to false and the second frames visibility to true in your buttonclick action. (see Sajal Dutta's answer)
But to have a consistent behaviour even for more than 2 frames, let each frame be stored in a HashTable in your main class (class holding the main method and not extending JFrame) with the ID being the order of the frame (first frame D 1, second: ID 2, etc.).
Then create a static method
public void switchFrame(JFrame originatingFrame, int NextFrame){
originatingFrame.this.setVisible(false);
((JFrame) myHashTable.get(NextFrame)).setVisible(true);
}
in your main class which can be called from each frame using
mainClass.switchFrame(this, IdOfFrameYouWantToGoTo);
that way you can also implement "Back"- and "Skip"-Buttons should you want to create something like a wizard.
NOTE: I did not test this code. This should just be seen as a general overview of how to do this.
The below piece of code will show to navigate from one page to another page in a menu format.
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.CardLayout;
import java.awt.Container;
import java.awt.GraphicsEnvironment;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.Panel;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class AddressBookDemo implements ActionListener, Runnable {
ArrayList personsList;
PersonDAO pDAO;
Panel panel;
JFrame appFrame;
JLabel jlbName, jblPassword, jlbAddress;
JPasswordField jPassword;
JTextField jtfName, jtfAddress;
JButton jbbSave, jbnClear, jbnExit, btnNext, button;
String name, address, password;
final int CARDS = 4;
CardLayout cl = new CardLayout();
JPanel cardPanel = new JPanel(cl);
CardLayout c2 = new CardLayout();
JPanel cardPanel2 = new JPanel(c2);
int currentlyShowing = 0;
Thread errorThrower;
// int phone;
// int recordNumber; // used to naviagate using >> and buttons
Container cPane;
Container cPane2;
private JFrame frame;
private TextArea textArea;
private Thread reader;
private Thread reader2;
private boolean quit;
private final PipedInputStream pin = new PipedInputStream();
private final PipedInputStream pin2 = new PipedInputStream();
public static void main(String args[]) {
new AddressBookDemo();
}
public AddressBookDemo() {
name = "";
password = "";
address = "";
// phone = -1; //Stores 0 to indicate no Phone Number
// recordNumber = -1;
createGUI();
personsList = new ArrayList();
// creating PersonDAO object
pDAO = new PersonDAO();
}
public void createGUI() {
/* Create a frame, get its contentpane and set layout */
appFrame = new JFrame("ManualDeploy ");
cPane = appFrame.getContentPane();
cPane.setLayout(new GridBagLayout());
// frame=new JFrame("Java Console");
textArea=new TextArea();
textArea.setEditable(false);
Button button=new Button("clear");
panel=new Panel();
panel.setLayout(new GridBagLayout());
GridBagConstraints gridBagConstraintsx01 = new GridBagConstraints();
gridBagConstraintsx01.gridx = 0;
gridBagConstraintsx01.gridy = 0;
gridBagConstraintsx01.insets = new Insets(5, 5, 5, 5);
panel.add(textArea,gridBagConstraintsx01);
GridBagConstraints gridBagConstraintsx03 = new GridBagConstraints();
gridBagConstraintsx03.gridx = 0;
gridBagConstraintsx03.insets = new Insets(5, 5, 5, 5);
gridBagConstraintsx03.gridy = 1;
panel.add(button,gridBagConstraintsx03);
// frame.add(panel);
// frame.setVisible(true);
// cPane2 = frame.getContentPane();
// cPane2.setLayout(new GridBagLayout());
button.addActionListener(this);
try
{
PipedOutputStream pout=new PipedOutputStream(this.pin);
System.setOut(new PrintStream(pout,true));
}
catch (java.io.IOException io)
{
textArea.append("Couldn't redirect STDOUT to this console\n"+io.getMessage());
}
catch (SecurityException se)
{
textArea.append("Couldn't redirect STDOUT to this console\n"+se.getMessage());
}
try
{
PipedOutputStream pout2=new PipedOutputStream(this.pin2);
System.setErr(new PrintStream(pout2,true));
}
catch (java.io.IOException io)
{
textArea.append("Couldn't redirect STDERR to this console\n"+io.getMessage());
}
catch (SecurityException se)
{
textArea.append("Couldn't redirect STDERR to this console\n"+se.getMessage());
}
quit=false; // signals the Threads that they should exit
// Starting two seperate threads to read from the PipedInputStreams
//
reader=new Thread(this);
reader.setDaemon(true);
reader.start();
//
reader2=new Thread(this);
reader2.setDaemon(true);
reader2.start();
// testing part
// you may omit this part for your application
//
System.out.println("Hello World 2");
System.out.println("All fonts available to Graphic2D:\n");
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fontNames=ge.getAvailableFontFamilyNames();
for(int n=0;n<fontNames.length;n++) System.out.println(fontNames[n]);
// Testing part: simple an error thrown anywhere in this JVM will be printed on the Console
// We do it with a seperate Thread becasue we don't wan't to break a Thread used by the Console.
System.out.println("\nLets throw an error on this console");
errorThrower=new Thread(this);
errorThrower.setDaemon(true);
errorThrower.start();
arrangeComponents();
// arrangeComponents2();
final int CARDS = 2;
final CardLayout cl = new CardLayout();
final JPanel cardPanel = new JPanel(cl);
JMenu menu = new JMenu("M");
for (int x = 0; x < CARDS; x++) {
final int SELECTION = x;
JPanel jp = new JPanel();
if (x == 0) {
jp.add(cPane);
} else if (x == 1) {
jp.add(panel);
} else if (x == 2)
jp.add(new JButton("Panel 2"));
else
jp.add(new JComboBox(new String[] { "Panel 3" }));
cardPanel.add("" + SELECTION, jp);
JMenuItem menuItem = new JMenuItem("Show Panel " + x);
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
currentlyShowing = SELECTION;
cl.show(cardPanel, "" + SELECTION);
}
});
menu.add(menuItem);
}
JMenuBar menuBar = new JMenuBar();
menuBar.add(menu);
btnNext = new JButton("Next >>");
JButton btnPrev = new JButton("<< Previous");
JPanel p = new JPanel(new GridLayout(1, 2));
p.add(btnPrev);
p.add(btnNext);
btnNext.setVisible(false);
JFrame f = new JFrame();
f.getContentPane().add(cardPanel);
f.getContentPane().add(p, BorderLayout.SOUTH);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(500, 500);
f.setLocationRelativeTo(null);
f.setJMenuBar(menuBar);
f.setVisible(true);
btnNext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (currentlyShowing < CARDS - 1) {
cl.next(cardPanel);
currentlyShowing++;
}
}
});
btnPrev.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (currentlyShowing > 0) {
cl.previous(cardPanel);
currentlyShowing--;
}
}
});
}
public void arrangeComponents() {
jlbName = new JLabel("Username");
jblPassword = new JLabel("Password");
jlbAddress = new JLabel("Sftpserver");
jtfName = new JTextField(20);
jPassword = new JPasswordField(20);
jtfAddress = new JTextField(20);
jbbSave = new JButton("move sftp");
jbnClear = new JButton("Clear");
jbnExit = new JButton("Exit");
/* add all initialized components to the container */
GridBagConstraints gridBagConstraintsx01 = new GridBagConstraints();
gridBagConstraintsx01.gridx = 0;
gridBagConstraintsx01.gridy = 0;
gridBagConstraintsx01.insets = new Insets(5, 5, 5, 5);
cPane.add(jlbName, gridBagConstraintsx01);
GridBagConstraints gridBagConstraintsx02 = new GridBagConstraints();
gridBagConstraintsx02.gridx = 1;
gridBagConstraintsx02.insets = new Insets(5, 5, 5, 5);
gridBagConstraintsx02.gridy = 0;
gridBagConstraintsx02.gridwidth = 2;
gridBagConstraintsx02.fill = GridBagConstraints.BOTH;
cPane.add(jtfName, gridBagConstraintsx02);
GridBagConstraints gridBagConstraintsx03 = new GridBagConstraints();
gridBagConstraintsx03.gridx = 0;
gridBagConstraintsx03.insets = new Insets(5, 5, 5, 5);
gridBagConstraintsx03.gridy = 1;
cPane.add(jblPassword, gridBagConstraintsx03);
GridBagConstraints gridBagConstraintsx04 = new GridBagConstraints();
gridBagConstraintsx04.gridx = 1;
gridBagConstraintsx04.insets = new Insets(5, 5, 5, 5);
gridBagConstraintsx04.gridy = 1;
gridBagConstraintsx04.gridwidth = 2;
gridBagConstraintsx04.fill = GridBagConstraints.BOTH;
cPane.add(jPassword, gridBagConstraintsx04);
GridBagConstraints gridBagConstraintsx05 = new GridBagConstraints();
gridBagConstraintsx05.gridx = 0;
gridBagConstraintsx05.insets = new Insets(5, 5, 5, 5);
gridBagConstraintsx05.gridy = 2;
cPane.add(jlbAddress, gridBagConstraintsx05);
GridBagConstraints gridBagConstraintsx06 = new GridBagConstraints();
gridBagConstraintsx06.gridx = 1;
gridBagConstraintsx06.gridy = 2;
gridBagConstraintsx06.insets = new Insets(5, 5, 5, 5);
gridBagConstraintsx06.gridwidth = 2;
gridBagConstraintsx06.fill = GridBagConstraints.BOTH;
cPane.add(jtfAddress, gridBagConstraintsx06);
GridBagConstraints gridBagConstraintsx09 = new GridBagConstraints();
gridBagConstraintsx09.gridx = 0;
gridBagConstraintsx09.gridy = 4;
gridBagConstraintsx09.insets = new Insets(5, 5, 5, 5);
cPane.add(jbbSave, gridBagConstraintsx09);
GridBagConstraints gridBagConstraintsx10 = new GridBagConstraints();
gridBagConstraintsx10.gridx = 1;
gridBagConstraintsx10.gridy = 4;
gridBagConstraintsx10.insets = new Insets(5, 5, 5, 5);
cPane.add(jbnClear, gridBagConstraintsx10);
GridBagConstraints gridBagConstraintsx11 = new GridBagConstraints();
gridBagConstraintsx11.gridx = 2;
gridBagConstraintsx11.gridy = 4;
gridBagConstraintsx11.insets = new Insets(5, 5, 5, 5);
cPane.add(jbnExit, gridBagConstraintsx11);
jbbSave.addActionListener(this);
// jbnDelete.addActionListener(this);
jbnClear.addActionListener(this);
jbnExit.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
System.out.println("inside button123");
if (e.getSource() == jbbSave) {
savePerson();
} else if (e.getSource() == jbnClear) {
clear();
} else if (e.getSource() == jbnExit) {
System.exit(0);
}
else if (e.getSource() == button)
{
System.out.println("inside button");
textArea.setText(" ");
}
}
// Save the Person into the Address Book
public void savePerson() {
name = jtfName.getText();
password = jPassword.getText();
address = jtfAddress.getText();
if (name.equals("")) {
JOptionPane.showMessageDialog(null, "Please enter password",
"ERROR", JOptionPane.ERROR_MESSAGE);
} else if (password != null && password.isEmpty()) {
JOptionPane.showMessageDialog(null, "Please enter password",
"ERROR", JOptionPane.ERROR_MESSAGE);
}
else {
btnNext.setVisible(true);
JOptionPane.showMessageDialog(null, "Person Saved");
}
}
public void clear() {
jtfName.setText("");
jPassword.setText("");
jtfAddress.setText("");
personsList.clear();
}
public synchronized void run()
{
try
{
while (Thread.currentThread()==reader)
{
try { this.wait(100);}catch(InterruptedException ie) {}
if (pin.available()!=0)
{
String input=this.readLine(pin);
textArea.append(input);
}
if (quit) return;
}
while (Thread.currentThread()==reader2)
{
try { this.wait(100);}catch(InterruptedException ie) {}
if (pin2.available()!=0)
{
String input=this.readLine(pin2);
textArea.append(input);
}
if (quit) return;
}
} catch (Exception e)
{
textArea.append("\nConsole reports an Internal error.");
textArea.append("The error is: "+e);
}
// just for testing (Throw a Nullpointer after 1 second)
// if (Thread.currentThread()==errorThrower)
// {
// try { this.wait(1000); }catch(InterruptedException ie){}
// throw new NullPointerException("Application test: throwing an NullPointerException It should arrive at the console");
// }
}
public synchronized String readLine(PipedInputStream in) throws IOException
{
String input="";
do
{
int available=in.available();
if (available==0) break;
byte b[]=new byte[available];
in.read(b);
input=input+new String(b,0,b.length);
}while( !input.endsWith("\n") && !input.endsWith("\r\n") && !quit);
return input;
}
public synchronized void windowClosed(WindowEvent evt)
{
quit=true;
this.notifyAll(); // stop all threads
try { reader.join(1000);pin.close(); } catch (Exception e){}
try { reader2.join(1000);pin2.close(); } catch (Exception e){}
System.exit(0);
}
}
I don't know why my scroll bar in text area doesn't work. I found many solutions in internet, but no 1 helped for me.
textArea1 = new JTextArea();
textArea1.setBounds(13, 28, 182, 199);
panel.add(textArea1);
JScrollBar scrollBar = new JScrollBar();
scrollBar.setBounds(205, 1, 17, 242);
panel.add(scrollBar);
I found that can't be Panel's layout Absolute, if I change It to Group layout the same.
What's wrong? Could you help me? Thank you.
UPDATED:
package lt.kvk.i3_2.kalasnikovas_stanislovas;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.JTextPane;
import javax.swing.DropMode;
import javax.swing.JFormattedTextField;
import java.awt.Component;
import javax.swing.Box;
import java.awt.Dimension;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Toolkit;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JMenuItem;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.ImageIcon;
import javax.swing.JDesktopPane;
import java.awt.SystemColor;
import java.awt.Font;
import javax.swing.border.BevelBorder;
import javax.swing.border.EtchedBorder;
import javax.swing.JScrollBar;
import java.awt.Color;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
import javax.swing.JLabel;
import javax.swing.JToolBar;
public class KDVizualizuotas {
private JFrame frmInformacijaApieMuzikos;
private JTextField txtStilius;
private JTextArea textArea1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
KDVizualizuotas window = new KDVizualizuotas();
window.frmInformacijaApieMuzikos.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public KDVizualizuotas() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmInformacijaApieMuzikos = new JFrame();
frmInformacijaApieMuzikos.setResizable(false);
frmInformacijaApieMuzikos.setIconImage(Toolkit.getDefaultToolkit().getImage(KDVizualizuotas.class.getResource("/lt/kvk/i3_2/kalasnikovas_stanislovas/resources/Sidebar-Music-Blue-icon.png")));
frmInformacijaApieMuzikos.setTitle("Muzikos stiliai");
frmInformacijaApieMuzikos.setBounds(100, 100, 262, 368);
frmInformacijaApieMuzikos.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
txtStilius = new JTextField();
txtStilius.setBounds(10, 34, 128, 20);
txtStilius.setColumns(10);
JButton btnIekoti = new JButton("Ie\u0161koti");
btnIekoti.setBounds(146, 36, 89, 19);
btnIekoti.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// textArea1.append(txtStilius.getText()+"\n");
// txtStilius.getText();
Scanner input = new Scanner(System.in);
try {
FileReader fr = new FileReader("src/lt/kvk/i3_2/kalasnikovas_stanislovas/Stiliai.txt");
BufferedReader br = new BufferedReader(fr);
String stiliuSarasas;
while((stiliuSarasas = br.readLine()) != null) {
System.out.println(stiliuSarasas);
textArea1.append(stiliuSarasas+"\n");
}
fr.close();
}
catch (IOException e) {
System.out.println("Error:" + e.toString());
}
}
});
JPanel panel = new JPanel();
panel.setBounds(10, 65, 224, 243);
panel.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));
panel.setBackground(SystemColor.text);
JLabel lblveskiteMuzikosStili = new JLabel("\u012Eveskite muzikos stili\u0173:");
lblveskiteMuzikosStili.setBounds(10, 14, 222, 14);
frmInformacijaApieMuzikos.getContentPane().setLayout(null);
panel.setLayout(null);
frmInformacijaApieMuzikos.getContentPane().add(panel);
JLabel lblInformacijaApieMuzikos = new JLabel("Informacija apie muzikos stili\u0173:");
lblInformacijaApieMuzikos.setBounds(12, 3, 190, 14);
panel.add(lblInformacijaApieMuzikos);
textArea1 = new JTextArea();
textArea1.setBounds(13, 28, 182, 199);
panel.add(textArea1);
JScrollBar scrollBar = new JScrollBar();
scrollBar.setBounds(205, 1, 17, 242);
panel.add(scrollBar);
frmInformacijaApieMuzikos.getContentPane().add(txtStilius);
frmInformacijaApieMuzikos.getContentPane().add(btnIekoti);
frmInformacijaApieMuzikos.getContentPane().add(lblveskiteMuzikosStili);
JMenuBar menuBar = new JMenuBar();
frmInformacijaApieMuzikos.setJMenuBar(menuBar);
JMenu mnFile = new JMenu("File");
menuBar.add(mnFile);
JMenuItem mntmExit = new JMenuItem("Exit");
mntmExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
mntmExit.setIcon(new ImageIcon(KDVizualizuotas.class.getResource("/lt/kvk/i3_2/kalasnikovas_stanislovas/resources/exitas.png")));
mnFile.add(mntmExit);
JMenu mnEdit = new JMenu("Edit");
menuBar.add(mnEdit);
JMenu mnHelp = new JMenu("Help");
menuBar.add(mnHelp);
JMenuItem mntmHelp = new JMenuItem("Help");
mnHelp.add(mntmHelp);
JMenu mnAbout = new JMenu("About");
menuBar.add(mnAbout);
JMenuItem mntmAbout = new JMenuItem("About");
mntmAbout.setIcon(new ImageIcon(KDVizualizuotas.class.getResource("/lt/kvk/i3_2/kalasnikovas_stanislovas/resources/questionmark.png")));
mnAbout.add(mntmAbout);
}
}
You need to add the component you want to be contained within the scroll pane to it.
You can do this via the JScrollPane's constructor or JScrollPane#setViewportView method
public class ScrollPaneTest {
public static void main(String[] args) {
new ScrollPaneTest();
}
public ScrollPaneTest() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
JPanel bigPane = new JPanel();
bigPane.setBackground(Color.BLUE);
// This is not recommended, but is used for demonstration purposes
bigPane.setPreferredSize(new Dimension(1024, 768));
JScrollPane scrollPane = new JScrollPane(bigPane);
scrollPane.setPreferredSize(new Dimension(400, 400));
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(scrollPane);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
Updated with proper layout
You should avoid null or absolute layouts, they will only hurt you in the long wrong.
You may also find How to use Scroll Panes of use
public class BadLayout {
public static void main(String[] args) {
new BadLayout();
}
public BadLayout() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JTextField searchField;
private JButton searchButton;
private JTextArea searchResults;
public TestPane() {
setLayout(new BorderLayout());
searchResults = new JTextArea();
searchResults.setLineWrap(true);
searchResults.setWrapStyleWord(true);
JScrollPane scrollPane = new JScrollPane(searchResults);
JPanel results = new JPanel(new BorderLayout());
results.setBorder(new EmptyBorder(4, 8, 8, 8));
results.add(scrollPane);
add(results);
JPanel search = new JPanel(new GridBagLayout());
search.setBorder(new EmptyBorder(8, 8, 4, 8));
searchField = new JTextField(12);
searchButton = new JButton("Search");
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1;
gbc.insets = new Insets(0, 0, 0, 4);
search.add(searchField, gbc);
gbc.insets = new Insets(0, 0, 0, 0);
gbc.gridx++;
gbc.fill = GridBagConstraints.NONE;
gbc.weightx = 0;
search.add(searchButton, gbc);
add(search, BorderLayout.NORTH);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 400);
}
}
}