Java je moćan i univerzalni jezik koji je oblikovao svijet softverskog razvoja. Kroz godine, Java je postala ključna komponenta raznih aplikacija, od mobilnih uređaja do velikih poslovnih sustava.
Ovo su bilješke koje sam koristio i koje nadopunjavam…
Osnovno
App.java :
public class App { public static void main(String[] args) { System.out.println("Hello, World!"); } }
Build:
javac App.java
Run:
java App
Basic Linux project
Pripremi:
mkdir java-project cd java-project mkdir libs touch build-run.sh touch App.java
build-run.sh
#!/bin/bash find . -type f -name "*.class" -exec rm -f {} + javac -cp '.:libs/*' App.java java -cp '.:libs/*' App
App.java
import javax.swing.*; import java.awt.*; public class App { public static void main(String[] args) { System.out.println("Hello, World!"); } }
/libs – mjesto za jar datoteke
/ – ovdje pravimo datoteke s klasama
Dokumentacija
Java html dokumentacija se nalazi u “*javadoc.jar” datoteci. Potrebno je samo raspakirati jar:
jar xf moj-lib-javadoc.jar
Jar files
https://repo1.maven.org/maven2/com/
Data Strutures
Mixed data list
List<Object> mixedList = new ArrayList<>(); mixedList.add(42); mixedList.add("Hello"); // Retrieving elements with type casting int intValue = (int) mixedList.get(0); String stringValue = (String) mixedList.get(1);
Thread-safe associative list
import java.util.concurrent.ConcurrentHashMap; public class ThreadSafeHashMap { public static void main(String[] args) { // Create a ConcurrentHashMap with String keys and Object values ConcurrentHashMap<String, Object> concurrentMap = new ConcurrentHashMap<>(); // Adding mixed data types concurrentMap.put("name", "John"); concurrentMap.put("age", 30); concurrentMap.put("isStudent", true); // Retrieve values by key String name = (String) concurrentMap.get("name"); int age = (int) concurrentMap.get("age"); boolean isStudent = (boolean) concurrentMap.get("isStudent"); // Display the values System.out.println("Name: " + name); System.out.println("Age: " + age); System.out.println("Is Student: " + isStudent); } }
ArrayList
import java.util.ArrayList; public class ArrayListDemo { public static void main(String[] args) { // Create an ArrayList of integers ArrayList<Integer> numbers = new ArrayList<>(); // Add elements to the ArrayList numbers.add(1); numbers.add(2); numbers.add(3); numbers.add(4); numbers.add(5); // Access elements using index int secondElement = numbers.get(1); // This will be 2 // Modify an element by its index numbers.set(2, 30); // Replace the element at index 2 with 30 // Remove an element by its index numbers.remove(3); // Print the entire ArrayList for(int num : numbers) { System.out.println(num); } } }
Linked List
import java.util.LinkedList; public class LinkedListDemo { public static void main(String[] args) { // Create a LinkedList of integers LinkedList<Integer> numbers = new LinkedList<>(); // Add elements to the LinkedList numbers.add(10); numbers.add(20); numbers.add(30); numbers.add(40); numbers.add(50); // Add element at the beginning numbers.addFirst(5); // Add element at the end (similar to add method) numbers.addLast(60); // Access elements using index int thirdElement = numbers.get(2); // This will be 30 // Remove the first element numbers.removeFirst(); // Remove the last element numbers.removeLast(); // Print the entire LinkedList for(int num : numbers) { System.out.println(num); } } }
Vector
import java.util.Vector; public class VectorDemo { public static void main(String[] args) { // Create a Vector of integers Vector<Integer> numbers = new Vector<>(); // Add elements to the Vector numbers.add(100); numbers.add(200); numbers.add(300); numbers.add(400); numbers.add(500); // Add element at a specific index numbers.add(2, 250); // Add 250 at index 2 // Access elements using index int fourthElement = numbers.get(3); // This will be 300 // Remove an element by its index numbers.remove(1); // Removes the element at index 1 (200) // Check the size of the Vector int size = numbers.size(); // Print the entire Vector for(int num : numbers) { System.out.println(num); } } }
Stack
import java.util.Stack; public class StackDemo { public static void main(String[] args) { // Create a Stack of integers Stack<Integer> stack = new Stack<>(); // Push elements onto the stack stack.push(10); stack.push(20); stack.push(30); stack.push(40); stack.push(50); // Peek the top element without removing it int topElement = stack.peek(); // This will be 50 // Pop elements from the stack (removes and returns the top element) int poppedElement = stack.pop(); // This will remove and return 50 // Check if the stack is empty boolean isEmpty = stack.isEmpty(); // Print the entire stack while(!stack.isEmpty()) { System.out.println(stack.pop()); } } }
Hashset
import java.util.HashSet; public class HashSetDemo { public static void main(String[] args) { // Create a HashSet of integers HashSet<Integer> numbers = new HashSet<>(); // Add elements to the HashSet numbers.add(10); numbers.add(20); numbers.add(30); numbers.add(40); numbers.add(50); // Adding a duplicate value will not have any effect numbers.add(30); // This will not add a new entry // Check if the HashSet contains a specific value boolean contains30 = numbers.contains(30); // Remove an element numbers.remove(20); // Print the entire HashSet for(int num : numbers) { System.out.println(num); } } }
Linked hashset
import java.util.LinkedHashSet; public class LinkedHashSetDemo { public static void main(String[] args) { // Create a LinkedHashSet of integers LinkedHashSet<Integer> numbers = new LinkedHashSet<>(); // Add elements to the LinkedHashSet numbers.add(70); numbers.add(80); numbers.add(90); numbers.add(100); numbers.add(110); // Adding a duplicate value will not have any effect numbers.add(90); // This will not add a new entry // Since it's a LinkedHashSet, the insertion order is preserved // Remove an element numbers.remove(80); // Print the entire LinkedHashSet for(int num : numbers) { System.out.println(num); } } }
Treeset
import java.util.TreeSet; public class TreeSetDemo { public static void main(String[] args) { // Create a TreeSet of integers TreeSet<Integer> numbers = new TreeSet<>(); // Add elements to the TreeSet numbers.add(5); numbers.add(15); numbers.add(25); numbers.add(35); numbers.add(45); // Adding a duplicate value will not have any effect numbers.add(25); // This will not add a new entry // Retrieve the first (smallest) and last (largest) elements int firstElement = numbers.first(); int lastElement = numbers.last(); // Remove an element numbers.remove(15); // Print the entire TreeSet for(int num : numbers) { System.out.println(num); } } }
Hashmap
import java.util.HashMap; public class HashMapDemo { public static void main(String[] args) { // Create a HashMap with String keys and Integer values HashMap<String, Integer> scores = new HashMap<>(); // Add key-value pairs to the HashMap scores.put("Alice", 85); scores.put("Bob", 90); scores.put("Charlie", 95); scores.put("David", 88); // Get a value associated with a key int bobScore = scores.get("Bob"); // Modify a value associated with a key scores.put("Alice", 87); // Update Alice's score to 87 // Remove a key-value pair by key scores.remove("David"); // Check if the HashMap contains a specific key boolean hasCharlie = scores.containsKey("Charlie"); // Print the entire HashMap for(String name : scores.keySet()) { System.out.println(name + ": " + scores.get(name)); } } }
Linked hashmap
import java.util.LinkedHashMap; public class LinkedHashMapDemo { public static void main(String[] args) { // Create a LinkedHashMap with String keys and Integer values LinkedHashMap<String, Integer> ages = new LinkedHashMap<>(); // Add key-value pairs to the LinkedHashMap ages.put("John", 28); ages.put("Jane", 25); ages.put("Jim", 30); ages.put("Jill", 29); // Get a value associated with a key int jimAge = ages.get("Jim"); // Modify a value associated with a key ages.put("Jane", 26); // Update Jane's age to 26 // Remove a key-value pair by key ages.remove("Jill"); // Since it's a LinkedHashMap, the insertion order is preserved // Print the entire LinkedHashMap for(String name : ages.keySet()) { System.out.println(name + ": " + ages.get(name)); } } }
Treemap
import java.util.TreeMap; public class TreeMapDemo { public static void main(String[] args) { // Create a TreeMap with String keys and String values TreeMap<String, String> countriesCapitals = new TreeMap<>(); // Add key-value pairs to the TreeMap countriesCapitals.put("Germany", "Berlin"); countriesCapitals.put("France", "Paris"); countriesCapitals.put("Japan", "Tokyo"); countriesCapitals.put("USA", "Washington, D.C."); // Get a value associated with a key String capitalOfFrance = countriesCapitals.get("France"); // Modify a value associated with a key countriesCapitals.put("USA", "Washington"); // Remove a key-value pair by key countriesCapitals.remove("Japan"); // Since it's a TreeMap, the keys will be sorted // Print the entire TreeMap for(String country : countriesCapitals.keySet()) { System.out.println(country + ": " + countriesCapitals.get(country)); } } }
Hashtable
import java.util.Hashtable; public class HashtableDemo { public static void main(String[] args) { // Create a Hashtable with String keys and String values Hashtable<String, String> dictionary = new Hashtable<>(); // Add key-value pairs to the Hashtable dictionary.put("apple", "A fruit that is typically round and red or green."); dictionary.put("banana", "A long curved fruit with a yellow skin."); dictionary.put("cherry", "A small round fruit that is typically red or black."); dictionary.put("date", "A sweet brownish fruit from an Old World palm."); // Get a value associated with a key String definitionOfBanana = dictionary.get("banana"); // Modify a value associated with a key dictionary.put("apple", "A fruit that can be red, green, or yellow."); // Remove a key-value pair by key dictionary.remove("date"); // Print the entire Hashtable for(String word : dictionary.keySet()) { System.out.println(word + ": " + dictionary.get(word)); } } }
Priority queue
import java.util.PriorityQueue; public class PriorityQueueDemo { public static void main(String[] args) { // Create a PriorityQueue of integers PriorityQueue<Integer> queue = new PriorityQueue<>(); // Add elements to the PriorityQueue queue.add(50); queue.add(20); queue.add(70); queue.add(40); queue.add(30); // Peek the element with the highest priority (smallest in this case) int topPriorityElement = queue.peek(); // This will be 20 // Poll (remove and return) the element with the highest priority int polledElement = queue.poll(); // This will remove and return 20 // Print the entire PriorityQueue while(!queue.isEmpty()) { System.out.println(queue.poll()); } } }
ArrayDeque
import java.util.ArrayDeque; public class ArrayDequeDemo { public static void main(String[] args) { // Create an ArrayDeque of integers ArrayDeque<Integer> deque = new ArrayDeque<>(); // Add elements to the front and back of the deque deque.addFirst(10); deque.addLast(20); deque.addFirst(5); deque.addLast(30); // Peek elements from the front and back without removing int frontElement = deque.peekFirst(); // This will be 5 int backElement = deque.peekLast(); // This will be 30 // Poll (remove and return) elements from the front and back int frontPolled = deque.pollFirst(); // This will remove and return 5 int backPolled = deque.pollLast(); // This will remove and return 30 // Print the entire ArrayDeque while(!deque.isEmpty()) { System.out.println(deque.pollFirst()); } } }
BitSet
import java.util.BitSet; public class BitSetDemo { public static void main(String[] args) { // Create two BitSet instances BitSet bits1 = new BitSet(16); BitSet bits2 = new BitSet(16); // Set some bits for(int i = 0; i < 16; i++) { if(i % 2 == 0) bits1.set(i); if(i % 5 != 0) bits2.set(i); } // Display the initial patterns System.out.println("Initial pattern in bits1: " + bits1); System.out.println("Initial pattern in bits2: " + bits2); // Perform logical AND on bits bits2.and(bits1); System.out.println("\nbits2 AND bits1: " + bits2); // Perform logical OR on bits bits2.or(bits1); System.out.println("\nbits2 OR bits1: " + bits2); // Perform logical XOR on bits bits2.xor(bits1); System.out.println("\nbits2 XOR bits1: " + bits2); } }
EnumSet
import java.util.EnumSet; public class EnumSetDemo { // Define an enum type enum Days { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY } public static void main(String[] args) { // Create an EnumSet using noneOf method EnumSet<Days> weekend = EnumSet.noneOf(Days.class); weekend.add(Days.SATURDAY); weekend.add(Days.SUNDAY); // Display the weekend days System.out.println("Weekend days: " + weekend); // Create an EnumSet using range method EnumSet<Days> workWeek = EnumSet.range(Days.MONDAY, Days.FRIDAY); // Display the workweek days System.out.println("Workweek days: " + workWeek); // Create an EnumSet using complementOf method EnumSet<Days> notWeekend = EnumSet.complementOf(weekend); // Display the days that are not weekends System.out.println("Days that are not weekends: " + notWeekend); } }
EnumMap
import java.util.EnumMap; public class EnumMapDemo { // Define an enum type for days enum Days { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY } public static void main(String[] args) { // Create an EnumMap that maps days to activities EnumMap<Days, String> activityMap = new EnumMap<>(Days.class); // Populate the EnumMap with values activityMap.put(Days.MONDAY, "Work"); activityMap.put(Days.TUESDAY, "Gym"); activityMap.put(Days.WEDNESDAY, "Work"); activityMap.put(Days.THURSDAY, "Yoga"); activityMap.put(Days.FRIDAY, "Work"); activityMap.put(Days.SATURDAY, "Relax"); activityMap.put(Days.SUNDAY, "Hiking"); // Retrieve and display activities for each day for(Days day : Days.values()) { System.out.println(day + ": " + activityMap.get(day)); } } }
Object Container
import java.util.HashMap; import java.util.Map; public class ObjectContainer { private static ObjectContainer instance; private Map<String, Object> container = new HashMap<>(); private ObjectContainer() {} // Private constructor to prevent external instantiation public static ObjectContainer getInstance() { if (instance == null) { instance = new ObjectContainer(); } return instance; } public void register(String name, Object object) { container.put(name, object); } public Object resolve(String name) { return container.get(name); } public boolean isRegistered(String name) { return container.containsKey(name); } }
Swing
Hello world
import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.SwingUtilities; public class HelloWorldSwing { public static void main(String[] args) { SwingUtilities.invokeLater(() -> createAndShowGUI()); } private static void createAndShowGUI() { // Create and set up the window JFrame frame = new JFrame("HelloWorldSwing"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Add a "Hello World" label JLabel label = new JLabel("Hello World"); frame.getContentPane().add(label); // Display the window frame.pack(); frame.setVisible(true); } }
Swing Layouts
BorderLayout
import javax.swing.JFrame; import javax.swing.JButton; import javax.swing.SwingUtilities; import java.awt.BorderLayout; public class BorderLayoutDemo { public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame frame = new JFrame("BorderLayout Demo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300, 200); frame.add(new JButton("North"), BorderLayout.NORTH); frame.add(new JButton("South"), BorderLayout.SOUTH); frame.add(new JButton("East"), BorderLayout.EAST); frame.add(new JButton("West"), BorderLayout.WEST); frame.add(new JButton("Center"), BorderLayout.CENTER); frame.setVisible(true); }); } }
FlowLayout
import javax.swing.JFrame; import javax.swing.JButton; import javax.swing.SwingUtilities; import java.awt.FlowLayout; public class FlowLayoutDemo { public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame frame = new JFrame("FlowLayout Demo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300, 200); frame.setLayout(new FlowLayout()); frame.add(new JButton("Button 1")); frame.add(new JButton("Button 2")); frame.add(new JButton("Button 3")); frame.add(new JButton("Button 4")); frame.add(new JButton("Button 5")); frame.setVisible(true); }); } }
GridLayout
import javax.swing.JFrame; import javax.swing.JButton; import javax.swing.SwingUtilities; import java.awt.GridLayout; public class GridLayoutDemo { public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame frame = new JFrame("GridLayout Demo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300, 200); frame.setLayout(new GridLayout(2, 3)); // 2 rows, 3 columns frame.add(new JButton("Button 1")); frame.add(new JButton("Button 2")); frame.add(new JButton("Button 3")); frame.add(new JButton("Button 4")); frame.add(new JButton("Button 5")); frame.add(new JButton("Button 6")); frame.setVisible(true); }); } }
CardLayout
import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class CardLayoutDemo { public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame frame = new JFrame("CardLayout Demo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300, 200); // Create CardLayout and panels CardLayout cardLayout = new CardLayout(); JPanel cards = new JPanel(cardLayout); JPanel card1 = new JPanel(); card1.add(new JLabel("Card 1")); JButton nextBtn1 = new JButton("Next"); card1.add(nextBtn1); JPanel card2 = new JPanel(); card2.add(new JLabel("Card 2")); JButton nextBtn2 = new JButton("Next"); card2.add(nextBtn2); cards.add(card1, "FirstCard"); cards.add(card2, "SecondCard"); nextBtn1.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { cardLayout.show(cards, "SecondCard"); } }); nextBtn2.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { cardLayout.show(cards, "FirstCard"); } }); frame.add(cards); frame.setVisible(true); }); } }
GridBagLayout
import javax.swing.*; import java.awt.*; public class GridBagLayoutDemo { public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame frame = new JFrame("GridBagLayout Demo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(400, 300); frame.setLayout(new GridBagLayout()); GridBagConstraints constraints = new GridBagConstraints(); JButton btn1 = new JButton("Button 1"); constraints.gridx = 0; constraints.gridy = 0; frame.add(btn1, constraints); JButton btn2 = new JButton("Button 2"); constraints.gridx = 1; constraints.gridy = 0; frame.add(btn2, constraints); JButton btn3 = new JButton("Button 3"); constraints.gridx = 0; constraints.gridy = 1; constraints.gridwidth = 2; // span two columns constraints.fill = GridBagConstraints.HORIZONTAL; frame.add(btn3, constraints); frame.setVisible(true); }); } }
BoxLayout
import javax.swing.*; import java.awt.*; public class BoxLayoutDemo { public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame frame = new JFrame("BoxLayout Demo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300, 200); // Setting up BoxLayout for horizontal alignment JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS)); JButton btn1 = new JButton("Button 1"); JButton btn2 = new JButton("Button 2"); JButton btn3 = new JButton("Button 3"); panel.add(btn1); panel.add(Box.createRigidArea(new Dimension(10, 0))); // Adding space between buttons panel.add(btn2); panel.add(Box.createRigidArea(new Dimension(10, 0))); panel.add(btn3); frame.add(panel); frame.setVisible(true); }); } }
GroupLayout
import javax.swing.*; import java.awt.*; public class GroupLayoutDemo { public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame frame = new JFrame("GroupLayout Demo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300, 200); JPanel panel = new JPanel(); GroupLayout layout = new GroupLayout(panel); panel.setLayout(layout); JButton btn1 = new JButton("Button 1"); JButton btn2 = new JButton("Button 2"); JButton btn3 = new JButton("Button 3"); layout.setHorizontalGroup( layout.createSequentialGroup() .addComponent(btn1) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) .addComponent(btn2) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) .addComponent(btn3) ); layout.setVerticalGroup( layout.createSequentialGroup() .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE) .addComponent(btn1) .addComponent(btn2) .addComponent(btn3)) ); frame.add(panel); frame.setVisible(true); }); } }
SpringLayout
import javax.swing.*; import java.awt.*; public class SpringLayoutDemo { public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame frame = new JFrame("SpringLayout Demo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300, 200); SpringLayout layout = new SpringLayout(); JPanel panel = new JPanel(layout); JButton btn1 = new JButton("Button 1"); JButton btn2 = new JButton("Button 2"); panel.add(btn1); panel.add(btn2); // Set constraints for Button 1 layout.putConstraint(SpringLayout.WEST, btn1, 10, SpringLayout.WEST, panel); layout.putConstraint(SpringLayout.NORTH, btn1, 10, SpringLayout.NORTH, panel); // Set constraints for Button 2 relative to Button 1 layout.putConstraint(SpringLayout.WEST, btn2, 10, SpringLayout.EAST, btn1); layout.putConstraint(SpringLayout.NORTH, btn2, 0, SpringLayout.NORTH, btn1); frame.add(panel); frame.setVisible(true); }); } }
MigLayout
import javax.swing.*; import net.miginfocom.swing.MigLayout; public class MigLayoutDemo { public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame frame = new JFrame("MigLayout Demo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(400, 300); JPanel panel = new JPanel(new MigLayout()); JButton btn1 = new JButton("Button 1"); JButton btn2 = new JButton("Button 2"); JButton btn3 = new JButton("Button 3"); panel.add(btn1, "cell 0 0"); panel.add(btn2, "cell 1 0"); panel.add(btn3, "cell 1 1"); frame.add(panel); frame.setVisible(true); }); } }
Maven
<dependency> <groupId>com.miglayout</groupId> <artifactId>miglayout-swing</artifactId> <version>5.3</version> </dependency>
Gradle
dependencies { implementation 'com.miglayout:miglayout-swing:5.3' }
Jar: https://repo1.maven.org/maven2/com/miglayout/miglayout-swing/11.2/
Resources
Load text file
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class ReadFileExample { public static void main(String[] args) { String fileName = "hello.txt"; // File path can be absolute or relative to the project root try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) { String line; while ((line = reader.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } } }
Load image
import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; public class LoadImageIOExample { public static void main(String[] args) { try { File file = new File("path/to/your/image.jpg"); // Provide the path to your image file BufferedImage image = ImageIO.read(file); // At this point, 'image' contains the loaded image data // You can now work with the image (display it, manipulate it, etc.) } catch (IOException e) { e.printStackTrace(); } } }
Load font
import javax.swing.JFrame; import javax.swing.JLabel; import java.awt.Font; import java.awt.GraphicsEnvironment; import java.io.File; public class LoadFontExample { public static void main(String[] args) { try { // Load the font Font customFont = Font.createFont(Font.TRUETYPE_FONT, new File("path/to/your/font.ttf")).deriveFont(24f); // Adjust the font size // Register the font GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); ge.registerFont(customFont); // Use the font in a component JLabel label = new JLabel("Custom Font Example"); label.setFont(customFont); JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(label); frame.pack(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }
Terminal
Output
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class LinuxCommandExecutor { public static void main(String[] args) { // Example command: list files in the current directory String command = "ls"; ProcessBuilder processBuilder = new ProcessBuilder(); // If you want to execute the command in a specific directory, use: // processBuilder.directory(new File("/path/to/directory")); processBuilder.command("bash", "-c", command); try { Process process = processBuilder.start(); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } int exitCode = process.waitFor(); System.out.println("\nExited with error code : " + exitCode); } catch (IOException | InterruptedException e) { e.printStackTrace(); } } }