gpt4 book ai didi

java - 简单的 GUI 指导。我可以坚持使用 BorderLayout 还是需要其他东西?

转载 作者:行者123 更新时间:2023-11-29 05:12:51 24 4
gpt4 key购买 nike

我正在尝试为个人项目创建 GUI。我有一个文件选择器、一个控制台区域、一个文本字段(带有标签)、一个按钮面板(2 个按钮),最后是一个“拖放区”区域。

GUI 垂直分成两半,右侧是控制台。在左上角,我将 FileChooser 定位在 BorderLayout.CENTER,然后是 ButtonPanel 在 BorderLayout.SOUTH。

下面是“拖放区”

目前看起来像这样:

 _________________
| file | console|
| chooser| |
| buttons| |
|--------| |
| drop | |
| zone | |
|________|________|

我想在文件选择器和按钮面板之间添加一个新的文本字段,但是当我将文件选择器更改为 NORTH,将 jtextfield 更改为 CENTER 并将按钮更改为 SOUTH 时,文件选择器非常小而 jtextfield 太大了.我认为这只是由于 BorderLayout 的固有属性,但我不确定。我应该使用不同的布局吗?我会做出什么样的改变?

我在下面包含了我正在使用的代码。提前感谢您的帮助!

import java.awt.datatransfer.*;
import java.awt.event.*;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.io.*;

import javax.swing.*;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.border.TitledBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.filechooser.FileSystemView;
import javax.swing.text.*;
import java.util.*;
import java.nio.*;

public class ConsolidatorDemo extends JPanel implements ActionListener {
JFileChooser fc;
JButton clear;
JButton ok;
JTextArea console;

JList<File> dropZone;
DefaultListModel listModel;
JSplitPane childSplitPane, parentSplitPane;
PrintStream ps;

JTextField wordCount;
JLabel lblCount;

public ConsolidatorDemo() {
super(new BorderLayout());
fc = new JFileChooser();;
fc.setMultiSelectionEnabled(true);
fc.setDragEnabled(true);
fc.setControlButtonsAreShown(false);
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);


JPanel fcPanel = new JPanel(new BorderLayout());
fcPanel.add(fc, BorderLayout.CENTER);

clear = new JButton("Clear All");
clear.addActionListener(this);

JPanel buttonPanel = new JPanel(new BorderLayout());
buttonPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
buttonPanel.add(clear, BorderLayout.LINE_END);

ok = new JButton("OK");
ok.addActionListener(this);
buttonPanel.add(ok, BorderLayout.WEST);

JPanel sizePanel = new JPanel(new BorderLayout());
sizePanel.setBorder(BorderFactory.createEmptyBorder(20,20,20,20));

wordCount = new JTextField();
sizePanel.add(wordCount, BorderLayout.LINE_END);

// lblCount = new JLabel("Word Counter");
// buttonPanel.add(lblCount, BorderLayout.CENTER);

JPanel leftUpperPanel = new JPanel(new BorderLayout());
leftUpperPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
leftUpperPanel.add(fcPanel, BorderLayout.NORTH);
leftUpperPanel.add(sizePanel, BorderLayout.CENTER);
leftUpperPanel.add(buttonPanel, BorderLayout.PAGE_END);

JScrollPane leftLowerPanel = new javax.swing.JScrollPane();
leftLowerPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));

listModel = new DefaultListModel();
dropZone = new JList(listModel);
dropZone.setCellRenderer(new FileCellRenderer());
dropZone.setTransferHandler(new ListTransferHandler(dropZone));
dropZone.setDragEnabled(true);
dropZone.setDropMode(javax.swing.DropMode.INSERT);
dropZone.setBorder(new TitledBorder("Selected files/folders"));
leftLowerPanel.setViewportView(new JScrollPane(dropZone));

childSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
leftUpperPanel, leftLowerPanel);
childSplitPane.setDividerLocation(400);
childSplitPane.setPreferredSize(new Dimension(480, 650));

console = new JTextArea();
console.setColumns(40);
console.setLineWrap(true);
console.setBorder(new TitledBorder("Console"));

parentSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
childSplitPane, console);
parentSplitPane.setDividerLocation(480);
parentSplitPane.setPreferredSize(new Dimension(800, 650));

add(parentSplitPane, BorderLayout.CENTER);

this.redirectSystemStreams();

}
private void updateTextArea(final String text) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
console.append(text);
}
});
}

private void redirectSystemStreams() {
OutputStream out = new OutputStream() {
@Override
public void write(int b) throws IOException {
updateTextArea(String.valueOf((char) b));
}

@Override
public void write(byte[] b, int off, int len) throws IOException {
updateTextArea(new String(b, off, len));
}

@Override
public void write(byte[] b) throws IOException {
write(b, 0, b.length);
}
};

System.setOut(new PrintStream(out, true));
System.setErr(new PrintStream(out, true));
}


public void setDefaultButton() {
getRootPane().setDefaultButton(ok);
}

public void actionPerformed(ActionEvent e) {
if (e.getSource() == clear) {
listModel.clear();
}
if(e.getSource() == ok){
try{
if(dropZone.isSelectionEmpty() == true){
int start = 0;
int end = dropZone.getModel().getSize() - 1;
if (end >= 0) {
dropZone.setSelectionInterval(start, end);
}
}
List<File> list = dropZone.getSelectedValuesList();
for (File file : list) {
//StringEditing.editDocument(file, Integer.parseInt(wordCount.getText()));
}
}
catch(NumberFormatException nfe){
System.out.println("You did not input a number");
}
catch(Exception ef){
System.out.println("Something is wrong!");
}
}
}


/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Make sure we have nice window decorations.
JFrame.setDefaultLookAndFeelDecorated(true);
try {
//UIManager.setLookAndFeel("de.javasoft.plaf.synthetica.SyntheticaBlackStarLookAndFeel");
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
}catch (Exception e){
e.printStackTrace();
}

//Create and set up the window.
JFrame frame = new JFrame("Consolidator!");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

//Create and set up the menu bar and content pane.
ConsolidatorDemo demo = new ConsolidatorDemo();
demo.setOpaque(true); //content panes must be opaque
frame.setContentPane(demo);

//Display the window.
frame.pack();
frame.setVisible(true);
demo.setDefaultButton();
}

public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}

class FileCellRenderer extends DefaultListCellRenderer {

public Component getListCellRendererComponent(JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {

Component c = super.getListCellRendererComponent(
list,value,index,isSelected,cellHasFocus);

if (c instanceof JLabel && value instanceof File) {
JLabel l = (JLabel)c;
File f = (File)value;
l.setIcon(FileSystemView.getFileSystemView().getSystemIcon(f));
l.setText(f.getName());
l.setToolTipText(f.getAbsolutePath());
}

return c;
}
}

class ListTransferHandler extends TransferHandler {

private JList list;

ListTransferHandler(JList list) {
this.list = list;
}

@Override
public boolean canImport(TransferHandler.TransferSupport info) {
// we only import FileList
if (!info.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
return false;
}
return true;
}

@Override
public boolean importData(TransferHandler.TransferSupport info) {
if (!info.isDrop()) {
return false;
}

// Check for FileList flavor
if (!info.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
displayDropLocation("List doesn't accept a drop of this type.");
return false;
}

// Get the fileList that is being dropped.
Transferable t = info.getTransferable();
List<File> data;
try {
data = (List<File>)t.getTransferData(DataFlavor.javaFileListFlavor);
}
catch (Exception e) { return false; }
DefaultListModel model = (DefaultListModel) list.getModel();
for (Object file : data) {
model.addElement((File)file);
}
return true;
}

private void displayDropLocation(String string) {
System.out.println(string);
}
}

我最终使用了 GridBagLayout 并使用了这里的各种答案,感谢您的帮助!

在这个例子中我有很多额外的/未使用的东西,主要是因为我开始实现我需要的功能时我想我会在这里发布更新。不过应该仍然可以正常编译和运行。

我遇到的一个问题是,生成的 GUI 与按钮面板/放置区分隔线有点相互侵 eclipse 。最重要的是,有一个没有宽度的文本字段,尽管在我使用拆分 Pane 之前它工作得很好。如果有人知道如何解决这些错误,我将不胜感激!

import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.*;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

import java.awt.datatransfer.*;
import java.awt.event.*;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.io.*;

import javax.swing.*;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.border.TitledBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.filechooser.FileSystemView;
import javax.swing.text.*;
import java.util.*;
import java.nio.*;

public class TestGridBagLayout {
final static boolean shouldFill = true;
final static boolean shouldWeightX = true;
final static boolean RIGHT_TO_LEFT = false;

public static void addComponentsToPane(Container pane) {
if (RIGHT_TO_LEFT) {
pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
}
JButton clear;
JButton ok;
JLabel num;
JTextField input;
JSplitPane childSplitPane, parentSplitPane;
PrintStream ps;
JTextArea console;
JList<File> dropZone;
DefaultListModel listModel;

pane.setLayout(new GridBagLayout());

JPanel leftUpperPanel = new JPanel(new GridBagLayout());
leftUpperPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
GridBagConstraints c = new GridBagConstraints();
if (shouldFill) {
//natural height, maximum width
c.fill = GridBagConstraints.HORIZONTAL;
}

JFileChooser fc = new JFileChooser();;
fc.setMultiSelectionEnabled(true);
fc.setDragEnabled(true);
fc.setControlButtonsAreShown(false);
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);

c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 40; //make this component tall
c.weightx = 0.0;
c.gridwidth = 4;
c.gridx = 0;
c.gridy = 1;
leftUpperPanel.add(fc, c);

ok = new JButton("OK");
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 0; //reset to default
c.anchor = GridBagConstraints.PAGE_END; //bottom of space
c.insets = new Insets(10,0,0,0); //top padding
c.weightx = 0.5;
c.gridx = 0; //aligned with button 2
c.gridwidth = 1;
c.gridy = 2; //third row
leftUpperPanel.add(ok, c);

num = new JLabel("Word Count:");
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.PAGE_END;
c.insets = new Insets(10,0,0,0); //top padding
c.weightx = 0.25;
c.gridx = 1;
c.gridy = 2;
leftUpperPanel.add(num, c);

input = new JTextField("", 50);
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.PAGE_END;
c.insets = new Insets(10,0,0,0); //top padding
c.weightx = 0.25;
c.gridx = 2;
c.gridy = 2;
leftUpperPanel.add(input, c);

clear = new JButton("Clear All");
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 0;
c.anchor = GridBagConstraints.PAGE_END;
c.insets = new Insets(10,0,0,0); //top padding
c.weightx = 0.5;
c.gridx = 3;
c.gridy = 2;
leftUpperPanel.add(clear, c);

JScrollPane leftLowerPanel = new javax.swing.JScrollPane();
leftLowerPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));

listModel = new DefaultListModel();
dropZone = new JList(listModel);
dropZone.setCellRenderer(new FileCellRenderer());
dropZone.setTransferHandler(new ListTransferHandler(dropZone));
dropZone.setDragEnabled(true);
dropZone.setDropMode(javax.swing.DropMode.INSERT);
dropZone.setBorder(new TitledBorder("Selected files/folders"));
leftLowerPanel.setViewportView(new JScrollPane(dropZone));

childSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
leftUpperPanel, leftLowerPanel);
childSplitPane.setDividerLocation(400);
childSplitPane.setPreferredSize(new Dimension(480, 650));

console = new JTextArea();
console.setColumns(40);
console.setLineWrap(true);
console.setBorder(new TitledBorder("Console"));

parentSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
childSplitPane, console);
parentSplitPane.setDividerLocation(480);
parentSplitPane.setPreferredSize(new Dimension(800, 650));

pane.add(parentSplitPane);

}

public static void initUI() {

JFrame frame = new JFrame("GridBagLayoutDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

addComponentsToPane(frame.getContentPane());

//Display the window.
frame.pack();
frame.setVisible(true);
}

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
TestGridBagLayout testMultiplePanels = new TestGridBagLayout();
testMultiplePanels.initUI();

}
});
}

}

最佳答案

您可以首先使用 GridLayout 设置来显示两列和一行。这将作为垂直拆分的主要显示/容器/面板开始。然后您需要另一个 JPanel,可能需要一个 GridLayout 设置来显示一列和两行,这将显示文件选择器和放置区。

然后您可以将此面板和文本区域添加到主面板。

您也可以使用单个 GridBagLaout 来完成此操作,但您可能会发现使用复合 GridLayout 更容易。

参见 How to Use GridLayoutHow to Use GridBagLayout了解更多详情

关于java - 简单的 GUI 指导。我可以坚持使用 BorderLayout 还是需要其他东西?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27736295/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com